Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieving values from backwards relationship as a list of integers instead of list of tuples?
Right now I have a column named 'Value' in my 'Data' model, which has a ForeignKey from 'FOO' model: class FOO(models.Model): label = models.CharField(max_length=10, primary_key=True) ... class Data(models.Model): label = models.ForeignKey(Tickers, on_delete=models.CASCADE) Volume = models.FloatField(default=0) ... I'm fetching related objects as follows: v = FOO.objects.get(pk='something') vol = v.foo_set.values_list('Volume') and a get a list of tuples, which, afterwards, I have to convert to list integers with list comprehension. Is there a more elegant way to get a list of integers directly? Thanks -
Token based authentication not using JWT?
Whats a good practice for developing token based authentication for my app not using JWT? -
How to deserialize nested serializers with Django Rest Framework
i have in models.py class Variants(Model): class Meta: db_table = 'variants' id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=False, blank=False) created_at = models.DateField(auto_created=True, default=now, blank=True) updated_at = models.DateField(auto_now=True, null=True, blank=True) and class VariantOptions(Model): class Meta: db_table = 'variant_options' id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) variant = models.ForeignKey(Variants, on_delete=models.CASCADE, null=False, blank=False) created_at = models.DateField(auto_created=True, default=now, blank=True) updated_at = models.DateField(auto_now=True, null=True, blank=True) and in serializers.py class VariantOptionsSerializer(serializers.ModelSerializer): class Meta: model = models.VariantOptions fields = ['name'] class VariantsSerializer(serializers.ModelSerializer): options = VariantOptionsSerializer(many=True) class Meta: model = models.Variants fields = ['name','client','options'] def create(self, validated_data): options_data = validated_data.pop('options') variant = models.Variants.objects.create(**validated_data) for option_data in options_data: models.VariantOptions.objects.create(variant=variant, **option_data) return variant and my view class VariantsCreate(APIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.VariantsSerializer def post(self, request, format=None): serializer = serializers.VariantsSerializer(data=request.data) if serializer.is_valid(): saved = serializer.save() return Response(serializer.data) ==> serializer.data gives error return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i have this error Got AttributeError when attempting to get a value for field options on serializer VariantsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Variants instance. Original exception text was: 'Variants' object has no attribute 'options'. but the data has already been validated by the call to is_valid() … -
django and mysql - select distinct column with filters
suppose, I have a table with 3 columns: create table t1 (c1 int, c2 int, c3 int) i want to return a list of distinct values of c2 after applying filters on c1, c2 and c3 at the SQL level, I can do this easily: select distinct (c1) from t1 where c1=10 and c2>30 and c3 in (1,2,3) what is the best way to do so in django? I don't want to use .raw SQL since the filters are dynamic and it will be a nightmare to build the appropriate SQL query (there are more than 30 columns in the real table). is there a way to create a queryset with filters against all the table colums that will return only sub columns of the table? if so the distinct() would have worked Thanks for any tip Eyal -
Error: No UserDetails model is Created
I'm trying to reduce the image size before upload. I'm using default User model given by django & linking it to another model just to add few more things to the user profile. This is how models.py looks like, class UserDetails(models.Model): user = models.OneToOneField(User) profile = models.ImageField(upload_to='profile_image', blank=True) ... def save(self, *args, **kwargs): img = Image.open(self.profile) resize = img.resize((240, 240), Image.ANTIALIAS) new_image = BytesIO() resize.save(new_image, format=img.format) temp_name = self.profile.name self.profile.save(temp_name, content=ContentFile(new_image.getvalue()), save=False) super(UserDetails, self).save(*args, **kwargs) Problem is that when I'm signing up with fields username, first_name & password, it's not creating a UserDetails model along with that user. So, if I try to visit any user's profile it gives an error, no UserDetails model is present. If I remove the image compression code from the model & sign up again everything starts working perfectly fine. How can we fix that? Thank You . . . -
Django multiple databases - correct router class
I would like to use two databases in my application: local database external database in the first one I want to save all django tables , e.g auth_group To do this I tried to use router class, but unsuccessfully - it doesn't work. Below you can find my code Django 1.11 setings file: DATABASE_ROUTERS = ['mainApp.models.DefaultDBRouter','subfolder.newApp.models.testDBRouter',] models.py - main app - I want to use default DB for this model from __future__ import unicode_literals from django.db import models class list_a( models.Model ): region = models.CharField(max_length=50, verbose_name="Region") country = models.CharField(max_length=50, verbose_name="Country") def __unicode__(self): return str( self.country ) class DefaultDBRouter(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Reads go to a default. """ return "default" def db_for_write(self, model, **hints): """ Writes always go to default. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the default. """ db_list = ('default') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model=None, **hints): """ All non-micro-management models end up in this pool. """ return True models.py - test app - I want to use … -
Is possible to monitor a celery task in a django view without block the server
I have a long running task that I need to decouple from my normal django app. Is called from several clients, and wonder if is possible to give them the ilusion of a synchronous call, where the server take the job of monitor the job and return back when it finish. This mean, that I only need to offload the server and not need to worry about blocking the clients (this is already solved). @task def sync(): # A long process here... So, in my view is possible to do something like: def sync_database(request): while timeout(60): #Monitor task, if error or result: sleep(1) return sync.result without kill the performance? -
Why a call to a celery task block forever?
I follow the tutorial at http://docs.celeryproject.org/en/master/django/first-steps-with-django.html from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cobros.settings') app = Celery('cobros') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() # Settings CELERY_APP="cobros" CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE and call my first job: @task def add(x, y): logger.info("Sum ", x, y) return x + y def syncClientAsync(): baseDir = getBaseDir(str(cobrador.id)) print("Delay...") return add.delay(4, 4) #No work return add.delay(4, 4).get(timeout=1) #No work When I run the code python get stuck/blocked forever. Redis and Celery are running and not report any error or problem. -
Queryset contentype show fields name and values in template table
I got a view that receives a model and field the user passes via post (existing model and field inside the app of course) and makes a queryset filter on it, then i need to show in my template that result in a table (name fields must be the column headers) and their respective values. This what i got so far trying to serialize the queryset result in order to make it easier to show in template: Views.py: from django.contrib.contenttypes.models import ContentType class CommitteeReport(BaseView): template_name = 'committee/committee_report.html' def post(self, request, **kwargs): myfield = request.POST['field'].lower() my_model = request.POST['model'].lower() queryset_obj = ContentType.objects.get(model = my_model).model_class().objects.filter(**{myfield:True}) return render(request, self.template_name,{ 'requirements': queryset_obj, }) And my template: <div class="tab-pane active" id="tab_1"> <table class="datatable table table-striped table-hover" cellspacing="0"> <thead> <tr> {% for key in requirements %} <th>{{ key.fields }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in requirements %} <tr>{{ item.value }}</tr> {% endfor %} </tbody> </table> </div> Thing is, i don't get result or if i change the tag inside the termplate, i get the objects dictionary for every row. Any idea of how to achieve what i need ?, thanks in advance. -
NameError: name 'reload' is not defined python 3.6.4
After installing Xadmin, i encounter some problems. And there is my error details: [File "C:\Users\Harry\PycharmProjects\mxonline\lib\site-packages\xadmin\sites.py", line 9, in <module> reload(sys) NameError: name 'reload' is not defined]1 i've tried import importlib importlib.reload(sys) but it still doesn't work. i use python 3.6.4 -
Aldryn NewsBlog Designing a Template
The documentation for aldryn news-blog is very vague and i don't understand how to use articles. I'm trying to make a section page where each instance of an article creates a panel with the article's featured image and the name as the footer which will also be a button. Each article will create a new column. When there is 4 articles in a column, a new row will be started for the next article. I constantly receive the following errors when I adjust. Could not parse the remainder: '(loop.index,4)' from 'divisibleby(loop.index,4)' or for {% if loop.index|divisibleby 4 %} divisibleby requires 2 arguments, 1 provided How would I go about fixing this forloop and having it display. Django V- 1.8 {% load i18n staticfiles thumbnail cms_tags apphooks_config_tags %} {% extends "base.html" %} <div class="container"> <div class="row"> {% for article in article_list %} <div class="col-4"> <div class="panel panel-default"> <div class=panel-body> <img src="{% thumbnail article.featured_image 800x450 crop subject_location=article.featured_image.subject_location %}" alt="{{ article.featured_image.alt }}"> </div> <div class=panel-footer> <a href="{{ article.get_absolute_url }}" class="btn btn-light btn-lg btn-block aria-pressed=False label={{ article.slug_source.fieldname }}"> </div> {% if loop.index|divisiableby 4 %} </div> <div class="row"> {% endif %} {% endfor%} </div> </div> -
Django-Leaflet show custom layers on a form
I have two models, one that shows a marker(PointField) and one that generates PolygonFields. In my views, i can perfectly show all the data on a map. However, I would like to show the same data when creating a new geometry. Question is, how do I overlay the marker and the polygonField data as a layer in a form. models class MyPolygon(gis_models.Model): geom = gis_models.PolygonField() objects = gis_models.GeoManager() class MyPoints(gis_models.Model): geom = gis_models.PolygonField() objects = gis_models.GeoManager() views class PolygonCreateView(CreateView): form_class = PolygonForm template_name = 'applications/create_polygon.html' success_url = '/applications/polygon' def view_polygon(request): polygons= ReserveAirspace.objects.all() return render(request, 'applications/polygons.html',{'polygons':polygons}) same applies to the points. html {{form.geom}} How do i add all the existing polygons and points to the form field above in the template??? -
Django ManyToManyField that only works one way
I have my models set up as follows: class Product(models.Model): related_products = models.ManyToManyField('self', blank=True, related_name='related_products') As you can see, the relation is to itself. Now, lets say I have 3 products in my database: A, B, C. Product B's related product is Product C. Now, if I add Product B to the related product for product A, then Product B's related product changes from C to A, C. I don't want this, I want the change to only go one way. If I add B to A's related products, then B's related product won't change. Hope this is clear. How can I do this? Thanks! -
how o make django-autocomplete light return selected text not id
I have a simple form which lets a user select his country, state and district and redisplays the selected data. Everything works as expected apart from the fact that what is displayed is not the "text" but "ids" of the selected data. Expectation: You belong to India, Punjab, Jalandhar. Me too. ;) Output: You belong to 1, 2, 4. Me too. ;) # my form class MyInfoForm(forms.Form): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ListSelect2( url='country-autocomplete', ) ) state = forms.ModelChoiceField( queryset=State.objects.all(), widget=autocomplete.ListSelect2( url='state-autocomplete', forward=(forward.Field('country'),) ) ) district = forms.ModelChoiceField( queryset=District.objects.all(), widget=autocomplete.ListSelect2( url='district-autocomplete', forward=(forward.Field('state'),) ) ) # my view which handles MyInfoForm class CountryView(FormView): template_name = 'home.html' form_class = MyInfoForm success_url = '/thanks/' def form_valid(self, form): print("Request :", self.request.POST) country = self.request.POST["country"] state = self.request.POST["state"] district = self.request.POST["district"] msg = "You belong to {country}, {state}, {district}. Me too. ;)".format( country=country, state=state, district=district) return HttpResponse(msg) # other auto-complete views (similar to official tutorials) class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Country.objects.none() qs = Country.objects.all() if self.q: qs = qs.filter(country_name__istartswith=self.q) return qs class StateAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return State.objects.none() qs = State.objects.all() country = self.forwarded.get('country', None) if country: qs = … -
Implementing the custom permissions from the Django REST framework tutorial
I'm following the Django REST framework tutorial (part 4) but I'm observing a discrepancy between the behavior of my API and what is expected according to the tutorial. Here is my project-level urls.py: from django.contrib import admin from django.urls import path, include from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path('admin/', admin.site.urls), path('users/', views.UserList.as_view()), path('users/<int:pk>/', views.UserDetail.as_view()), path('', include('snippets.urls')) ] urlpatterns += [ path('api-auth/', include('rest_framework.urls')) ] and here is the included snippets.urls: from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path('snippets/', views.SnippetList.as_view()), path('snippets/<int:pk>/', views.SnippetDetail.as_view()) ] urlpatterns = format_suffix_patterns(urlpatterns) I've created a permissions.py with a custom permission class IsOwnerOrReadOnly: from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user and I've added this class to permission_classes in the SnippetDetail class in views.py: from django.contrib.auth.models import User from snippets.models import Snippet from snippets.serializers import SnippetSerializer, UserSerializer from rest_framework … -
How to deserialize data from multiple sources for one model using DRF?
I am transitioning some data over to use DRF. I have a POST endpoint that takes a JSON payload, parses relevant fields, and creates multiple objects out of that data. Each subsequent object created also relies on the previous object created (see example below). I am trying to figure out how to accomplish below, using DRF to deserialize data. It doesn't exactly have to be modeled like the code below, but I need the same end result. def job_start(request, plat_name="other", script_version="1"): a_product, created = Product.objects.get_or_create(name="Mobile") a_platform, created = Platform.objects.get_or_create(name=plat_name) tool, created = Tool.objects.get_or_create( product=a_product, platform=a_platform, url=jenkins_dump.url) job, created = Job.objects.get_or_create(name=jenkins_dump.job_name, tool=tool) job_in_progress, _ = Status.objects.get_or_create(name="IN_PROGRESS") start_time_raw = datetime.fromtimestamp(jenkins_dump.start_time / 1000) job_execution = JobExecution.objects.create(build_id=jenkins_dump.execution_number, job=job, time_start=start_time_raw, status=job_in_progress, pipeline_script_version=script_version) # what I want to do # serializer = ProductSerializer(request.data) # if serializer.is_valid(): # serializer.save() # serializer = ToolSerializer(request.data) # if serializer.is_valid(): # serializer.save() I'm wondering how I can serialize all these values and then when I create an object, append it to the serialized data, then pass that serialized data to the next object serializer, etc. -
Django. Comparing the model fields before saving for the admin panel
I'm new to Django and I have a question (Yes, yes, I was looking for and did't find ...). There are two models: class CounterDetail(models.Model): counter = models.ForeignKey(Counter, on_delete=models.CASCADE) date_placing = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) verifying_period_mounts = models.IntegerField(blank=False, null=False) and class Detail(models.Model): counterdetail = models.ForeignKey(CounterDetail, on_delete=models.CASCADE) date_last_verification = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) date_obxoda = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) How to implement the check when adding an entry to the second model through the admin panel: field date_obxoda = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False)more then date_placing = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) from another model. Please give an example, thank you. -
Comment form in django didn't save the new comments
I have a little problem. I'v create a new form for comments the articles on website. When I add the new comment from django admin everythink works ok, but when I try to add the new comment directly from detail page nothings happen and I'am redirecting to the page with list of articles. here are my files models.py: class Komentarz(models.Model): post = models.ForeignKey(Wpisy, related_name="komentarze", verbose_name="Komentarze do artykułu", on_delete=models.CASCADE) name = models.CharField(max_length=80, verbose_name="Imię") email = models.EmailField(verbose_name="Email") content = models.TextField(verbose_name="Treść komentarza") created_date = models.DateTimeField(verbose_name="Utworzono", auto_now_add=True) active = models.BooleanField(verbose_name="Aktywny?", default=True) class Meta: ordering = ('created_date',) verbose_name="Komentarz" verbose_name_plural="Komentarze" def __str__(self): return 'Komentarz dodany przez {} dla strony {}'.format(self.name, self.post) vies.py with the function of details from django.shortcuts import render, get_object_or_404 from .models import Wpisy, Komentarz from .forms import KomentarzeForma .... def detale_bajki(request, slug, ): detale_bajki = get_object_or_404(Wpisy, slug=slug) komentarze = detale_bajki.komentarze.filter(active=True) if request.method == 'POST': formularz_komentarza = KomentarzeForma(data=request.POST) if formularz_komentarza.is_valid(): nowy_komentarz = formularz_komentarza.save(commit=False) nowy_komentarz.detale_bajki = detale_bajki nowy_komentarz.save() else: formularz_komentarza = KomentarzeForma() return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki, 'komentarze': komentarze, 'formularz_komentarza': formularz_komentarza}) forms.py from .models import Komentarz from django import forms class KomentarzeForma(forms.ModelForm): class Meta: model = Komentarz fields = ('name', 'email', 'content') and detail.html ... {% with komentarze.count as total_komentarze %} <h2> {{ total_komentarze }} … -
Django server crashes when accessing webcam with opencv
so I found out that everything works fine when I remove cv2.imshow("Face",img) from the code but when it is used the server crashes due to some reason, the code runs perfectly when run as a plain script excluding django code. Can anyone tell me why is this happening and the possible solution? thanks from django.shortcuts import render, redirect import cv2 import numpy as np from settings import BASE_DIR def index(request): return render(request, 'index.html') def create_dataset(request): userId = request.POST['userId'] faceDetect = cv2.CascadeClassifier(BASE_DIR+'/ml/haarcascade_frontalface_default.xml') cam = cv2.VideoCapture(0) id = userId sampleNum = 0 while(True): ret, img = cam.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceDetect.detectMultiScale(gray, 1.3, 5) for(x,y,w,h) in faces: sampleNum = sampleNum+1 cv2.imwrite(BASE_DIR+'/ml/dataset/user.'+str(id)+'.'+str(sampleNum)+'.jpg', gray[y:y+h,x:x+w]) cv2.rectangle(img,(x,y),(x+w,y+h), (0,255,0), 2) cv2.waitKey(500) cv2.imshow("Face",img) cv2.waitKey(1) if(sampleNum>35): break cam.release() cv2.destroyAllWindows() return redirect('/') -
User registration using extra fields by extending AbstractUser
I asked something similar before, but people don't seem to understand what I ask or maybe I just don't understand, but I'm really trying to find a solution here. So I have a student model which extends AbstractUser like: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password') class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('phone', 'student_ID', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) photo = models.ImageField(upload_to='students_images') phone = models.CharField(max_length=15, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_student(sender, instance, created, **kwargs): if created: Student.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_student(sender, instance, **kwargs): instance.profile.save() And the expected output is this: I just don't know how the view is supposed to look like. I figured something in the past, but nothing would have been saved. I want that student will not be able to register unless he fills up all those fields: username, email, phone, student_ID etc. But also, I want that the fields of Student to be editable in database after the user is created by the form submission. I'm new to this, but I really need to … -
How to get pk of an instance of a django model before saving the instance
I am trying to upload an image using models.ImageField(upload_to=upload_location) def upload_location(instance,filename): print("%s/%s"%(instance.id,filename)) return "%s/%s"%(instance.id,filename) but its giving "GET /media/None/image_qacfEsv.jpg HTTP/1.1" I have tried using slug field it worked fine but neither id nor pk is working I want to use the obj ID to name the folder for image but its giving none here are my files def upload_location(instance,filename): print("%s/%s"%(instance.id,filename)) return "%s/%s"%(instance.id,filename) class Post(models.Model): draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False,auto_now_add=False) user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1) slug = models.SlugField(unique=True) title = models.CharField(max_length=120) image = models.ImageField(upload_to=upload_location, null=True,blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) -
Django dont show block tags properly
im using 2 apps. blog and contact. i included 2 block tags in my index.html. but i can only get one working at the same time. when im on my blog it wont show the contact one, when im on my contact it wont show the blog block. My Project: https://github.com/bibschxz/bibsch_project -
Reset a value in a model for all users each year - Django.
I am developing a Django application that tracks an employees holiday. I am not to sure how I would go about resetting the holiday each year at a specific date. Are there any good known solutions/libraries for how to do this? class User(models.Model): avatar = models.ImageField( default='images/avatars/profile.png', upload_to=user_directory_path) name = models.CharField(max_length=100) title = models.CharField(max_length=200, default="Employee") email = models.EmailField(max_length=254) present = models.BooleanField(default=False) code = models.CharField(max_length=4, unique=True) date_created = models.DateTimeField(auto_now_add=True) date_clocked = models.DateTimeField(default=timezone.now) total_holiday = models.DecimalField( default=28.0, decimal_places=1, max_digits=4) holiday_remaining = models.DecimalField( default=28.0, decimal_places=1, max_digits=4) My model is shown above I need to reset the remaining_holiday field on a admin user defined day each year. -
returning record count in django restful api
I have a very complex API that accepts different filter fields via POST request. the result is a list of items from the database. The total result set can be thousands of items if the user does not filter good. The API will be returning only 30 items but I want to add the total amount of items that satisfied the search conditions. I know that I can add a custom field in the Serializer class to return the count but I don't know how to access the queryset to query for the count(). I am sure there is a simple solution for this which I am missing Thanks Eyal -
Pass related object's field in Django ModelForm
I have a Django model class that extends the django.contrib.auth.models.User: class MyModel(models.Model): user = models.OneToOneField(User, models.CASCADE, unique=True) bio = models.TextField() date_of_birth = models.DateField() and out of this model I'm making a ModelForm: class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['bio', 'date_of_birth'] How can I tell the MyModelForm to take in the User's fields such as username, first_name, last_name? Example in the class Meta fields I can add ['bio', 'date_of_birth', 'user'] but that will just provide me with the dropdown to select to whom shall the MyModel in the MyModelForm be related to. Doing ['bio', 'date_of_birth', 'user.first_name'] throws an exception django.core.exceptions.FieldError: Unknown field(s) (user.first_name) specified for MyModel