Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django many-to-many override save method to increment a field instead of creating new objects
I have the following classes in my Models.py: class Size(models.Model): prod_size = models.DecimalField(max_digits=3, decimal_places=1) quantity = models.IntegerField(default=1) def save(self, *args, **kwargs): size_exists = Size.objects.filter( prod_size=self.prod_size, product_id=self.product_id ).exists() if size_exists: Size.objects.filter( prod_size=self.prod_size, product_id=self.product_id ).update(quantity=F('quantity')+1) else: super(Size, self).save(*args, **kwargs) class Product(models.Model): sizes = models.ManyToManyField(Size, related_name='products') I want the save method to update the quantity field of Size if there already exists a prod_size with the same value and related to the same product_id. But I am having trouble with getting the product_id information from the intermediate table. Is there any way I can achieve this? -
Deploying a Django application to Elastic Beanstalk AWS 502 Bad Gateway
I follow all the instructions on the official AWS website, but I still get the same mistake. I have tried several projects, each on the local server works quite normally as soon as it starts on AWS I get the next error 502 Bad Gateway. this seams like main problem : ModuleNotFoundError: No module named 'ebddjango/wsgi' Status: Updated: 2022-01-27 14:19:09.259000+00:00 Status: Ready Health: Red Erorr log Jan 27 14:49:19 ip-172-31-8-170 web: File "", line 1006, in _gcd_import Jan 27 14:49:19 ip-172-31-8-170 web: File "", line 983, in _find_and_load Jan 27 14:49:19 ip-172-31-8-170 web: File "", line 965, in _find_and_load_unlocked Jan 27 14:49:19 ip-172-31-8-170 web: ModuleNotFoundError: No module named 'ebddjango/wsgi' Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4399] [INFO] Worker exiting (pid: 4399) Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4392] [INFO] Shutting down: Master Jan 27 14:49:19 ip-172-31-8-170 web: [2022-01-27 14:49:19 +0000] [4392] [INFO] Reason: Worker failed to boot. Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Starting gunicorn 20.1.0 Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Listening at: http://127.0.0.1:8000 (4407) Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4407] [INFO] Using worker: gthread Jan 27 14:49:20 ip-172-31-8-170 web: [2022-01-27 14:49:20 +0000] [4414] … -
How to set up a loading screen for a form that takes time to process in Django?
I have the following view (with some code removed for simplicity): def add_entry(request, num): form = ModelForm1() form2 = Form2() if request.method == 'POST': form = ModelForm1(request.POST) form2 = Form2(request.POST) if form.is_valid() and form2.is_valid(): text = form2.cleaned_data['text'] database_dict = process_data(text) # Some code here that dictates how data is saved from the dictionary.... entry.save() return redirect('entries', num) return render(request, 'app/add_entry.html', {"form": form, "form2": form2}) Basically, this view contains a form which takes a text input. That text input is processed through a function with returns a dictionary of values. Those values are then stored in a database, and this database is rendered to the template "entries.html". Depending on the amount of text in the form, it can take quite some time to process, and this time is spent in the input-screen of the form. I would like to add an interim "loading"-screen which the user is taken to while the form is processed, which then redirects to entires.html after the processing is done, but I can't seem to find out how. Adding a redirect without the "return" statement right after the data is processed doesn't seem to do anything, and adding the "return" messes everything up. How do I do … -
simple: django create dynamic url
When your view looks like this def LinkView(request): #do i even have to pass parameters to the function? return render(request, 'linkview.html', {}) What can I do to have a dynamic URL based on the user model so that every user has his own url/page? path('links/#User_model??#/', LinkView), -
Django Rest Framework ModelViewSet ManyToMany Field override partial_update Method is not working update_or_create
I have a question here I have two models Tag Model class Tag(models.Model): creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author') name = models.CharField(max_length=100) def __str__(self): return self.name Profile Model class Profile(models.Model): profiler = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='contour') bio = models.TextField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, related_name='keywords') image = models.ImageField(default='avatar.jpg', upload_to='images', blank=True, null=True) def __str__(self): return f'{self.profiler}' Tag Serializer class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' Profile Serializer class ProfileSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, read_only=True) class Meta: model = Profile fields = ['id', # List All fields Exclude profiler => OneToOne field name 'bio', 'description', 'tags', 'image', 'birthDate', 'created', 'updated', ] depth = 1 Profile Viewset class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = [IsAuthenticated] def partial_update(self, request, *args, **kwargs): data = request.data profile_obj = Profile.objects.update( profiler=self.request.user, bio=data['bio'], description=data['description'], image=data['image'], birthDate=data['birthDate'], ) profile_obj.save() for tag in data['tags']: tag_obj = Tag.objects.update_or_create( creator=self.request.user, name=tag['name'], # name => Field Name in Tag Model ) print(tag_obj) profile_obj.tags.add(tag_obj) # tags => ManyToMany Field Name in Profile Model serializer = ProfileSerializer(profile_obj) return Response(serializer.data) my aim is to create a new tag if this name is not exist, and also update profile tags but my code is not working, and I don't know why Can Any body … -
How to add data to Many-To-Many field in Django DRF
I'm new to Django DRF, trying to have a sports school project done. I have a model for coaches, classes and students. Here is a stripped version to keep it simple and easy: class Student (models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) def __str__(self): return f'{self.first_name} {self.last_name}' class Coach (models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) def __str__(self): return f'{self.first_name} {self.last_name}' class ClassDetails (models.Model): class_name = models.CharField(max_length = 50) class_coach = models.ForeignKey(Coach, related_name='coach_classes') class_members = models.ManyToMany(Student, related_name='student_classes') def __str__(self): return self.class_name In order to list/add students to the class, I'm using the following serializer: class ClassDetailsSerializer(serializers.ModelSerializer): class Meta: model = ClassDetails fields = ['id','class_name', 'class_coach', 'class_members] read_only_fields = ('id', 'class_name', 'class_coach') Getting the data is working ok. Also, adding a coach is working fine, what is really giving me a hard time is adding a class member. I'm using the following view: def member_add(self, request): my_class = ClassDetails.objects.get(pk = request.data['id'] serializer = ClassDetailsSerializer(my_class, data=request.data) if serializer.is_valid(): serializer.save() return Response('Member added', status.HTTP_201_CREATED) return Response(serializer.errors, status.HTTP_406_NOT_ACCEPTABLE) I'm sending a POST body like: { "id": 2, <- class id "class_members": [20] <- student's id to add to the class members } The problem is no … -
Comment je dois regler ce probleme dans mon code'NoneType' object has no attribute 'is_admin'
from django.db import models from django.contrib.auth.base_user import AbstractBaseUser,BaseUserManager class UsagerManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Vous devez entrer un mail valide ou un téléphone valide") user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save() return user def create_superuser(self, email, password = None): user = self.create_user(email=email, password=password) user.is_admin = True user.is_staff = True user.save() return user class UsagerClient(AbstractBaseUser): CHOISI = [ ('Atl', 'Atlantique'), ('Ata','Atacora'), ('Ali', 'Alibori'), ('Bor', 'Borgou'), ('Cou', 'Couffo'), ('Col', 'Colline'), ('Don', 'Donga'), ('Lit', 'Littoral'), ('Mon', 'Mono'), ('Oue', 'Oueme'), ('Pla', 'Plateau'), ('Zou', 'Zou') ] nom = models.CharField(max_length=50) prénom = models.CharField(max_length=100) téléphone = models.CharField(max_length=8) societe = models.CharField(max_length=15) email = models.EmailField(unique=True, max_length=255, blank=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) département = models.CharField(max_length=30, choices=CHOISI) ville = models.CharField(max_length=3) adresse = models.CharField(max_length=50) USERNAME_FIELD = "email" objects = UsagerManager() REQUIREMENT_FIELD = ["nom", "prénom", "téléphone", "email", "département","ville", "adresse"] def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True -
Reference the parent model id in getting the child data in Django Multitable inheritance
I have extended 2 models from a parent model like this. class ParentModel(models.Model): # fields class ChildModelA(ParentModel): # fields class ChildModelB(ParentModel): # fields Is there any way I can reference the id of the child models to the parent model? Right now, I am still manually fetching it by obj.parentmodel_ptr.id -
Respond to Instagram webhook in Django
I set the callback-url for Instagram webhook, and when Instagram Get my callback-url I should Respond to the hub.challenge to verify. Instagram GET request to my endpoint URL: GET https://callback_url/webhooks? hub.mode=subscribe& hub.challenge=1158201444& hub.verify_token=meatyhamhock But I have this error: The URL couldn't be validated. Response does not match challenge, expected value="1120110039", received="\u003C!DOCTYPE html>\n\u003Chtm..." My code in vews.py: def getInstagramWebhook(request): if request.method == "GET": mode = request.GET.get("hub.mode") challenge = request.GET.get("hub.challenge") verify_token = request.GET.get("hub.verify_token") return challenge I tried JsonResponse, HttpResponse, and redirect but not work -
Namespace Error uploading an image from Flutter Image Picker to Rest API using Django Rest Framework
I am receiving Namespace error in my debug console when I try to upload an image in Flutter through Django Rest Framework. The following code has been implemented: File? galleryFile; final ImagePicker _picker = ImagePicker(); Future imageSelectorGallery() async { var image = (await _picker.pickImage( source: ImageSource.gallery, )); if (image != null) { setState(() { galleryFile = File(image.path); }); List<int> imageBytes = galleryFile!.readAsBytesSync(); String baseimage = base64Encode(imageBytes); print(baseimage); } The error image: Any help would be appreciated. -
Django pass id from instance to not instantiated model field
Im my ProductImages model i made some fields to store various types of some image, like: models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) #This field is used in form image_file_w200_png = models.ImageField( verbose_name = "Selecione a imagem", upload_to=upload_to_image_file_w200_png, null=True, blank=True, default='magickhat-profile.jpg' ) #This field is not used in forms image_file_w480_png = models.ImageField( upload_to=upload_to_image_file_w480_png, null=True, blank=True, default='magickhat-profile.jpg' ) ... Well, the ideia is when user upload a image from image_file_w200_png field, the image is resized to various dimensions, and i save that other images in other fields like image_file_w480_png My actual problem consiste in upload_to, as we can see in docs, upload_to may also be a callable, such as a function. So i made my own function in utils.py to upload_to to each field. utils.py def upload_to_image_file_w200_png(instance, filename): ext = filename.split('.')[-1] filename = instance.product.slug+"_"+str(instance.id)+"_w200_png."+ext return 'user_{0}/{1}/{2}/{3}'.format(instance.product.user.id, instance.product.id, instance.id, filename) def upload_to_image_file_w480_png(instance, filename): ext = filename.split('.')[-1] filename = instance.product.slug+"_"+str(instance.id)+"_w480_png."+ext return 'user_{0}/{1}/{2}/{3}'.format(instance.product.user.id, instance.product.id, instance.id, filename) the problem is, instance.id is the id of field image, but the only field that is instantiated is image_file_w200_png field, the image_file_w480_png is not, so how can i use the instance.id from upload_to_image_file_w200_png function in upload_to_image_file_w480_png function? -
How to add row in automatically created table in Django from views.py?
I have a model called 'Kategoria' which is a ManyToMany field in 'Produkt' model: kategoria = models.ManyToManyField(Kategoria) Django automatically generated a table, which looks like this: In a view, I have retreived kategoria_id and created an object which is named "Produkt" in models.py. kategoria_nazwa = str(data['kategoria']) kategoriaa = Kategoria.objects.get(nazwa_kategorii=kategoria_nazwa) product = Produkt.objects.create(nazwa=nazwa, numer_partii=numer_partii, cena=cena, opis=opis, liczba=liczba, image=image, producent_id=producent_id) It is created successfully, however now I want to add information about product_id and kategoria_id to automatically generated table in django, which I obviously didn't declare in models.py file. # TODO: Produkt.kategoria.create(produkt_id=product.id_produktu, kategoria_id=kategoriaa.id_kategorii) This part doesn't work. It says that there is an AttributeError: 'ManyToManyDescriptor' object has no attribute 'create'. How to insert row into a table from views.py? I have also checked if kategoriaa.id_kategorii and product.id_produktu are correct, and everything is fine. -
Problem with TableOfContent ReportLab doc.notify does not generate in TOC
I have a problem with TableOfContent ReportLab doc.notify does not generate in TOC. Direct call to doc.notify does not generate in TableOfContent. Calling afterFlowable(doc, f) to definition does not generate a TableOfContent. Only direct doc.notify call in myLaterPages definition works, but of course it generates list of all pages with static string "Chapter". Where do I go wrong? from django.http import FileResponse from reportlab.pdfgen import canvas import reportlab.pdfgen from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak #from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch from django.http import HttpResponse, HttpResponseBadRequest from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import mm, inch from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.pdfmetrics import registerFontFamily from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus.tableofcontents import TableOfContents, SimpleIndex #from reportlab.lib.pagesizes import letter, A5 from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT PAGESIZE = (140 * mm, 216 * mm) BASE_MARGIN = 5 * mm def generatePDF(request,id): pdfmetrics.registerFont(TTFont('Berylium', 'resources/fonts/Berylium/Berylium.ttf')) pdfmetrics.registerFont(TTFont('BeryliumBd', './resources/fonts/Berylium/Beryliumbold.ttf')) pdfmetrics.registerFont(TTFont('BeryliumIt', './resources/fonts/Berylium/BeryliumItalic.ttf')) pdfmetrics.registerFont(TTFont('BeryliumBI', './resources/fonts/Berylium/BeryliumboldItalic.ttf')) registerFontFamily('Berylium', normal='Berylium', bold='BeryliumBd', italic='BeryliumIt', boldItalic='BeryliumBI') PAGE_HEIGHT=defaultPageSize[1] PAGE_WIDTH=defaultPageSize[0] book = Book.objects.get(id=id) Title = book.title pageinfo = book.title Author = book.author Filename = book.title def afterFlowable(self, flowable): "Registers TOC entries." if flowable.__class__.__name__ == 'Paragraph': text = flowable.getPlainText() style = flowable.style.name if style == 'style1': self.notify('TOCEntry', (0, text, self.page … -
Django create correct model form?
When I load the page, the value of the input is automaticly this: How is that possible? views file if request.method == 'POST': form = FieldForm(request.POST, instance=Field(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard') else: form = FieldForm(instance=Field) ...... forms file class FieldForm(forms.ModelForm): class Meta: model = Field fields = ( 'title', 'url' ) models file class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=255) url = models.CharField(max_length=255) creator_adress = models.GenericIPAddressField(null=True) def __str__(self): return str(self.user) Here one input 😂 " maxlength="255" required="" id="id_url"> -
Table already exists when I run pytest on Django project
I have a Django project of version 3.2.5. I created a new model: app.model. Then I ran python manage.py makemigrations app command. When I ran the tests via pytest, I got the following errors: E psycopg2.errors.DuplicateTable: relation "app_model" already exists E django.db.utils.ProgrammingError: relation "app_model" already exists However there's no such table neither on my local database nor in test database which is created from scratch. I pushed my code on a branch to Github and build succeeded online with no problems. However my test suite complained about this existing table. I ran python manage.py migrate app and it worked. -
How to use SMTP to send email using python on Godaddy servers
I have build a website using django,and it uses smtp to send me a mail containing details filled out on a form on the same site,But SMTP is not working on Godaddy servers,Below is the code i used: import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMETe sender_address = 'user@gmail.com' receiver_address = 'userto@gmail.com' sender_pass = '123' #Setup the MIME message = MIMEMultipart() message['From'] = sender_address message['To'] = receiver_address message['Subject'] = 'N' #The subject line #The body and the attachments for the mail message.attach(MIMEText(mail_content, 'plain')) #Create SMTP session for sending the mail session = smtplib.SMTP('localhost', 25) #use gmail with port session.starttls() #enable security session.login(sender_addres, sender_pass) #login with mail_id and text = message.as_string() session.sendmail(sender_address, receiver_address, text) session.quit() print('Mail Sent') it just gives me the error: SMTPAuthenticationError (535, b'Incorrect authentication data') My username and password are correct,i have used localhost and port 25 as said in one of thier documentation Thanks in Advance -
How to use another python project function into your project
I'm working with Django in a project, I want to use a python function from a project in Github, I can't install this project as a library with pip install dicom-exporter because it doesn' work. The project I want to use: https://github.com/KitwareMedical/dicom-exporter/ the function I want to use : dicom-exporter <path/to/dicom/folder> <path/to/output.vti> The project contain setup.py file where there is script entry-point, Please How can use this project in my django project. -
What should I do so that the result of filter() function is the dictionary mapping result
I have a model like this: class BNetworkEdge(models.Model): id = models.AutoField(unique=True, primary_key=True) source = models.IntegerField() target = models.IntegerField() edge_type = models.IntegerField() class Meta: managed = True db_table = 'b_network_edge' I have a dictionary like this: {0:'direct', 1:'no-direct'} How do I get the function 'BNetworkEdge.objects.all()' is directly the dictionary mapping result? Thanks! -
Delete django data without RuntimeWarning: DateTimeField received a naive datetime
I am trying to delete 3 years old data in my python django db. Here is code: from datetime import datetime from dateutil.relativedelta import relativedelta def db_cleanup(): cleanup_start = datetime.utcnow().date() three_years_ago = cleanup_start - relativedelta(years=3) MyData.objects.filter(create_date__lt=three_years_ago).delete() however I receive RuntimeWarning: DateTimeField received a naive datetime . How to do it properly? -
Can someone explain to me how this code works? Django Python [closed]
I have this code here in models.py which I don't exactly know how it works. models.py: from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="profile_pic", blank=True) def __str__(self): return self.user.username The User here what does it do. Does OneToOneField link user to User. Is the user.username a table automatically created when I migrate "user = models.OneToOneField(User, on_delete=models.CASCADE)". I do understand the code somewhat but want to understand it better. Please any explanation would be much appreciated. -
"Contact Me" form that sends emails to me
I have the following HTML page: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Contact Me</title> <link rel="stylesheet" href="{% static 'projects/style_contact.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div class="container"> <div class="text">Contact Me</div> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="input-data"> <div class="underline"></div> <input type="text" name="name" required placeholder="Name"> </div> <div class="input-data"> <div class="underline"></div> <input type="text" name="email" required placeholder="Email Address"> </div> </div> <div class="form-row"> <div class="input-data"> <div class="underline"></div> <input type="password" name="password"required placeholder="Password"> </div> </div> <div class="form-row"> <div class="input-data textarea"> <div class="underline"></div> <input type="text" name="message" required placeholder="Write your message"> </div> </div> <div class="form-row submit-btn"> <div class="input-data"> <div class="inner"></div> <input type="submit" value="submit"> </div> </div> </form> </div> </body> </html> I want to be able to send emails from that form. I know that all the Email configurations need to go inside the settings.py file, but how would i make sure that the legitimate owner of that email sends the message. The form needs to get the correct password of that specific email address so that the legitimate owner is the only one who can actually send the message. Any ideas?? -
Are these (performance) concerns valid when loading images via https from an external website?
Running a website with lots of images from external websites*, I have an option to either A) Download the images myself and serving them or B) Loading them via https from the external website image URL. I'm thinking of going with option B, as it saves computations by not downloading the images. However, serving images from external websites also gives me a couple of concerns: How can I check if there actually is an image on the URL, when I don't download the image? Note: I'm using Python Will the size of the external images affect my performance? When I download the images, I can make sure that they have a specific (small) size that fits my pages. I will load a lot of images, e.g. 20 30x30 size images in a grid, on a single page. External images may be a lot larger than the intended size on my page, so I will have to implement height:30px;width:30px; or similar in the HTML. Won't the performance (page load time) take a huge hit, as the original images are actually 10x or 20x the size? Is there a way to solve this? *Note: ignore the concern of image rights, as that … -
unable to find timezone in django
What I am doing. I am working on a very basic django project. what is my problem. When I am loading my webpage (locally) it is showing following error on webpage. A server error occurred. Please contact the administrator and error that I saw on terminal is zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key utc' -
Login to django admin via requests
I want to log in on the django admin site via a python script using requests library. From another posts' answer (here) i figured using a requests.Session() would be appropriate. However upon trying the following code, i get an 403 - forbidden status code. url = 'url_to_django_admin' payload = {'username': 'some_username', 'password': 'some_password'} with reqeuests.Session() as s: r = s.post(url, data=payload) print(r) >>> <Response [403]> I checked credentials in the browser, so that should be fine. For the keys in the payload dict i tried both values of the forms input fields keys name and id (i think name would be correct) -
DRF serializer does not send the correct data from the request
I build an API endpoint that talks an image as input and print it on the screen, the problem is when I print the request.data it gives me the correct data, but when I pass this data to the serializer, DRF change it! serializer: class TestUploadImageSerializer(serializers.Serializer): images = serializers.ImageField() views: class TestUploadImageApi(APIView): def post(self, request): serializer = TestUploadImageSerializer(data=request.data) serializer.is_valid(raise_exception=True) print(f'request.data = {request.data} \n') print(f'serializer.data = {serializer.data} \n') return Response(status=status.HTTP_200_OK) I'm using Postman to send the image: This is the output for request.data and serializer.data request.data = <QueryDict: {'images': [<InMemoryUploadedFile: ikea3.png (image/png)>]}> serializer.data = {'images': None} So, the question is why serializer.data gives me these result?