What does it mean "to=" when creating model field in django? - django-models

Are those tree ways giving the same result/field, is there any other way?
class Message(models.Model):
user = models.ForeignKey(to=User)
user = models.ForeignKey(User)
user = models.ForeignKey("User")

Are those tree ways giving the same result/field
Yes, although the first requires to import a model named user, and is thus vulnerable to cyclic imports.
is there any other way?
The advised way is to make use of the settings.AUTH_USER_MODELĀ [Django-doc] to refer to the user model, than to use the User modelĀ [Django-doc] directly, so:
from django.conf import settings
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
For more information you can see the referencing the User model section of the documentation.

Related

Parsing JSON and save values to database in django

Am getting a post request from a ussd gateway. The post has a body in JSON format["phone":"07xxxxxx":"shortCode":"*100#":"text":"1"]
I need to parse this JSON,get individual values and save in django as a record. How do I go about this?
next time please provide some code with what you tried so far. It shows other guys, that you at least tried to figure it out yourself. The problem you have is well documented in the DRF Tutorial and pretty straight forward. As you are new here on SO I will show it to you, but next time please put some more effort in it before writing a question.
You need four things:
-model
-serializer
-url
-view
The model represents the way your database table is built up. Based on your json data it could look like this:
models.py
from django.db import models
class ExampleModel(models.Model):
phone = models.CharField(max_length=10) # There are third party fields like django-phonenumber-field
shortCode = models.CharField(max_length=10)
text = models.CharField(max_length=50)
Then you need a serializer to handle your incoming json data and validate them. Create a serialzers.py file. In this example we use modelserializer, but there are some more like hyperlinkedmodelserializer or the serializer baseclass to create a fully custom serializer. For your purpose the modelserializer is a good way to go.
serializers.py
from rest_framework import serializers
from .models import ExampleModel
class ExampleModelSerializer(serializers.Modelserializer):
class Meta:
model = ExampleModel
fields = '__all__'
Now we need a view. For your use case you need a view that handles the post request. I will use the generics.CreateAPIView. There is a lot that goes under the hood. You should do the tutorial to understand how you get from the APIView to the generic Views. Keep in mind that the CreateAPIView only handles the creation of new items. There are more generic views to handle list, retrieve, update and so on.
views.py
from rest_framework import generics
from .serializers import ExampleModelSerializer
class MyCreateView(generics.CreateAPIView):
serializer_class = ExampleModelSerializer
The last thing you have to do is to define a url path.
urls.py
from django.urls import path
from yourappname import views
urlpatterns = [
path('example/', views.MyCreateView.as_view()),
]
All of the things I wrote are covered in the tutorial.In the future, if something is not working and you could not solve it, provide a short example and you will find people to help you. But they won't write the entire code for you like I did this time. The reason I did it was that you are new and it was pretty straight forward to write it down. Good luck for you project.

Django, relate User with another table

So I got the tables you can see in the image below:
.
What I would like to do is to create a relationship so that each user (of django auth_user) will be enrolled(or able to enrol) to exactly one "course" so that he will be able to see next events for his modules.
Do I have to create another table and place 2 foreign keys or this is a way to do it in 'php' and it's more simple with Django? I was suggested to create 'student' model inheriting from 'User' with extended behavior and one to many relationship on auth. I tried to do that but unfortunately had not results since I'm really new to Django & Python.
If every auth_user (or auth.User) will be or have the opportunity to be enrolled on a course I would create a 'user profile' model that has a 1-to-1 relationship with the django User model. You can store additional User data in this model, including what course they are enrolled on. See https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model for more details but here is an example:
class UserProfile(models.Model):
user = models.OneToOneField('auth.User')
course = models.ForeignKey('courseapp.Course', null=True)
You would probably need to create a signal that gets fired each time an auth.User object is saved, such that if it is the first time that User object has been saved, it automatically creates the UserProfile:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from yourusersapp.models import UserProfile
def create_user_profile(sender, instance, created, **kwargs):
# Automatically creates a UserProfile on User creation.
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
When you query a User object, you can then reference the User object's profile like:
user_object.userprofile
You could then create a Course object and link the user_object indirectly via its UserProfile to that Course:
course = Course.objects.create(name='course_name', next_field='whatever')
user_profile = user_object.userprofile
userprofile.course = course
userprofile.save()
Now you have a user object with a UserProfile that is linked to only 1 course. Many users can be on the same course, but a user can only be on 1 course. You can also reference all users on a particular course like:
course = Course.objects.get(name='course_name')
course_users = course.userprofile_set.all()
HTH
I think that you can go about this one of two ways.
Extend the User model. 'Student' would probably be a good name for your new model. It would have a OneToOne relationship with 'User', and a ForeignKey relationship with 'Course'. It can store any other information that is applicable to students only. Documentation for how to do that can be found here https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#extending-the-existing-user-model
Create a custom User model that has a ForeignKey relationship with Course. This approach is a bit more complicated, but yields a slightly cleaner end result. Documentation for that is here. https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#substituting-a-custom-user-model
Sorry if it seems like I'm just sending you to the Django docs, but both of those sections are well written and should explain things pretty clearly. If you'd like to post another question with example code we can try and see why your original attempt at extending the User model didn't work. By the way, your "Student" model shouldn't have to inherit from the User model in order to extend it.

Django ownership foreign key to User or UserExtenstion

I'm quite new with Django, and so far I have a pretty basic setup where I attach an extra model to the default User model from (django.contrib.auth.models). In my accounts.models.py I have something in the line of:
class UserExtension(models.Model):
user = models.OneToOneField(User, primary_key=True)
# more code
I also have another model which needs to be specified an owner. My question is: Which is the better (more django-ish, more readable, more efficient, more flexible) way to signify the owner:
class Owned(models.Model):
# code
owner = models.ForeignKey(User)
# more code
or:
class Owned(models.Model)
# code
owner = models.ForeignKey(UserExtension)
# more code
I'll really appreciate if you mention pros and cons of those approaches.
I'd recommend the first option. The user model is the nontrivial model in the sense that an owned object should not be able to exist without a user, but could exist without a UserExtension.
Also consider that in Django 1.5 you are able to create custom user model, eliminating the need for the UserExtension class. See the documentation for more information.
Consider using UserProfile for any per user add-on information. Check out this blog to see how to do it. Then you can be assured that you are creating UserProfile object every time you create the User.
Now whether you FK on User or UserProfile depends logically on what you are doing within Owned. If Owned works with User's data/field, FK on User; if it works with UserProfile's data, FK on UserProfile.

Elegant way to store anonymous users with nick names in django?

I have a simple Post model in my django app:
class Post(models.Model):
category = models.CharField(max_length=10, choices=choices)
message = models.CharField(max_length=500)
user = models.ForeignKey(User, editable=False)
I'd like to implement the feature of having anonymous users create posts with nick names. Unfortunately django doesn't allow you to save an instance of AnonymousUser as a foreignkey to the Post class.
I was thinking of adding a "dummy" user record into the db that represents the anonymous user(id=0, or some negative number if possible) that would be used for all posts without a user. And if it is present a nullable name field would be used to represent the nickname of the anonymous user.
This solution seems a bit hacky to me. Is there any cleaner more effecient solution?
If you can identify new users by some session information, you could just create normal user accounts, pro forma so to speak - with a flag to identify them as volatile (this may lead to some regular maintenance cleanup).
If, during session lifetime, the user actually want to register, you can reuse the user account on your side and the user can keep all his data on his.
As #slacy commented and #Dominique answered; instead of rolling your own take a look at existing projects, e.g. this:
http://www.stereoplex.com/blog/introducing-django-lazysignup
Not tested , but this can help:
https://github.com/danfairs/django-lazysignup
You can add blank=True and null=True to User ForeignKey and set it to None, if user is anonymous. You just need to store the nickname somewhere.
I am new to Django. A friend told me not to use ForeignKey further stating that using CharField is ok. ForeignKey is slower than CharField, as it has some check for user info.

Django model defining list of URLFields

I'm pretty new to relational databases and this may be why I'm having this problem but I have a model - Post.
I want it to have variable number of URLs, however Django only seems to have the OneToManyField which requires a model (not a field - which URLField is).
In relational database design, the fields in a table are always scalar values. in your case, such a field would 'a url'. The way you get a collection to apply to a row, you join that row with the rows of another table. In django parlance, that would mean that you need two models, one for the Post objects, and another that links multiple urls with that post.
class Post(models.Model):
pass
class Url(models.Model):
url = models.URLField()
post = models.ForeignKey(Post)
myPost = Post.objects.all().get()
for url in myPost.url_set.all():
doSomething(url.url)
Now you can access urls through a urls member
But if you want to get the admin page for Post to also let you add urls, you need to do some tricks with InlineModelAdmin.
from django.db import models
from django.contrib import admin
class Post(models.Model):
pass
class Url(models.Model):
url = models.URLField()
post = models.ForeignKey(Post)
class UrlAdmin(admin.TabularInline):
model = Url
class PostAdmin(admin.ModelAdmin):
inlines = [UrlAdmin]
admin.site.register(Post, PostAdmin)

Resources