Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get maximum value of each day in month using django queryset
Let's assume I have Model, Products and I have 100k records. Now I want to pass month 2022-01-01 and get maximum price of each day of the passed month. Product Model id price date 1. 33.33 2022-01-01 2. 93.33 2022-01-01 3. 64.33 2022-01-02 4. 34.33 2022-01-02 . . . 101. 43.33 2022-01-29 102. 74.33 2022-01-30 103. 36.33 2022-01-30 Expecting Result 93.33 64.33 . . . 43.33 74.33 I just want queryset. Kindly try avoid loop. -
G Suite - django social auth redirecting to accounts/login
I have configured social-auth-django for my project. And in G suite, I have done all the setup for third party SAML authentication (SSO). The problem is after completing the Google authentication it is redirecting to accounts/login/ instead of the configured redirect URL. # Social Auth settings AUTHENTICATION_BACKENDS = [ 'social_core.backends.saml.SAMLAuth', 'django.contrib.auth.backends.ModelBackend', 'users.auth.backend.CaseInsensitiveModelBackend', ] SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'https://example.com/home' # Overriding pipeline to skip user auto registration # since we have automatic user provisioning enabled SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) Package verions: social-auth-app-django==5.0.0 social-auth-core==4.1.0 python3-saml==1.12.0 Django==3.0.5 Anyone have any idea on this? Thank you -
Update a field but do not replace the old one in django rest framework
I have a barcode field in a model. While updating i do not want to replace with old one instead i want to add the new one and keep the old one also and while getting the data latest one will be visible. For example barcode contains B001 in that model and i updated with B002. So it will not replace B001. It will keep both B001 and B002. I am really curious how to achieve this. Any help would be really appreciated. -
I can't login with facebook after in django
After i hosted my app in heroku when i click on login with facebook it throws me an error saying: ProgrammingError at /oauth/complete/facebook/ relation "social_auth_usersocialauth" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "social_au... Request Method: GET Request URL: https://zu4.herokuapp.com/oauth/complete/facebook/? granted_scopes=public_profile&denied_scopes&code=AQBjAKGr1DmC3xKRUcPBZw8t_aS77an_AmwYItJ- qCQyhEjxnxTmnwLNNLISHIGhOlV9LMCRX72- YjBt7Oiaa3zRO56QTqpQZVHL_3OwF6xQMbDOsc0_S8XvogqboLykuQ7O2P7_jtlnV1g4wqZ0Ktlg7feUsQMeWzNwILpHfcdVx9ZAVkB-qamP42ae0iN3mKePBdoIIaD_4ES_0aEhlS47VDXKHRFTmBnyWNpr1J6oWtVby184FTXvY3X7nxzIvhDVFrueCdAoJ8MhxU- nFiPdzfHMwBcyoaNq67a564MdadIMledAFbDdvq0vfG6xuA15X5HVGq9nIyocGBjmtRZBeQc25nNCmXLhDOFq9a- bJBzGQIsFSvahjHQxV2lnNFY&state=oqiCjnfkDTr208JjRHj2mBUdpgVMsPnZ Django Version: 4.0 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', #Scial liogin Module 'social_django', #My App Module 'itouch', #Bootstrap Module 'bootstrap5', #cloudinary Module 'cloudinary', ] Any help please ? -
javascript afterprint event works once
I need to carry out my own procedure after calling up the print function of the browser. The only problem is that it only runs it once. I'm using JQuery and Sweetalert2. Below is the source code: window.onafterprint = function () { location.href = '{% url 'logout_' %}'; } Swal.fire({ title: 'Example', showDenyButton: true, showCancelButton: true, confirmButtonText: 'Yes', confirmButtonColor: 'green', denyButtonText: 'No', cancelButtonText: 'Cancel' }).then((result) => { if (result.isConfirmed) { flPrint = true; } else if (result.isDenied) { flPrint = false; } if ((result.isConfirmed) || (result.isDenied)) { $.ajax({ url: '{% url 'ajax-view' %}', dataType: 'json', contentType: "application/json", type: 'GET', success: function (r) { if (r.result) { if (flPrint) { window.print(); } else { location.href = '{% url 'logout_' %}'; } } }, error: function (err) { console.log(err); } }); } }) What can I do to make the afterprint() event always run? Thanks. -
convert oracel query into django
Query: select t1.a, t2.b, t3.c, t2.f from t1 t2 t3 where t1.b=t2.c and t1.c=t3.a and t2.b=t3.c t1, t2, t3, t4 represent tables a,b,c are values -
Running heroku local results in SyntaxError: invalid syntax
When I run heroku local in terminal it throws this error: 22:01:24 web.1 | File "manage.py", line 17 22:01:24 web.1 | ) from exc 22:01:24 web.1 | ^ 22:01:24 web.1 | SyntaxError: invalid syntax [DONE] Killing all processes with signal SIGINT 22:01:24 web.1 Exited with exit code null I am following this tutorial. Not sure if it helps but here is my Procfile contents: web: python manage.py runserver 0.0.0.0:$PORT My Python version is 3.9.9 -
How do i fix Exception Type:OperationalError Exception Value:no such table: home_user
from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils.html import escape, mark_safe from embed_video.fields import EmbedVideoField class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, first_name, password, **other_fields): other_fields.setdefault('is_teacher', True) other_fields.setdefault('is_learner', True) other_fields.setdefault('is_admin', True) if other_fields.get('is_teacher') is not True: raise ValueError( 'admin must be assigned to is_teacher=True.') if other_fields.get('is_learner') is not True: raise ValueError( 'admin must be assigned to is_learner=True.') return self.create_user(email, user_name, first_name, password, **other_fields) def create_user(self, email, user_name, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True,default="") first_name = models.CharField(max_length=150, blank=True) about = models.TextField(( 'about'), max_length=500, blank=True) is_learner = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] def str(self): return self.user_name Admin from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.forms import TextInput, Textarea from .models import User,Profile,Announcement,Course,Tutorial,Notes,Quiz,Answer,Learner,Instructor,TakenQuiz,LearnerAnswer class UserAdminConfig(UserAdmin): model = User search_fields = ('email', 'user_name', 'first_name',) list_filter = ('email', 'user_name', 'first_name', 'is_teacher', 'is_learner') ordering = ('-start_date',) list_display = ('email', 'user_name', 'first_name', 'is_teacher', 'is_learner') fieldsets = ( (None, {'fields': ('email', 'user_name', 'first_name',)}), … -
How can I do JavaScript ajax call on page onload and retrieve data from views in Django
I wish to pass localStorage data to Django views and display the return record on page template on page load. I think it can be done with Ajax, but I have no Idea how I can pass specific localStorage variable to Django views on specific pageload and display the record on template as regular templating(not ajax html return) For example: If I load abcd.com/test URL, I want to pass an array of ids or something of a Variable, and return views on template according to passed values. Is there any better way of achieving this ? I have tried this way but no luck: Javascript: <script> window.onload = function(){ var compare = localStorage.getItem("comparisionProducts"); var action_url =$this().window.location.href if (compare.value !== ''){ $.ajax({ url: action_url, type: "POST", data: {'compare_id': compare }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function (result) { console.log("Success") }, error: function () { alert("Please login"); } }); } }; <script> and My Views: def compare(request): if request.is_ajax() and request.POST and 'compare_id' in request.POST: data = Products.objects.filter(product_id = int(request.POST['compare_id'])) context={ 'product':product, } return render (request, './ecommerce/compare.html', context) -
Temporary model instances referenced as foreign keys
Is there a way to keep a Django model instance, which is referenced by foreign keys, in memory without storing it to the database? The code is part of an _add_ overload, but the way it is implemented now is very ugly as it is hard to keep track of the new instances, and it also produces a lot of unnecessary DB accesses. Ideally I want to keep the new instances temporary as long as the user does not call the save() method on the returned instance. When I uncomment the save() calls like below, the annotation instances are not referenced in the returned Sequence instance. class Sequence(models.Model): ... def __add__(self, other:'Sequence'): """ This enables you to use the + operator when dealing with Sequence objects :param other: :return: """ # concatenate the actual sequences sum_seq.sequence = self.sequence + other.sequence #sum_seq.save() len_self_seq = len(self.sequence) # annotations annot: SequenceAnnotation # copy the own anntotations for annot in self.annotations.all(): new_annot = deepcopy(annot) new_annot.id = None # this is crucial to actually create a new instance new_annot.ref_sequence = sum_seq #new_annot.save() if other_is_bioseq: # copy the other annotations, adjust the start and end positions for annot in other.annotations.all(): new_annot = deepcopy(annot) new_annot.id = None … -
How can I get a object for a specific user?
I'm trying to display all the Books issued by a user. In my views im trying to get the IssueBook model's objects (only with the current user), The Book is just working fine, having trouble with IssueBook model- views.py def booksIssued(request): issued = IssueBook.objects.filter(user=request.user) books = Book.objects.filter(issued=True, user=request.user) print(issued, books) context = { "books" : books, "issued" : issued } return render(request, 'books_issued.html', context) models.py class IssueBook(models.Model): name = models.CharField(max_length=400) classSection = models.CharField(max_length=10) rollno = models.PositiveIntegerField() issued_date = models.DateTimeField(auto_now_add=True) date = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return f"{self.book} issued by {self.name}" forms.py class issueBook(ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('usr') super(ModelForm, self).__init__(*args, **kwargs) self.fields['book'] = forms.ModelChoiceField(queryset=Book.objects.filter(user = user)) date = forms.DateTimeField(widget=forms.DateInput(attrs={'type':'date'})) class Meta: model = IssueBook fields = ['name', 'classSection', 'book', 'rollno', 'date'] -
Django odd behaviour
Whenever I start a project in Django, independently of the name of the app or project, and irrespective of any urls or settings configuration, upon running python manage.py runserver and navigating to 127.0.0.1 I get the following error: Not Found: /ball/ [10/Jan/2022 11:32:32] "GET /ball/ HTTP/1.1" 404 2337 and this displays in th browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ball/ Using the URLconf defined in ornaments.urls, Django tried these URL patterns, in this order: admin/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, ball/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Why is Django looking for a route called ball? Thanks. -
Mock async_task of Django-q
I'm using django-q and I'm currently working on adding tests using mock for my existing tasks. I could easily create tests for each task without depending on django-q but one of my task is calling another async_task. Here's an example: import requests from django_q.tasks import async_task task_a(): response = requests.get(url) # process response here if condition: async_task('task_b') task_b(): response = requests.get(another_url) And here's how I test them: import requests from .tasks import task_a from .mock_responses import task_a_response @mock.patch.object(requests, "get") @mock.patch("django_q.tasks.async_task") def test_async_task(self, mock_async_task, mock_task_a): mock_task_a.return_value.status_code = 200 mock_task_a.return_value.json.return_value = task_a_response mock_async_task.return_value = "12345" # execute the task task_a() self.assertTrue(mock_task_a.called) self.assertTrue(mock_async_task.called) I know for a fact that async_task returns the task ID, hence the line, mock_async_task.return_value = "12345". However, after running the test, mock_async_task returns False and the task is being added into the queue (I could see a bunch of 01:42:59 [Q] INFO Enqueued 1 from the server) which is what I'm trying to avoid. Is there any way to accomplish this? -
I am trying to register a staff in my database throuout the form But I get error
I have two models staff and UserAddress and I'm trying to add the staff through models. But I get this error: AttributeError at /accounts/signup/staff/ 'NoneType' object has no attribute 'add' What should I do now, Could some one help me? I wanted to register a staff but this thing happened. models.py: class UserAddress(models.Model): city = models.CharField(max_length=100) address = models.CharField(max_length=200) zip_code = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.id) class CustomUser(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) user_address = models.ForeignKey(UserAddress, on_delete=models.CASCADE, null=True) class Staff(CustomUser): def save(self, *args, **kwargs): if not self.id: self.is_staff = True self.is_superuser = False return super(Staff, self).save(*args, **kwargs) class Meta: proxy = True forms.py: class StaffCreationForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) email = forms.EmailField(required=True) city = forms.CharField(max_length=100) address = forms.CharField(max_length=100) zip_code = forms.CharField(max_length=15, required=True) class Meta(UserCreationForm.Meta): model = CustomUser @transaction.atomic def save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get("first_name") user.last_name = self.cleaned_data.get("last_name") user.email = self.cleaned_data.get("email") user.is_staff = True user.save() address = UserAddress.objects.create(city=self.cleaned_data.get("city"), address=self.cleaned_data.get("address"), zip_code=self.cleaned_data.get("zip_code")) user.user_address.add(address) return user views.py: class StaffSignUpView(CreateView): model = CustomUser form_class = StaffCreationForm template_name = "accounts/signup_user.html" def get_context_data(self, **kwargs): kwargs["user_type"] = "staff" return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect("home") -
sync_to_async problem with scrapy-django-dashboard
i want to use scrapy and django for scrape some date and i implemented it with scrapy-django-dashboard document well but when i run this commant: scrapy crawl post_spider -a id=1 -a do_action=yes i get this error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. this is my model.py class in django : @python_2_unicode_compatible class NewsWebsite(models.Model): name = models.CharField(max_length=200) url = models.URLField() scraper = models.ForeignKey( Scraper, blank=True, null=True, on_delete=models.SET_NULL) scraper_runtime = models.ForeignKey( SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name @python_2_unicode_compatible class Article(models.Model): title = models.CharField(max_length=200) # https://stackoverflow.com/a/44026807 news_website = models.ForeignKey( NewsWebsite, blank=True, null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True) url = models.URLField(blank=True) thumbnail = models.CharField(max_length=200, blank=True) checker_runtime = models.ForeignKey( SchedulerRuntime, blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.title class ArticleItem(DjangoItem): django_model = Article @receiver(pre_delete) def pre_delete_handler(sender, instance, using, **kwargs): if isinstance(instance, NewsWebsite): if instance.scraper_runtime: instance.scraper_runtime.delete() if isinstance(instance, Article): if instance.checker_runtime: instance.checker_runtime.delete() pre_delete.connect(pre_delete_handler) and this is my spider: class ArticleSpider(DjangoSpider): name = 'article_spider' def __init__(self, *args, **kwargs): self._set_ref_object(NewsWebsite, **kwargs) self.scraper = self.ref_object.scraper self.scrape_url = self.ref_object.url self.scheduler_runtime = self.ref_object.scraper_runtime self.scraped_obj_class = Article self.scraped_obj_item_class = ArticleItem super(ArticleSpider, self).__init__(self, *args, **kwargs) also this is my pipline: class DjangoWriterPipeline(object): def process_item(self, item, spider): if spider.conf['DO_ACTION']: try: item['news_website'] = spider.ref_object checker_rt = … -
"'str' object has no attribute 'get'" when passing slug to django form
I am attempting to pass a slug to a form, so that it can match user accounts with related groups (called 'events' in this project/context). The slug is an identifier for the event, which has several types of many-to-many connections to user-profiles (an extension to the standard django user model specifically made for connecting users to events). The form is supposed to create two drop-down choice fields to let an event manager set the permissions any other user has in the event, i.e. being a passive observer, an editor or a manager. However, as of now, django generates the error 'str' object has no attribute 'get' when rendering the page. The exception is located in django/forms/widgets.py in the function value_from_datadict, with the error being stated to be on line 0 in the base template base.dashboard.html, occurring during rendering. I've managed to avoid the error by removing both fields but leaving the slug and by removing both the candidate field and the slug, leaving the permissions field intact. I have also attempted to explicitly convert the passed value into a slug in the form (just in case some weird dynamic typing tripped the system up), but to no effect. What am … -
drf filter with related table count
Here is my model: class Artwork(models.Model): id = models.BigAutoField(primary_key = True) serial = models.IntegerField(choices=Serial.choices, default=100) title = models.CharField(max_length=255, blank=True, null=True) slug = models.CharField(max_length=255, blank=True, null=True) class Views(models.Model): id = models.BigAutoField(primary_key = True) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name="views") artwork = models.ForeignKey(Artwork, null=True, blank=True, on_delete=models.CASCADE, related_name="views") Here is my view class GetArtworkLiteView(viewsets.ModelViewSet): queryset = Artwork.objects.all() serializer_class = GetArtworkLiteSerializer filter_backends = [filters.OrderingFilter, DjangoFilterBackend] filterset_fields = ['slug'] ordering_fields = ["id", "serial"] Here i want to make ordering by count(views) in artwork model. How can i add logic to that so artwork model will sort by count of views i wants to implement this using django rest framework -
Django model second update statement not working
I am working on Django 3.2 and trying to make multiple updates to different records in the same function. The model that I have is as following class PlayerData(models.Model): id = models.AutoField(primary_key=True, blank=False, null=False) is_playing = models.IntegerField(blank=True, null=True) current_team_name = models.CharField(max_length=50, blank=True, null=True) current_team_id = models.IntegerField(blank=True, null=True) I need to set is_playing flag as false for everyone which belongs to certain team. Which I am doing like this PlayerData.player.filter(current_team_name__in=teamInfo).update(is_playing=0) This update works perfectly. Next I need to iterate a dictionary and get some values and update the records with those values which I am doing this way for player in playerObj: playerId = player['id'] playerTeamData = playerTeamInfo[playerId] PlayerData.player.filter(id=playerId)\ .update(current_team_name=playerTeamData.split(":::")[0], current_team_id=playerTeamData.split(":::")[1], is_playing=1) This update statement doesn't work, neither I get any error nor the DB is updated. I am not sure what I am doing wrong. Do I need add some sort of commit statement between two updates? -
Invalid HTTP_HOST header: 'subdomain.domain.com'. You may need to add 'subdomain.domain.com' to ALLOWED_HOSTS
after two days From deplyoing my application and working fine, I have decided to change the name of the subdomain so i have just rename it under the path: /etc/nginx/sites-available and then i have did again sudo certbot --nginx for the "https" , then adding this host in settings.py from my django application, I have did sudo systemctl restart nginx to restart nginx then: sudo systemctl restart gunicorn then python manage.py makemigrations -->No changes detected python manage.py migrate -->No changes detected and when i go to the browser to access to my application I got this error DisallowedHost at / Invalid HTTP_HOST header: 'subdomain.domain.com'. You may need to add 'subdomain.domain.com' to ALLOWED_HOSTS. , otherwise i Have added the host on "settings.py" Help please isn't there any other step i should do when i change the host ,Thanks in advance -
Can you import django-signal function to another django file?
I have imported a function in my Store Model to get some information after i save a file in django-admin. Looks like this: @receiver(post_save, sender=Store) def update_from_crawl(instance, **kwargs): import time import os info = { 'api_url': instance.api_url, 'access_key': instance.access_key, 'c_key': instance.consumer_key, 'c_secret': instance.consumer_secret, } time.sleep(2) os.system("python manage.py woocommerce") return info Now in my woocommerce.py (custom django-admin command script) after importing update_from_crawl update_from_crawl() shows update_from_crawl() missing 1 required positional argument: 'instance' In the woocommerce.py file i have this variable which checks for wcapi = API( url="", consumer_key="", consumer_secret="", version="wc/v3" ) And i would like to pass the info['api_url'], info['c_key'], info['c_secret'] into this file everytime a model is saved and automatically run it. Do you have any idea how to pass it? I've tried so many things but i cant figure it out:) Thanks in advance -
How to request.data multiple files from postman?
I am having a file field "documents" in which I want to add multiple files. But when I do documents = request.data('documents[]') I only get the last selected file. How can I get all the files as a list in documents variable. -
Should we use django authentication for all users of a site?
I have just started developing a bookstore site with Django and I have a question about user authentication. I want users to have a wallet, shopping cart and additional information for their account such as profile picture, phone number, address, etc. to buy books. And now I am faced with the dilemma of whether to change the User model itself, or create a Profiles model for each and link it to the User model, or create a separate model (in other words, the authentication system) and do everything from scratch. Now I have started building a separate authentication system. Everything was going well until I had problems in sending and receiving user data in the template contexets. Finally, in general, I want to know if Django authentication system is really suitable for all users of a site? -
Django, ImportError: cannot import name 'task' from 'celery'
I have Django application that was using Celery version 4.4.2, which was working fine. from celery import task import logging @task(ignore_result=True) def log_user_activity(user_id): try: logging.info(user_id) except Exception as e: logging.error(str(e)) As I tried to update the Celery version to v5.2.2 I get below error: ImportError: cannot import name 'task' from 'celery' Can someone help what is task been replaced with? they still have example here with same. https://github.com/celery/celery/blob/v5.2.2/examples/celery_http_gateway/tasks.py -
Filtering a Django model on an AutoField
I have a Django model that looks like this - class History(models.Model): testcaseidstring = models.AutoField(primary_key=True) # Field name made lowercase. I am storing String values in this field in the Database When I make a query on this field like - qs=qs.filter(testcaseidstring="tc123") I get an error saying "Field 'testcaseidstring' expected a number but got 'TC123'" How can I filter on this AutoField? Is converting that field to a TextField the only way to go? Any help would be highly appreciable Thanks!! -
You are trying to change the nullable field 'email' on customuser to non-nullable without a default
I have two models (UserAddress and CustomUser) in my models.py, the field user address in CustomUser was a many to many field but I decided to change it to a foreign key field. But when I ran python manage.py make migrations it asked me to choose a choice: what should I do: You are trying to change the nullable field 'email' on customuser to non-nullable without a default; we can't do that (the database needs something to populate exis ting rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous dat a migration) Quit, and let me add a default in models.py Here is my models.py file: class UserAddress(models.Model): city = models.CharField(max_length=100) address = models.CharField(max_length=200) zip_code = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.id) class CustomUser(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) user_address = models.ForeignKey(UserAddress, on_delete=models.CASCADE)