Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
I can't run even simple code of python in my PyCharm IDE. Do need support
I can't run my python files with pycharm. It says "Error running 'main': Cannot run program "C:\Users\pbrah\AppData\Local\Microsoft\WindowsApps\python3.10.exe" (in directory "C:\Users\pbrah\PycharmProjects\pythonProject9"): CreateProcess error=1920, The file cannot be accessed by the system" The Screen shot of the mentioned issue when i had to install Django there was an issues with Django working inpycharm.so I uninstalled and reinstalled PyCharm. Django stated working but now simple python codes doesn't works at all and the above mentioned problem was coming forward. -
I am getting the error 'ReverseManyToOneDescriptor' object has no attribute 'exclude'
Trying to get a one to many kind of query with filters but I keep getting this error, kindly assist def user_profile(request,pk): profileObj = Profile.objects.get(id = pk) topSkill = Profile.skill_set.exclude(description__isnull=True) otherSkill = Profile.skill_set(description = "") context = {"profile":profileObj,'topSkills':topSkills,"otherSkills":otherSkills} return render(request, 'users/user_profile.html', context) but I keep getting this error, kindly assistReverseManyToOneDescriptor' object has no attribute 'exclude' Here are my models class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null = True, blank = True) name = models.CharField(max_length= 500, null = True, blank = True) email = models.EmailField(max_length= 500, null = True, blank = True) username = models.CharField(max_length= 500, null = True, blank = True) location = models.CharField(max_length= 500, null = True, blank = True) short_intro = models.CharField(max_length= 300, null = True, blank = True) bio = models.TextField(max_length= 500, null = True, blank = True) profile_image = models.ImageField(upload_to = "profiles/", default = "profiles/user-default.png", null = True, blank = True) social_github = models.CharField(max_length= 500, null = True, blank = True) social_twitter = models.CharField(max_length= 500, null = True, blank = True) social_linkedIn = models.CharField(max_length= 500, null = True, blank = True) social_youtube = models.CharField(max_length= 500, null = True, blank = True) social_website = models.CharField(max_length= 500, null = True, blank = True) created = models.DateTimeField(auto_now_add … -
ValueError: not enough values to unpack (expected 2, got 1) while running django tests
Django test throws value error every time i try to input data in the test request req_body = {"Value1":"Value1", "Value2":"Value2"} request = self.client.get(self.getSingleData_url, data= json.dumps(req_body), content_type='application/json') I have tried data = req_body but it returns an empty {} to the endpoint Complete Value error I have tried using, other ways to pass data, but once it is passed as json it throws Value Error -
Django-admine cmd and creat a projet
I wante to creat un projet with django but i have problem with django-admin. I install django and django admine and i have this message : WARNING: The script django-admin.exe is installed in 'C:\Users\maede\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. when i type django-admin startproject siteweb(name of projet), i have this message: 'django-admin' n’est pas reconnu en tant que commande interne ou externe, un programme exécutable ou un fichier de commandes. How i can change direction of django admin and solve this problem? reinstall django and update pip3 : pip 22.3.1 -
How to create a case insensitive choice field from DRF normal choice field?
I am trying to create a case insensitive choice filed such as CaseInsensitiveChoiceField that inherits and modifies serializers.ChoiceField suppose I a creating a serializer as below from rest_framework import serializers my_field_choices = ["A", "BCD", "e"] class MySerializer(serializers.Serializer): my_field = serializers.ChoiceField(choices=my_field_choices) this serializer does not validate if I pass data={"my_field": "a"} or data={"my_field": "BCd"} or {"my_field": "e"} to it. what I could do was from rest_framework import serializers my_field_choices = ["A", "BCD", "e"] class MySerializer(serializers.Serializer): my_field = serializers.ChoiceField(choices=[item.upper() for item in my_field_choices]) and then modify the data and then pass it to it: data = request.body data["my_field"] = data["my_field"].upper() However, this is not very clean and I dont want to modify the request body because of validation. I am looking for a way to create a CaseInsensitiveChoiceField that tweaks ChoiceField and inherits from it. any idea how to do that? I dont clearly understand how these serializers and fields work. Otherwise, I may be able to do this. -
Hello, please i want to generate a random alphanumeric code, turn it into a qr code and then save both in my db with one click but i keep having bugs
Im a beginner and is part of the first big project i started but i keep getting errors. as it is, the qr code is created and stored in the media file but the name and alphanumeric code are not saved in the db and when i try modifying the code a little bit, the name and alphanumeric code are saved but the qr code is not created If possible i also need a way to save each qr code with the alphanumeric code used to generate it (a way to give a more meaningfull name to the qr code will be welcome from django.shortcuts import render, redirect from .models import Code from django.conf import settings from qrcode import * import time from pathlib import Path from django.http import HttpResponseRedirect from .forms import CodeForm import random import string # Create your views here. def show(request): return render(request, 'show.html') def win(request): return render(request, 'win.html') def qr_gen(request, x): if request.method == 'POST': data = x img = make(data) img_name = 'qr' + str(time.time()) + '.png' img_path = Path(settings.MEDIA_ROOT) img.save(str(img_path) + '/' + img_name) return render(request, 'index.html', {'img_name': img_name}) return render(request, 'index.html') def generator(request): user_code = "".join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=20)) form=CodeForm() …