Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Correct way to close down RabbitMQ and Celery?
I'm using Django to call a Selenium script through Celery and RabbitMQ as a message broker. The problem I'm having is often changes I make to my Selenium script aren't actually changing anything when I rerun my Django server. It sounds weird but I feel like something is still using my old code, not the one with the changes I make. My guess is that this is something to do with RabbitMQ being kept running while I make changes to my Selenium script? Do I need to 'refresh' it somehow each time I make changes or re-start the process? Also, I just ctrl+C to close everything when I'm finished, is there a 'proper' way to close down each time? -
Save customer in the background on django forms
Hi I am trying to automatically save the customer on post without having to list it in the forms. It currently shows the drop down and saves correctly but if I remove customer from forms.py it doesn't save anymore. I think I need to add something in the views but not sure what I am missing? views.py @login_required(login_url='login') def createInfringer(request): customer=request.user.customer form = InfringerForm(customer=customer) if request.method == 'POST': form = InfringerForm(customer, request.POST) if form.is_valid(): form.save() return redirect('infringer-list') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringerForm(ModelForm): def __init__(self, customer, *args, **kwargs): super(InfringerForm,self).__init__(*args, **kwargs) self.fields['customer'].queryset = Customer.objects.filter(name=customer) self.fields['status'].queryset = Status.objects.filter(customer=customer) class Meta: model = Infringer fields = ['name', 'brand_name','status','customer'] -
How to assign django permissions for object creators?
is it possible to allow editing on django admin site of objects in database only for creators of these objects? is extension django-guardian essential for this case? as i understood with django guardian i need manually assign permissions for each db objects and it seems not effective I tried to use django-guardian for this case, but documentation for it is not very clear for me and I am not sure this extension solve this case -
How do I get uuid foreign key to save in a form in django?
I have built a model with a uuid as the primary key. When I try to update using the uuid to identify the entry I am getting a valuetype error which says the object_id needs to be an integer. My Model: class IPHold(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) CHOICES = [ ('1', 'Book'), ('2', 'Documentary'), ('3', 'Graphic Novel/Comic'), ('4', 'Journalism'), ('5', 'Merchandise'), ('6', 'Podcast'), ('7', 'Stage Play/Musical'), ('8', 'Video Game'), ] media_type = models.CharField(max_length=1, choices=CHOICES, blank=False) title = models.CharField(max_length=255, blank=False) author_creator = models.CharField(max_length=255, blank=True) production_company = models.CharField(max_length=255, blank=True) artist = models.CharField(max_length=255, blank=True) composer = models.CharField(max_length=255, blank=True) publisher = models.CharField(max_length=255, blank=True) producer = models.CharField(max_length=255, blank=True) director = models.CharField(max_length=255, blank=True) year_published = models.ForeignKey(YearHold, on_delete=models.CASCADE, related_name='year_published', blank=True) # published_through = models.ForeignKey(YearHold, on_delete=models.CASCADE, related_name='published_through', default='0') ip_image = ResizedImageField(blank=True, size=[360, 360], force_format='JPEG', upload_to='media/ips/%Y/%m/') logline = models.TextField(blank=True) summary_description = models.TextField(blank=True) BOOKS = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10+'), ] series_length = models.CharField(max_length=2, choices=BOOKS, blank=True) episodes = models.PositiveSmallIntegerField(default=0) other_formats = models.BooleanField(default=False) genres = TaggableManager(through=TaggedGenreHold, verbose_name='Genres', blank=True) tags = TaggableManager(through=TaggedTagHold, verbose_name='Tags', blank=True) AVCHOICES = [ ('1', 'Available'), ('2', 'Optioned'), ('3', 'Purchased'), ('4', 'Public Domain'), ] availability = models.CharField(max_length=1, choices=AVCHOICES, blank=True) minimum_option_price = models.PositiveIntegerField(default=0) … -
Django: Custom User Model with Autoincrementing Id
I am trying to use Django Authentication and I want to create a custom model for the user that has an autoincrementing integer as id. I know about uuid library, but I want the id to be an integer number, that is why I want to avoid it. My code looks like: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, email, username, avatar, password=None): if not username: raise ValueError('User must have an username') if not avatar: raise ValueError('User must have an avatar') user = self.model( email=self.normalize_email(email), username=username, avatar=avatar, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, username, avatar, password): user = self.create_user( email=self.normalize_email(email), username=username, avatar=avatar, password=password, first_name=first_name, last_name=last_name ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) avatar = models.CharField(max_length=200) # required is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'id' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'email', 'avatar'] objects = MyAccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True The … -
how in javascript select some models field from django?
Hi i start learning javascript and i have a question. How in javascript select some models field from django? I searched this question in goggle but don’t get a current answer. -
Django model filter with "exact" IN operator
I want to find all users who have exactly same tags like a particular category (exactly same tags and also same amount of tags assigned) Something like... category = Category.objects.first() User.objects.filter(tags__in=category.tags.filter()) But this returns also users who share even only one tag with the category. Models are class User(models.Model): tags = models.ManyToManyField(Tag, blank=True, related_name='users') class Category(models.Model): tags = models.ManyToManyField(Tag, blank=True, related_name='categories') class Tag(models.Model): name = models.CharField(max_length=255, blank=False) Any solution appreciated. -
Django async access to related objects from .aget()
I have done some extensive searches and read the documentation. Unfortunately I could not solve the following. I probably missed something. ` async def generate_quotes(request, id): try: interrogation = await Interrogation.objects.aget(id=id) except Interrogation.DoesNotExist: return JsonResponse("Interrogation does not exist") print(interrogation.address.postcode) #where address is a onetoone related object with related name address i get a keyerror for address anddjango.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.` I am stuck on how to proceed. I have tried sync to async in all manner of ways with that one print statement and still nothing. I cant seem to get to the address object through its related interrogation object query result. I thought maybe it's to do with caching related objects. Any help would be greatly appreciate ! Thanks -
Why is the data being passed to the serializer saving as null in the database?
I've been working on this Django project with a rest framework serializer to take info sent from the front-end organize it and save it in the database. The info is made by drawing boxes over input fields on forms and sending all the fields you define. However, it's as though the data isn't actually being used after defining DataSerializer(data=data). An example of request.data = {'TextField': [], 'DateField': [], 'SignatureField': [['FieldName', [129, 79], [138, 35], 'Form.jpg']]} Here's my serializer: Class DataSerializer(serializers.ModelSerializer): class Meta: model = FormData fields = ["FieldName", "StartX", "StartY", "width", "height", "JSONData", "FormType"] def create(self, **validated_data): print(**validated_data) return FormData.objects.create(**validated_data) Here's my post View @api_view(['POST']) def create_list(request): if request.method == 'POST': dataDict = request.data for info in dataDict: Field = dataDict[info] stringDict = str(dataDict) for object in Field: datadict = { "FieldName": object[0], "StartX": object[1][0], "StartY": object[1][1], "width": object[2][0], "height": object[2][1], "JSONData": stringDict, "FormType": object[3] } serializer = DataSerializer(data=datadict) if serializer.is_valid(): serializer.create() return JSONResponse(serializer.data, status=201) print(serializer.errors) return Response("Not Valid") Here's my model which has been modified to accept null values not gonna be the case after I figure this out. class FormData(models.Model): FieldName = models.CharField(max_length=100) StartX = models.IntegerField(null=True) StartY = models.IntegerField(null=True) width = models.IntegerField(null=True) height = models.IntegerField(null=True) JSONData = models.CharField(max_length=500) … -
django-filter python class sub function under __init__ function not receive value return
I'm coding a django project that use django-filter: filter.py: import django_filters from myApp.models import MyRunStats class MyRunStatsFilter(django_filters.FilterSet): def gen_choice(filed): return tuple((l, l) for l in list(AegisRunStats.objects.values_list(filed, flat=True).distinct())) name_procss=django_filters.ChoiceFilter(label='Process',choices=gen_choice('name_procss')) class Meta: model = MyRunStats fields = ['name_procss'] For some reason I need to add a init function: class MyRunStatsFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super(MyRunStatsFilter, self).__init__(*args, **kwargs) def gen_choice(filed): return tuple((l, l) for l in list(AegisRunStats.objects.values_list(filed, flat=True).distinct())) name_procss=django_filters.ChoiceFilter(label='Process',choices=gen_choice('name_procss')) class Meta: model = MyRunStats fields = ['name_procss'] But after modify the code ,the gen_choice function is not called . My question is how to call gen_choice() functioin again after I put it under def __init__(self, *args, **kwargs): -
Saving logs in Mongodb as 2nd DB in Django app
I need to save all request logs in Mongodb in Django. Can you provide me with some tutorial or blog? I tried searching but could not find any good post about this. -
CustomUser has no customer error for users signed in with google
I have a CustomUser model to differentiate between customer and merchant. class CustomUser(AbstractUser): is_customer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) Now the customers have the add to cart functionality for which I have a utils.py def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems':cartItems ,'order':order, 'items':items} As per the utils.py I always need request.user.customer. The customer instance here is created during customer registration. forms.py: @transaction.atomic def save(self): user = super().save(commit=False) user.is_customer = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.username=self.cleaned_data.get('username') user.email=self.cleaned_data.get('email') user.phone_number=self.cleaned_data.get('phone_number') user.address=self.cleaned_data.get('address') user.save() customer = Customer.objects.create(user=user) customer.first_name=self.cleaned_data.get('first_name') customer.last_name=self.cleaned_data.get('last_name') customer.username=self.cleaned_data.get('username') customer.email=self.cleaned_data.get('email') customer.phone_number=self.cleaned_data.get('phone_number') customer.address=self.cleaned_data.get('address') customer.save() return user So with the customer, everything worked just fine. But the problem arises when I try to sign in with google. I have signed in with google functionality with Oauth, worked on the google developers console, installed required packeges, and made changes to settings.py. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'projectapp.apps.ProjectappConfig', 'django_extensions', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
How to make JWT Token Authentication on pure Django without React?
I am backend dev, and I want to make website without front end, like react or other front end libraries, just on pure Django. I made on Django a website, all is done, and now it is time for JWT Token Authentication. Is it possible to make it on pure Django, if yes can you give me a hint how, the best will be some videos or done projects. Thanks in advice :)) -
Django add function to "from" clause?
I'm trying to write a Django query that generates the following: select group_id, cardinality(array_agg(distinct aul)) from report_table, unnest(active_user_list) as aul group by group_id Where active_user_list is an array[int] type. I'm trying to get a count of the unique items in the arrays of all rows that are in a group. The queryset.extra method gets me very close to this, but adds double quotes around unnest(active_user_list) as aul and doesn't work. I created a custom sql function that does work, but I'd prefer to do it in Django if possible. -
django-filter caused sqlite3.OperationalError: no such table issue
I'm coding a django project using django-filter: filter.py: import django_filters from myApp.models import MyRunStats class MyRunStatsFilter(django_filters.FilterSet): def gen_choice(filed): NAME_PROCESS_LIST = list(MyRunStats.objects.values_list(filed, flat=True).distinct()) NAME_PROCESS_CHOICE = tuple((l, l) for l in NAME_PROCESS_LIST) #this above 2 line codes will generate a tuple like NAME_PROCESS_CHOICE = (('One', 'One'), ('Two', 'Two')) return NAME_PROCESS_CHOICE name_procss=django_filters.ChoiceFilter(label='Process',choices=gen_choice('name_procss')) class Meta: model = MyRunStats fields = ['name_procss'] views.py: from myApp.models import MyRunStats from myApp.filter import MyRunStatsFilter def runstat_hist_view(request): all_obj = MyRunStats.objects.all().order_by('-create_dttm') hist_filter = MyRunStatsFilter(request.POST, queryset=all_obj) paginator= Paginator(hist_filter.qs[:75], 15) 'logic and code here....' While I'm using django-filter,when I tried to: python manage.py makemigrations or python manage.py migrate or python manage.py mangage.py runserver I always met the error: sqlite3.OperationalError: no such table issue I googled and found all the solutions are not work for me .But finally I manfully solved the issue by: First in Veiws.py I commend this line: from myApp.filter import MyRunStatsFilter And then run any of above 3 command line ,it works ,the server can up and then I commend that line back. Everything goes well, but this method is very manually. Once I upload the code to a automatically testing sever the issue comes again ,since it is solved manfully ,in the testing sever I need find out … -
How to make Model Save method the PK gets incremented by n number
This is follow up question to my previous post. I am trying to overwrite the Save method of model so that the primary key gets incremented by 5 as follow: class Client(Model): client_id= models.PositiveIntegerField(primary_key=True) client_name = models.CharField(max_length=1000, null=True, blank=True) # Overwrite the Save functionality to increment the Client ID by 5 def save(self, *args, **kwargs): try: if self._state.adding is True: # Intialize the first Client Id to 5 and then after Increment by 5 if not Client.object.count(): self.client = 5 else: self.client = Client.object.last().client + 5 super(Client, self).save(*args, **kwargs) except (Exception, FileNotFoundError, IOError, ValueError) as e: print(e) return False def __str__(self): return str(self.client_name) class Meta: db_table = 'Client' However, the above code is not working infact its not creating client entry at all. Any suggestion what I am doing wrong? Thank You. -
how to query the user customer in user model to do a query and add record in django
I have a custom user model with a field 'customer'. Each user has a customer. I am trying to get the logged in users customer so that when I add infringer, the correct customer is added for the record. I think below is wrong in views. customer=request.user.customer think below is wrong in forms. customer__user=self.customer views.py @login_required(login_url='login') def createInfringer(request): customer=request.user.customer form = InfringerForm(customer=request.customer) if request.method == 'POST': form = InfringerForm(customer, request.POST) if form.is_valid(): form.save() return redirect('infringer-list') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringerForm(ModelForm): def __init__(self, customer, *args, **kwargs): self.customer = customer super(InfringerForm,self).__init__(*args, **kwargs) self.fields['customer'].queryset = Customer.objects.filter(customer__user=self.customer) class Meta: model = Infringer fields = ['name', 'brand_name','status' , 'customer'] models.py class Infringer (models.Model): name = models.CharField(max_length=200) brand_name = models.CharField(max_length=200, null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name class Customer (models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=254, default='@cudo.ai') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) phone_number = PhoneNumberField(blank=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) player = models.ManyToManyField(Player, related_name='player', blank=True) is_active = models.BooleanField(default=False) class Meta: ordering = ['name'] def __str__(self): return self.name -
Django unittest with redirect based on return_value
I have a view function similar to def my_function(request): session = create_something('some_random_string') return redirect(session.url, code=303) To test it import unittest from django.test import TestCase from unittest.mock import patch from my_app.views import my_function class TestMyFunction(TestCase): @patch('my_app.views.create_something', return_value={ "url": "https://tiagoperes.eu/" }) def test_my_function(self, mock_create_something): response = self.client.get("/my-function/") This gives AttributeError: 'dict' object has no attribute 'url' This question is similar the following questions Cannot redirect when Django model class is mocked (in that I'm using the redirect() that takes dynamic values coming from the mocked function) How to debug patched method with unittest.mock (in that without the return_value I'd get TypeError: expected string or bytes-like object) -
How to combine methods for outputting data in textarea?
I have a django application. And I have some methods that output data in a textarea through a upload function So I am using this textstring for outputting data: text="[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 Nederland\nFactuur datum : 10-12-21\nAantal Omschrijving Prijs Bedrag\nOrder number : 77553 Loading date : 09-12-21 Incoterm: : FOT\nYour ref. : SCHOOLFRUIT Delivery date :\nWK50\nD.C. Schoolfruit\n16 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 123,20\n360 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 2.772,00\n6 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,/0 € 46,20\n75 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 577,50\n9 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 69,30\n688 Appels Royal Gala 13kg 60/65 Generica PL I € 5,07 € 3.488,16\n22 Sinaasappels Valencias 15kg 105 Elara ZAI € 6,25 € 137,50\n80 Sinaasappels Valencias 15kg 105 Elara ZAI € 6,25 € 500,00\n160 Sinaasappels Valencias 15kg 105 FVC ZAI € 6,25 € 1.000,00\n320 Sinaasappels Valencias 15kg 105 Generica ZAI € 6,25 € 2.000,00\n160 Sinaasappels Valencias 15kg 105 Noordhoek ZA I € 6,25 € 1.000,00\n61 Sinaasappels Valencias 15kg 105 Noordhoek ZA I € 6,25 … -
Sending Emails through Django is not working in Nov 2022
I have tried all the advices and guides already available but it is not working at any cost. Please refer below to know more. I have activate the 2 factor authentifcation required. 2 factor authentication activated I generated the App password and used it correctly in the django settings.py file. You can see there is an app password in the above image. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "xyz" EMAIL_HOST_PASSWORD = "abc" And use the following code to send the email. subject = "Email verification" text = "Hi, This is the link to verify you registration email with our site {0}. Please paste the link to verify your account {0}/auth/verify/{1}/" message = text.format(self.request.get_host(), self.token) email_from = settings.EMAIL_HOST_USER recipient_list = [self.request.data['email'],] send_mail(subject, message, email_from, recipient_list) But still I am getting the below error. Error form smtp: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials l9-20020a17090a150900b0020d48bc6661sm10003685pja.31 - gsmtp') I have tried enbaling less secure apps but it shows like this: No change possible for less secure apps I have also tried this link: https://accounts.google.com/DisplayUnlockCaptcha enter image description here -
Network exception error when trying to use Daphne with GreaterWMS
I am extremely new to programming, just wanted to try out the GreaterWMS warehouse management software, as my parents currently count all warehouse inventory by hand.. (yeah I know). Here is the error I am receiving network exception error, from doing a bit of googling I see this network exception error means that I don't have an internet connection. I have turned off windows firewall to see if that would have done the trick, but it did not help. Here is what my powershell shows when I'm listening to the port Powershell List of pip packages Not sure if this is enough information, please let me know if you require any other info and I can provide! I just so lost I have no idea what to do next. Thanks everyone in advance! I expected the intranetIP:8008 site to work, currently I just want to register an admin account so that I can start inputting inventory into the website. However I can not because when I try to register a account onto the intranet site I receive a NETWORK EXCEPTION ERROR. Doing some googling it seems that this error occurs when you have windows firewall enabled, however I disabled it … -
Is there any way to fix the login page not found error?
I created a login page, but it seems that the link is not valid, I have tried many ways but it doesn't work Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%7B%25url%20'login'%7D Using the URLconf defined in mysite.urls Here is my code urls.py ` from django.contrib import admin from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.index), path('contact/', views.contact, name='contact' ), path('register/', views.register, name= 'register'), path( 'login/',auth_views.LoginView.as_view(template_name="pages/login.html"), name="login"), path('logout/',auth_views.LogoutView.as_view(next_page='/'),name='logout'), ] ` <!DOCTYPE html> <html lang="en"> <head> <meta charset ="UFT=8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Documment</title> </head> <body> <form method = "POST" > {%csrf_token%} {%for key, value in form.errors.items %} {{value }} {% endfor %} <p> <label>Tài Khoản : </label>{{form.username}}</p> <p> <label>Mật Khẩu : </label>{{form.password}}</p> <input type="hidden" name='next' value="/"/> <input type="submit" value="Đăng nhập"/> </form> </body> </html> -
Why the object name and value is displayed in the django template?
I have a little problem on django when I use a model with a one to many relationship. When the field is part of another table that is linked by a foreign key, I get the result but I have the name of the model which is 'Leaf1' with that with "object(value)". And what I would like is that the "value" My result Code: {% for i in table_fu %} {{ i.nip }} {% endfor %} PS:For the other columns it works fine. How to display only the value without the object name? -
How to make Model's PK as FK to all Django's Project Models
I need some help to figure out what's the best way to design following model use case in Django. I have model "Client" which defines client id for an app. This model needs to refer as a foreign key to all models of project. Here is code snippet: Class Client(Model): ClientId = models.AutoField(primary_key=True) Class Location(Model): LocationId = models.AutoField(primary_key=True) ClientId = models.ForeignKey(Client, on_delete=models.CASCADE, db_column="ClientId") Class User(Model): UserId = models.AutoField(primary_key=True) ClientId = models.ForeignKey(Client, on_delete=models.CASCADE, db_column="ClientId") Class Document(Model): DocumentId = models.AutoField(primary_key=True) ClientId = models.ForeignKey(Client, on_delete=models.CASCADE, db_column="ClientId") As shown above, Location, User and Document all have ClientId as FK. It works however.... Issue with above design is that I have to explicitly specify ClientId as FK in each table. As ClientID is required FK for each models of Project, I want to know if there is any simple design pattern where ClientId is defined as FK to each model without specifying it. I have thought of using inheritance but that does not work as there is only one Global ClientId and defining Client as Parent for each model means it creates Client Id each time new instance of child is created. Any idea or pointer to this issue. -
How to store weekday and time with timezone?
We are currently storing events: As single dates Date_from: 2022-11-11 10:00, Date_to: 2022-11-11 11:00) As weekdays (Currently as one database entry) Weekday: Monday, Time_from: 10:00, Time_to: 11:00 We want to add timezone information: Single dates: easy - just convert the datetime to UTC and convert it back when used Weekdays: ?? The questions: How do we handle different timezones with weekdays? Do we store the weekday in UTC? If so, how do we convert a weekday into an UTC weekday?