Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django web page opening but not loading in browser
I am using Visual Studio Code for coding python using django framework. But when I open the http://127.0.0.1:8000/ on my browser it always shows waiting for 127.0.0.1:8000 but he page never loads -
.map is not a function reactjs
So I'm following this tutorial, https://www.udemy.com/course/django-with-react-an-ecommerce-website/, but with some custom HTML template that I made. I keep getting the error .map() is not defined. As the udemy course is more so for Django developers, I am a little lost of the react side. Below is my HomeScreen.js page that is supposed to display products. import React from 'react'; import products from '../products' function HomeScreen() { return ( <section class = "w3l-ecommerce-main"> <div class = "ecom-contenthny py-5"> <div class = "container py-lg-5"> <h3 class = "hny-title mb-0 text-center">Shop With<span>Us</span></h3> <p class = "text-center">Handpicked Favourites just for you</p> <div class = "ecom-products-grids row mt-lg-5 mt-3"> { products.map(products => ( <div key = {products._id} class = "col-lg-3 col-6 product-incfhny mt-4"> <div class = "product-grid2 transmitv"> <div class = "product-image2"> <a href = "#"> <img class = "pic-1 img-fluid" src = "/images/shop-1.jpg"/> <img class = "pic-2 img-fluid" src = "/images/shop-11.jpg"/> </a> <ul class = "social"> <li><a href = "#" data-tip = "Quick View"> <span class = "fa fa-eye"></span></a></li> <li><a href = "#" data-tip = "Add to Cart"><span class = "fa fa-shooping-bag"></span></a></li> </ul> <div class = "transmitv single-item"> <form action="#" method = "post"> <input type="hidden" name="cmd" value="_cart"> </input> <input type="hidden" name="add" value="1"> </input> <input type="hidden" … -
VSCode not auto completing python module import
My VSCode editor suddenly stopped listing suggestion when am running import statements. ie. from django.shortcuts import render, redirect, get_object_or_404, get_list_or_404, HttpResponse normally when I type: from django. it should suggest all packages in django or when I type from django.shortcuts import it again should suggest render, get_object_or_404 etc. But this is not more happening. I have to painstakingly type these out myself. please any help would be highly appreciated. Thanks a lot. -
Including another URLconf doesent work, in parent app
I'm facing a problem in the last few days with Django URLs and include(). I'm doing an toturial online to create a chat app using django, and I'm using the newest version of django. my parent app named mySite, and my sub-app called chat. chat.urls from django.urls import path from .import views urlpatterns = [ path('', views.index), ] chat.views from django.shortcuts import render def index(request): return render(request , 'chat/index.html') . ##########################################################################################3 I'm trying to include the chat.URLs in the parent app mySite.urls but I'm getting an error page after I runserver. i tried to migrate and still is not working. mySite.URLs from django.contrib import admin from django.urls import path from django.urls import include from chat import urls urlpatterns = [ path('admin/', admin.site.urls), path('chat/', include('chat.urls')), ] -
How to fix slugs implemented in Django?
I am using django to create a blog where all posts are shown on the home page as well as on pages depending on their subject. While the basics as shown work, I am having great difficulty with the following: For each subject page I would like the url to include ~/subject_slug/ Currently I am getting ~/subject/subject_slug When I eliminate subject/ from urls.py (line 8), I get the desired ~/subject_slug only. HOWEVER, the individual posts cannot now be accessed. Error: Subject.DoesNotExist: Subject matching query does not exist. Line 21 in views.py is pointed to. There I have tried to include either Subject, or subject, in the bracket before subject_slug=subject_slug. Unfortunately that shows: UnboundLocalError: local variable 'subject' referenced before assignment. Attempts with adding subject to the post_detail view have also not worked. For each post I would like the url to include ~/subject_slug/slug/ Therefore I added str:subject_slug/ to urls.py line 10. This throws the error: NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with arguments '('a-slightly-longer-post',)' not found. 1 pattern(s) tried: ['(?P<subject_slug>[^/]+)/(?P[^/]+)/$']. models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify class Subject(models.Model): subject = models.CharField(max_length=200) subject_slug = … -
Connect uploaded file to a post in Django
I am trying to connect an uploaded document with the related post in Django. The idea is that when a user creates a post (I called it seed in my code), he can upload a document with it if he wants to. I tried using the joint method to do so, but it is not working (either telling me it expects an "str" and not an "int" or telling me the ForeignKey condition is not working). Is there any way to then connect those two classes, and successfully upload a file? Thank you for any help!! Here is what I tried: views.py """ def seed_create(request): if request.method == "POST": seed_form = SeedForm(request.POST) docu_form = DocumentForm(request.POST, request.FILES) if seed_form.is_valid() and docu_form.is_valid(): seed_form.instance.user = request.user docu_form.save() seed_form.save() messages.success(request, 'Your seed was successfully created!') return redirect('seed:view_seed') else: messages.error(request, 'Please correct the error below.') else: seed_form = SeedForm(request.POST) docu_form = DocumentForm(request.POST, request.FILES) return render(request, "seed/create.html", context={"seed_form": seed_form, "docu_form": docu_form}) """ models.py """ def gallery_folder(instance, file): return '/'.join(['documents', instance.seed_related_id, file]) class Document(models.Model): seed_related = models.ForeignKey(Seed,on_delete=models.CASCADE,default=1) description = models.CharField(max_length=255, blank=True) file = models.FileField(default="No file",upload_to=gallery_folder) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title """ forms.py """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'file') """ -
pass form instance in django formview
I have a forms.py file as class SocialMediaForm(forms.ModelForm): class Meta: model = SocialMedia fields = "__all__" exclude = ("doctor",) labels = {} widgets = { "whatsapp": forms.TextInput(attrs={"class": "form-control"}), "telegram": forms.TextInput(attrs={"class": "form-control"}), "facebook": forms.TextInput(attrs={"class": "form-control"}), "instagram": forms.TextInput(attrs={"class": "form-control"}), "linkedin": forms.TextInput(attrs={"class": "form-control"}), } with a view.py file class SocialMediaProfile(FormView): model = DoctorSocialMedia form_class = SocialMediaForm success_url = "." template_name = "doctor/social_media_profile.html" the question is how could i pass a form instance to template in FormView view as SocialMediaForm(instace=someInstance) # in fun based views. -
Unable to send e-mail from Django EmailBackend but it works by simply using smtplib with the same SMTP parameters
I'm trying to send an e-mail to the user on registration using taigaio, which is based on Django. Here are my current SMTP settings (I didn't yet switched to SSL but I'm planning to): DEFAULT_FROM_EMAIL=noreply@server.org EMAIL_HOST_USER=noreply EMAIL_HOST_PASSWORD="thesupersecretpassword" EMAIL_HOST=smtp.server.org EMAIL_PORT=25 EMAIL_USE_TLS=False EMAIL_USE_SSL=False But the browser raises a 500 Internal Server Error and I got on the server side: (...) File "/taiga-back/taiga/auth/services.py", line 62, in send_register_email return bool(email.send()) File "/opt/venv/lib/python3.7/site-packages/django/core/mail/message.py", line 306, in send return self.get_connection(fail_silently).send_messages([self]) File "/opt/venv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/opt/venv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 70, in open self.connection.login(self.username, self.password) File "/usr/local/lib/python3.7/smtplib.py", line 710, in login raise SMTPException("No suitable authentication method found.") smtplib.SMTPException: No suitable authentication method found. I also tried to simply send a mail using smtplib as follow (inspired from https://mkyong.com/python/how-do-send-email-in-python-via-smtplib/) to see if I can figure out what's wrong: import smtplib to = 'me@gmail.com' email_user = 'noreply' smtpserver = smtplib.SMTP("smtp.server.org", 25) header = 'To:' + to + '\n' + 'From: ' + email_user + '\n' + 'Subject:testing \n' msg = header + '\n Sending test message. from noreply@server.org \n\n' smtpserver.sendmail(email_user, to, msg) smtpserver.close() And it works fine, I do receive that e-mail. Did I miss something in the Django config for sending e-mails? -
Creating a Formset which relates to Custom User (AbstractUser)
I have a use case here and I don't know how to go about it. I have Custom User and this works well when adding a new user. But then I have another model which I would like the Custom User to populate. It is kind of link a main form subform approach but no data on the main form is going to be edited but only creating new records on the formset (subform). from django.core.validators import RegexValidator from sos.models import Company from django.db import models from django.contrib.auth.models import AbstractUser from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse # page 138 Django for Beginneers # Create your models here. # https://stackoverflow.com/questions/19130942/whats-the-best-way-to-store-phone-number-in-django-models/19131360 class CustomUser(AbstractUser): position = models.CharField(max_length=30, null=True ) email = models.EmailField(null=True, blank=False, unique=True ) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") mobile_phone = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=True, unique=True) date_created = models.DateTimeField(auto_now_add=True, editable=True) is_staff = models.BooleanField(verbose_name="Is Staff Admin?", help_text="Designates whether this user should be able to log in the Admin Interface.") company = models.ForeignKey(Company , on_delete=models.CASCADE, verbose_name="Company Name") def __str__(self): return self.username def get_absolute_url(self): return reverse("customuser_detail", args=[str(self.id)]) class Meta: ordering = ["username"] # email_address = models.EmailField(null=True, blank=False, unique=True ) class … -
Simplest example for Django Meta (SEO)
I want to add these meta tags to every article in a Django blog: title, description, keywords I'm using : Python 3.7, Django 3 I've been searching for it and found DJANGO-META package best to use (in this link : djangopackages.org/grids/g/seo/ ) mostly because of the regular updates. Other packages like DJANGO-SIMPLE-SEO and DJANGO-SEO2 meet my needs but they don't update regularly and are not compatible with the newer versions of Django. The problem is that the DJANGO-META package is not easy to understand (at least for me :) ). Can anyone please explain how to implement the DJANGO-META in a project with the easiest example possible? -
Pdf file created throw following error, file response has no read attribute
I am trying to save pdf file inside directory , pdf file is properly created but it does not contains data and throw error. def file_pdf_to_merge(id): flow_obj=flow_obj_for_display(id) buffer = io.BytesIO() doc = SimpleDocTemplate(buffer) doc.build(flow_obj) buffer.seek(0) file_nm=file_name_only(id) response= FileResponse(buffer,as_attachment=True,filename=file_nm) fs=FileSystemStorage() if fs.exists(file_nm): fs.delete(file_nm) fs.save(file_nm,response) code throws following error. I think due to this error pdf file created is also corrupt or not properly decoded. 'FileResponse' object has no attribute 'read' thanks -
When I Submit Form I Got This Errors Field 'id' expected a number but got Why i got this errors ? What's wrong in my code :(
views---------- def update(request): if request.method == 'POST': aa = Add_Ep(request.POST) print("this is id:") Title = Add_Ep.Ep_Title print(Add_Ep) aa.save() return redirect('/') else: aa = Add_Ep() Form class add_ep(ModelForm): class Meta: model = Add_Ep fields = "__all__" Error: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['UTwwWtdY9Vy0L6BzYL5jK9SPRqBFsJaBpGwxIOtqdD5kDQC7CRiyPSDxC0rbUo4g'], 'Ep_Title': ['title'], 'CreatorsNote': ['this is creaters note555'], 'series': ['2']}>. -
Django Many-To-One Relationship add data to Many side
I have two models like below. I'm using Django restframework. class Family(models.Model): name= models.CharField(max_length=100) class Parishioner(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) family = models.ForeignKey(Family, on_delete=models.CASCADE) There are my ViewSets class FamilyViewSet(viewsets.ModelViewSet): queryset = Family.objects.all() serializer_class = FamilySerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) class ParishionerViewSet(viewsets.ModelViewSet): queryset = Parishioner.objects.all() serializer_class = serializers.ParishionerSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) These are my Serializers class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'name') read_only_fields = ('id',) class ParishionerSerializer(serializers.ModelSerializer): class Meta: model = Parishioner fields = ('id', 'first_name', 'last_name', 'family') read_only_fields = ('id',) depth = 1 So basically Parishioner can have one Family. Family has multiple members(Parishioners) Currently I have to go to all Parishioners and select the Family. is it possible to add a field called members to Family model, where members would be an Array of Parishioners ? or is there any other way to handle this ? -
How to correctly 1.Implementing slugs in Django? 2. Instantiate subject in Django? 3. Extend base.html in Django?
I am using django to create a blog where all posts are shown on the home page as well as on pages depending on their subject. While the basics as shown work, I am having great difficulty with the following three issues: For each subject page I would like the url to include ~/subject_slug/ Currently I am getting ~/subject/subject_slug When I eliminate subject/ from urls.py (line 8), I get the desired ~/subject_slug only. HOWEVER, the individual posts cannot now be accessed. Error: Subject.DoesNotExist: Subject matching query does not exist. Line 21 in views.py is pointed to. There I have tried to include either Subject, or subject, in the bracket before subject_slug=subject_slug. Unfortunately that shows: UnboundLocalError: local variable 'subject' referenced before assignment. Attempts with adding subject to the post_detail view have also not worked. For each post I would like the url to include ~/subject_slug/slug/ Therefore I added str:subject_slug/ to urls.py line 10. This throws the error: NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with arguments '('a-slightly-longer-post',)' not found. 1 pattern(s) tried: ['(?P<subject_slug>[^/]+)/(?P[^/]+)/$']. This part of base.html is repeated on each page: DR SMART.INFO the web site for the analytical rugby fan However this part only shows on index.html <p> <ul> {% for … -
How can I implement two kinds of login with Django?
How can I implement two kinds of logins with Django? For example, 1, Employee login - Employee page 2, Supervisor login - Supervisor page. -
annotate group by in django
I'm trying to perform a query in django that is equivalent to this: SELECT SUM(quantity * price) from Sales GROUP BY date. My django query looks like this: Sales.objects.values('date').annotate(total_sum=Sum('price * quantity')) The above one throws error: Cannot resolve keyword 'price * quantity' into field Then I came up with another query after checking this https://stackoverflow.com/a/18220269/12113049 Sales.objects.values('date').annotate(total_sum=Sum('price', field='price*quantity')) Unfortunately, this is not helping me much. It gives me SUM(price) GROUP BY date instead of SUM(quantity*price) GROUP BY date. How do I query this in django? -
IntegrityError not thrown during create within transaction.atomic()
I want to create a Car with an FK to an Engine. I also want to save a record to an audit table that Car has been created; I'm including the Engine's id within that audit record. I'm using the Django Rest Framework. Here's my serializer code for "create": @transaction.atomic def create(self, validated_data): try: with transaction.atomic(): car = Car.objects.create(**validated_data) except Exception as e: raise serializers.ValidationError("my message") a_function_that_creates_an_audit_record() The problem is that, if engine_id=0 in validated_data and there is no Engine object with an id of 0, no Exception is thrown, and the except ... doesn't get triggered. Execution continues to a_function_that_creates_an_audit_record(), where I do something like car.engine.id and there I do get an IntegrityError saying that an Engine with an id of 0 doesn't exist. What am doing wrong? Is there something I'm missing? -
Django test if SMTPRecipientsRefused error is raised
I'm writing tests in Django for some functions but one of them causes me problem to test. Here is the part of the function: try: set_password_form = PasswordResetForm({'email': newuser.email}) if set_password_form.is_valid(): set_password_form.save( request=request, email_template_name='authentication/password_reset/password_reset_html_email.html', html_email_template_name='authentication/password_reset/password_set_email.html', subject_template_name='authentication/password_reset/password_set_subject.txt' ) messages.success(request, "The user {} has been created. A mail has been sent foir setting the password".format( newuser.fullname())) return redirect('authentication:users') except SMTPRecipientsRefused: form.add_error('email', 'This email address does not exist') messages.error(request, "Some data are not valid") I would like to test that the exception is raised when giving a wrong email but I have absolutely no clue how to do that according to the fact that Django doesn't try to send the mail in the tests. -
django mysql and Big Sur
Some trouble after Big Sur update I use Django 2.1.15 and Python 3.8 according to posts and documentation I installed the connector brew install mysql-connector-c and pip install mysql-python after I install mysql brew install mysql and the client pip install mysqlclient try to run django and i get: django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 54") This is my setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'BATABASE', 'USER': 'sa', 'PASSWORD': 'password', 'HOST': '192.168.1.10', 'PORT': '1433', -
Django : Not able to handle Multiple post request on the same page / FormHi
i have a code which should handle multiple post request on the same page . it has two button in html page inside a single form . It is taking the post value from first button but not the second . no idea why when i include the second button and click on first it says the second button not found . Can anyone please help me solve this issue . index.html <input type="submit" style="background-color:#FFFF66;color:black;width:150px; height:40px;" name="ServerDetails" value="ServerDetails"/> <br><br> <input type="submit" style="background-color:#FFFF66;color:black;width:150px; height:40px;" name="GenerateFile" value="GenerateFile"/> views.py if request.method == 'POST': if request.POST['ServerDetails']: print("Inside Server Details") if request.POST['GenerateFile']: filename = request.POST['patchconfigofpg3'] print(filename) models.py class course(models.Model): patchconfigofpg3 = models.CharField(max_length=100) so when i click on first button it is throwing me the below error : -
Error: invalid input syntax for type numeric: "21/4/2020 01:52:56.2751+00" But there is no type numeric
I have this error in PostGreSQL running a simple select query: select * from public.jaap_rent ERROR: invalid input syntax for type numeric: "21/4/2020 01:27:26.357908+00" The thing is, in this view, there are no numeric column. There are 3 timestamp with timezone columns, which is where the problem come from. Selecting any other column is completely normal. This is how the timestamp columns defined: to_timestamp(( CASE WHEN ((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text) ~~ '%E9'::text) THEN ((((replace((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text), 'E9'::text, ''::text))::double precision * ('1000000000'::numeric)::double precision))::integer)::numeric WHEN (((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text))::numeric > ('100000000000'::bigint)::numeric) THEN (((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text))::numeric / (1000)::numeric) ELSE ((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text))::numeric END)::double precision) AS first_scrape_date I updated the table using an old Django system. However, another view without being updated also had this issue that we've never previously experienced. I don't have a lot of experience with SQL so after some looking I still don't know where to start to solve this issue. -
How to implement django rest api with phone otp based authentication
I am tried and succeed send otps and verifies otps. How to create custom user model for Django phone otp based authentication after entering otp how to check particular phone number with that otp, after verification how to create jwt token using phone number.... please reply if any knows as early as possible. -
How to use if else in django template
I have a part of the registration form that I wish to hide from third party viewers. Basically, it can only be seen on registration and the user of the account. I thought this is the correct syntax but it gavve me a TemplateSyntaxError Could not parse the remainder: '(request.user.is_authenticated' from '(request.user.is_authenticated' {% if (request.user.is_authenticated and request.user.account_type == 1) or not request.user.is_authenticated %} -
I want to serve a Django website from a Raspberry pi, setup as an access point in a standalone network (not connected to the internet)
I am working on a project to serve a django website from a raspberry pi thatis set up as an access point in a standalone network(not connected to the internet) just a minimum pi setup,am able to set it up as a wifi access point, but the challenge now is deploying the django website and serving it over the wifi access point to any connected device. am hoping somone could guid me through this orpoint me to any link with a guide to solve this -
Django Ordering First Column Groupings by Max Value in Second Column Per Group
Given a Model in Django with fields/values as shown: Group Votes A 5 B 2 B 7 A 3 it's easy to use class Meta: ordering = ['group', '-votes'] to return Group Votes A 5 A 3 B 7 B 2 How could this be modified so that the Group is also ordered by the max Votes value within each Group as shown: Group Votes B 7 B 2 A 5 A 3