Autofill Models in Django - python

What I'm trying to implement is an invite system while I develop my website, but I'm new to how Django works.
For now, I want to be able to create a random string in the admin panel, have those added to the database, and then be required for a user to register. Eventually I want to create a user group system on the front end website where I can generate the strings there versus the admin panel, and then be able to send them out that way, but I'll get to that later.
I have the Model showing successfully in the admin panel, but I don't know how to make a text field that's automatically filled out anytime I create a new one and have the string be random each time.
class randomString(models.Model):
name = models.CharField(max_length=200)
random = models.ManyToManyField(get_random_string(length=6))
This is my current code which is throwing out an error, but I assumed that it would, I did it this way just to check and see if it was this simple. I have found out that it's not.

You can simply use an UUID:
from uuid import uuid4
class randomString(models.Model):
name = models.CharField(max_length=200)
random = models.UUIDField(unique=True, default=uuid4)
If the UUID is too long, you can generate a shorter string:
def generate_random():
from django.utils.crypto import get_random_string
return get_random_string(length=11)
class randomString(models.Model):
name = models.CharField(max_length=200)
random = models.CharField(default=generate_random, max_length=11, unique=True)

Related

Django create ManytoOne relation in one form

I am trying to develop a form where the user would be able to achieve this :
Database
So the form would have :
a TextField for the name
a TextField for the description
a TextField for the addresses that would be entered by the User as a list
According to you, what would be the most appropriate approach to do so?
Thank you very much !
from django.db import models
class Address(models.Model):
address = models.TextField()
class UserModel(models.Model):
user = models.CharField(max_length=255, required=True)
description = models.TextField()
addresses = models.ManyToMany(Address)
You can create the models and integrate them by the above code. One user can set multiple addresses to him, on the other side, one address can be assigned into many users. so Many To Many relationships can be fruitful to this scenario.

How to put two different model's uuid and id in a same url?

I have two different model linked by a ForeignKey one contains a certain uuid and the other has a certain id. I'd like to be able to put these in the same URL.
Here's the models.py :
class Creation(models.Model):
...
uuid = models.UUIDField(default=uuid.uuid4, unique=True)
class User(models.Model):
...
creation = models.ForeignKey(Creation, null=True)
Here's what the URL pattern should look like :
url(r'^edit/(?P<id>\d+)/(?P<uuid>[^/]+)/$', views.edit, name='edit'),
Views.py
def edit(request, id, uuid):
user_uuid = User.objects.filter(id=id)
user = get_object_or_404(User, id=id, uuid=user_uuid.creation.uuid)
As you can see the view function doesn't make any sense since I don't see how what I'm trying to do should work but the User should be the id in the URL and the Creation should be the uuid since each user can have many Creations.
How can I achieve this?
Your question is quite hard to understand, but I think what you want is:
user = User.objects.get(id=id)
creation = user.creation_set.filter(uuid=uuid)
Note of course though that since uuid is unique, there's no need to use the User ID in the query at all; you could drop it from the URL altogether, use just the uuid to get the Creation, then get the user via creation.user.

django admin, displaying all instances of a model1 associated with model2 on model2's change page?

Consider these two models Keyword and Statement (model1 and model2 respectively):
#python_2_unicode_compatible
class Keyword(models.Model):
word = models.CharField(max_length=200)
statement = models.ManyToManyField(Statement)
def __str__(self):
return self.word
#python_2_unicode_compatible
class Statement(models.Model):
statement_id = models.CharField(max_length=200)
title = models.CharField(max_length=200)
issue_date = models.DateField("Issue-Date")
author = models.ForeignKey(Person)
released_by = models.ForeignKey(Organization)
kicpairs = models.ManyToManyField('KeywordInContext')
So on the admin site right now, the only way one would be able to determine what keywords are associated with each statement is that they have to go check the Keyword model in admin, and check each Keyword's display page and scroll through the menu.
At least with regards to the admin site, it's important for someone to be able to see a Statement model's display with all of its associated Keywords visible, and for users to be able to choose additional Keywords within the database (or make new ones). I also hope to be able to have a Statement's keywords modifiable on the admin page via the filter_horizontal widget, since that seems to be the most user friendly.
But I'm having trouble just starting with that. I'm not sure what I need to use or how.

Foreign key use with user model upload

These are my models and one user can upload multiple videos but one video belongs only to one user. How do I use the foreign key concept over here? When I add a user, does this automatically add a username in the Video model? If not, how do I do that? I'm very new to django over here
class User(models.Model):
first_name=models.CharField(max_length=20)
last_name=models.CharField(max_length=20)
username=models.CharField(max_length=25, primary_key=True)
password=models.CharField(max_length=15)
email_id=models.CharField(max_length=30, default='NULL')
profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',default='')
def __str__(self):
return self.username
class Video(models.Model):
username=models.ForeignKey(User,on_delete=models.CASCADE,default="")
video=models.FileField(upload_to='videos/%Y/%m/%d/',default='')
videotitle=models.CharField(max_length=100)
likes=models.PositiveIntegerField(default=0)
dislikes=models.PositiveIntegerField(default=0)
def __str__(self):
return self.video
Try the following
from django.db import models
from django.conf import settings
class Video(models.Model):
...
username = models.ForeignKey(settings.AUTH_USER_MODEL)
Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active User model – the custom User model if one is specified, or User otherwise.
More info can be found here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#referencing-the-user-model
Not, it won't do it automatically -- and how would it do that. You need to pass user. Also you definitely don't want to add a username, but a reference to a User object. This is misleading in the code as you have a "username" in the Video class, which acutally is not just a name (string), but a ForeignKey -- a reference to an object User when adding the new video. So what you need to do when adding a video is something along the lines of:
def add_new_video(username, filename, title):
owner = User.objects.get(username=username)
newvid = Video(username=owner, video=filename, videotitle=title)
newvid.save()
assuming that likes and dislikes will be added later on...

Resolve circular import issue

I am creating an app using Flask with MongoEngine to connect to MongoDB.
My folder structure looks like this:
app/
__init__.py
mod_users/
__init__.py
constants.py
forms.py
models.py
views.py
mod_games/
__init__.py
constants.py
forms.py
models.py
views.py
Let's say my User and Game models are like the following:
mod_users/models.py
class User(db.Document):
email = db.EmailField()
username = db.StringField()
password = db.StringField()
mod_games/models.py
from app.mod_users.models import User
class Game(db.Document):
title = db.StringField()
creator = db.ReferenceField(User, reverse_delete_rule=db.CASCADE)
likes_count = db.IntField()
Now, my problem is that I would like the User to have a list of the game he likes. But I cannot use a reference field because I would have to import Game which would create a circular import.
This won't work:
from app.mod_games.models import Game
class User(db.Document):
email = db.EmailField()
username = db.StringField()
password = db.StringField()
liked_games = db.ListField(
db.ReferenceField(Game, reverse_delete_rule=db.PULL)
)
I thought about storing in every game a list of users who liked it, and then adding a static method in Game that would retrieve
a list of liked Game for a given user, but that doesn't seem to be a clean and efficient way to resolve this.
Although you have an answer - MongoEngine does cater for this as you can pass the string name of the class to a reference field eg:
class User(db.Document):
email = db.EmailField()
username = db.StringField()
password = db.StringField()
liked_games = db.ListField(
db.ReferenceField('Game', reverse_delete_rule=db.PULL)
)
M:N relationships to be modelled via Association class
Game and User have a relationship, where one Game can be liked by any number of Users and one User can like any number of Games.
This is typical M:N relationship, and this is to be modelled by an association class (take it as class modelling rule).
The class should have:
reference to User
reference to Game
any additional properties of this particular relationship, e.g. how many stars the use gave to this game.
The tuple User - Game must be unique.
When defining this type of class, you import from User and from Game module.
User and Game shall not import this association class (otherwise you would enter into circular references problem again)
As it was mentioned before you can pass a string name of a model to a reference field. That is the first thing you should do to avoid circular imports:
class User(db.Document):
company = db.ReferenceField('Company')
But when you have a method that uses some model, let's say, to aggregate some data, this way above doesn't helps - you still may get an circular imports issue. To resolve this try get_document function. See example below.
from mongoengine.base.common import get_document as get_model
class User(db.Document):
# fields definition omitted
def get_games(self):
Game = get_model('Game')
games = Game.objects.filter(user=self.pk)
# some code here

Categories