Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to access django app on other android devices on my hotspot network
I created the django app and hosted the same on my laptop which was connected to my android mobile hotspot. Then I got the IP of my machine, using ipconfig Wireless LAN adapter Wi-Fi: Connection-specific DNS Suffix . : Link-local IPv6 Address . . . . . : fe80::2d4e:f2c4:bc88:e67e%5 IPv4 Address. . . . . . . . . . . : 192.168.43.69 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.43.1 then I added the same to ALLOWED_HOSTS = ['192.168.43.69'] and ran the server using python manage.py runserver 192.168.43.69:8000 now when I am accessing the same on my laptop, I am able to access the device but when I am trying to access the same on my mobile device I am getting the same typical chrome connection error The site can't be reached 192.168.43.69 took too long to respond ERR_CONNCTION_TIMED_OUT How can I resolve the same? -
Getting error while creating a Python Model
I am trying to create a multiple comparison model in Python. However it is giving me an error that the values for the code is incorrect. Can anyone help me with the same I am using models.append to create a model -
Write properly appointment database with time slot availabilities
My aim is to create an appointment system in Django able to create appointment between teachers and student with the possibility for teachers to choose their availabilities and for student to choose time slots according to teacher's availabilities. There are 2 classes : One is the class with the teacher's availabilities: the foreign key is the teacher and there are also the date and the start time and end time One is the class appointment with 2 foreign keys for both student and teacher EDIT: Here are the models : class Appointment(models.Model): student = models.ForeignKey('Student', null=True, on_delete=models.CASCADE) staff = models.ForeignKey('Staff', null=True, on_delete=models.CASCADE) date = models.DateField(null = True) timeslot = models.IntegerField(null = True, choices=TIMESLOT_LIST) @property def time(self): return self.TIMESLOT_LIST[self.timeslot][1] is_completed = models.BooleanField(default=False) is_confirmed =models.BooleanField(default=False) class AppointmentAvailability(models.Model): staff = models.ForeignKey('Staff', null = True, on_delete = models.CASCADE) date = models.DateField(null = True) timeslot = models.IntegerField(null = True, choices=TIMESLOT_LIST) But now how to withdraw an time slot availability in the teacher's class availabilities to not allow student to ask an appointment at the same time ? -
Cant send subject in email - python
when i send an email message like this i cant get the subject get into the message(i get it in the body). what can i do to change it? thank you! def SendEmailNotHTML(EmailToList,EmailBody,EmailSubject): mail_from = settings.SMTP_USER try: for current_mail_to in EmailToList: fromaddr = settings.SMTP_USER toaddrs = current_mail_to msg = "\r\n".join([ "Subject: {0}".format(EmailSubject), "", "{0}".format(EmailBody) ]) print(msg) my_email = MIMEText(msg, "plain") username = settings.SMTP_USER password = settings.SMTP_PASSWORD server = smtplib.SMTP('smtp.gmail.com:25') server.ehlo() server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, my_email.as_string()) server.quit() except Exception as e: print('cant send email' + str(e)) -
ImportError: cannot import name 'NinjaAPI' from 'ninja'
I am working on the Django ninja rest framework. the project is working fine on my machine, but when I try to run it in a virtual environment (venv) and install all requirements.txt including django-ninja it raise an error (ImportError: cannot import name 'NinjaAPI' from 'ninja'). These are my requirements.txt asgiref==3.4.1 cffi==1.14.6 cryptography==3.4.7 dj-database-url==0.5.0 Django==3.2.6 django-heroku==0.3.1 django-ninja==0.13.2 gunicorn==20.1.0 jwt==1.2.0 ninja==1.10.2 psycopg2==2.9.1 psycopg2-binary==2.9.1 pycparser==2.20 pydantic==1.8.2 PyJWT==2.1.0 pytz==2021.1 sqlparse==0.4.1 typing-extensions==3.10.0.0 whitenoise==5.3.0 Python version Python 3.9.0 pip version: pip 21.2.3 -
How to add function for counting correct answer in django api?
I am creating quiz application in django .I created result page ,but in result page every time it shows correct ans = 0 ..plz suggest how can i change logic behind this ...plz...plz **Code for view.py ** from django.shortcuts import render,redirect from django.contrib.auth import login,logout,authenticate from .forms import * from .models import * from django.http import HttpResponse # Create your views here. def home(request): if request.method == 'POST': print(request.POST) questions=QuesModel.objects.all() score=0 wrong=0 correct=0 total=0 for q in questions: total+=1 print(request.POST.get(q.question)) print(q.ans) print() if q.ans == request.POST.get(q.question): score+=10 correct+=1 else: wrong+=1 percent = score/(total*10) *100 context = { 'score':score, 'time': request.POST.get('timer'), 'correct':correct, 'wrong':wrong, 'percent':percent, 'total':total } return render(request,'result.html',context) else: questions=QuesModel.objects.all() context = { 'questions':questions } return render(request,'home.html',context) Code for Model.py from django.db import models # Create your models here. class QuesModel(models.Model): question = models.CharField(max_length=200,null=True) op1 = models.CharField(max_length=200,null=True) op2 = models.CharField(max_length=200,null=True) op3 = models.CharField(max_length=200,null=True) op4 = models.CharField(max_length=200,null=True) ans = models.CharField(max_length=200,null=True) def __str__(self): return self.question -
django Field 'id' expected a number but got <built-in function id>
I'm learning this tutorial about django todoapp. I want to display all user's content (their todolists) and well im getting that error see the title I'm using google's login auth here's my views.py def todoView(request,): all_todo_items = Todoitem.objects.filter(userid=id).values_list('id', flat=True) return render(request, 'todoapp.html', {'all_items': all_todo_items}) here's my models.py class Todoitem(models.Model): content = models.CharField(max_length=100) userid = models.ForeignKey(AuthUser, models.DO_NOTHING, db_column='userid', blank=True, null=True) class Meta: managed = False db_table = 'todoitem' def __str__(self): return self.content class AuthUser(models.Model): password = models.CharField(max_length=128) username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) class Meta: managed = False db_table = 'auth_user' here's my todoapp.html {% load socialaccount %} <body> {% if user.is_authenticated %} <p>Welcome, {{ user.username }} !</p> {% else %} <h1>My Google Login Project</h1> <a href="{% provider_login_url 'google' %}">Login with Google</a> {% endif %} <h2>My Personal TodoApp Project</h2> <br> <table> <tr> <th colspan="2">List of Todos</th> </tr> {% for todo_items in all_items %} <tr> <td>{{todo_items.content}}</td> </tr> {% endfor %} </table> </body> -
In this nested list replace hello into goodbye
l = [3,7,7,78,12,[1,4,'hello']] Below Ans dose not shows output : l[4][2] = "goodbye" print(l) -
Python/Django 'OperationalError' in admin Django Rest Framework (DRF)
I keep getting the Operational error below in my Django admin when I try to update a models table. I'm trying to add a new field to the polls table. What could be the problem? Thanks in advance! OperationalError at /admin/vote/poll/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://localhost:8000/admin/vote/poll/add/ Django Version: 2.0.3 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: D:\Studio\Python\REST\elections\env\Scripts\python.exe Python Version: 3.9.0 Python Path: The polls model: models.py class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) The urls.py code: urlpatterns = [ path("polls/", PollList.as_view(), name="polls_list"), path("polls/<int:pk>/", PollDetail.as_view(), name="polls_detail"), ] -
Python/Django 'Type object is not iterable' Django Rest Framework (DRF)
I'm trying to GET fetch my REST API in DRF, but keep getting the error below. What could be the problem? Thanks! Internal Server Error: /polls/ ..... ..... TypeError: 'type' object is not iterable [08/Aug/2021 07:02:50] "GET /polls/ HTTP/1.1" 500 100344 Not Found: /favicon.ico [08/Aug/2021 07:02:53] "GET /favicon.ico HTTP/1.1" 404 3415 The apiviews code: apiviews.py class PollList(generics.ListCreateAPIView): queryset = Poll.objects.all() serializer_class = PollSerializer The polls code: models.py class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) -
Django user token is not getting authenticated by the user by which it is created
i Create a views function to set the user.is_active to true with the help of the link to activate the user account in django The link contains the uidb64 and token i genrate the token while signup and send that link by email by that is not getting authanticated with the user here is the link sending function def register(request): error = None if request.method == 'POST': form = RegisterUser(data= request.POST) email = request.POST['email'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] phone_number = request.POST['phone_number'] password = request.POST['password'] password1 = request.POST['password1'] username = request.POST['email'] if (email) and (first_name) and (last_name) and (phone_number) and (password) and (password1) and (username): try: user = Account.objects.get(username = username) error = 'user with this email already exists' return render(request, 'account/register.html', {'error':error}) except Account.DoesNotExist: if password == password1: user = Account.objects.create_user(email= email,first_name= first_name,last_name= last_name,password= password, username=username) user.phone_number = phone_number # user activation current_site = get_current_site(request) email_subject = 'Activate your account' message = render_to_string('account/email.html',{'user': user , 'domain':current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)) , 'token':default_token_generator.make_token(user) }) email_from = settings.EMAIL_HOST_USER to_email = email send_email = EmailMessage(email_subject, message , to=[email]) send_email.send() user.save() print(user) else: error = "Passwords didn't match" return render(request, 'account/register.html', {'error':error}) else: error = 'Fill the form correctly' return render(request, 'account/register.html', {'error':error}) context = … -
Error Django Models - ForeignKey and SQLSever
guys. I'm doing some tests with django and sql server and I always get this error when I need to use ForeignKey in the models. Does anyone know the reason? Thank you in advance. -
How to sum up entire column of a table values in django website?
I am very new to programming. I want to sum up my entire column payment_amount. I don't know which code should I use to sum up entire column and save it on home server. I have tried to create a function but it didn't work. Can I use multiple function on same page or will have to write all different function in same def function()? I will be very grateful for your kind help. HTML part: I <h1>Hellow</h1> {% extends 'base.html' %} {% block content %} Payment Completed <table border="1"> <tr> <th>Name</th> <th>Mobile</th> <th>Payment</th> </tr> {% for payment in payments %} <tr><td>{{ payment.payee_name }}</td><td>{{ payment.phone_number }}</td><td>{{ payment.payment_amount }}</td></tr> {% endfor %} {% for totalpayment in totalpayments %} <tr> <td>{{ Payment.totaldonation }}</td> </tr> {% endfor %} </table> {% endblock %} admin.py part: from django.contrib import admin from .models import ToDo, Payment class PaymentAdmin(admin.ModelAdmin): list_display = ('payee_name', 'phone_number', 'payment_amount') admin.site.register(Payment, PaymentAdmin) **forms.py part:** from django.forms import ModelForm from .models import ToDo, Payment class PaymentForm(ModelForm): class Meta: model = Payment fields = ['payee_name', 'phone_number', 'payment_amount'] models.py part: from django.db import models from django.contrib.auth.models import User from django import forms class Payment(models.Model): payee_name = models.CharField(max_length=50) phone_number = models.CharField(max_length=14) payment_amount = models.IntegerField() def __str__(self): return … -
Creating a new field to an extended user model every time a post is made by that user
I want my extended user model to look like what it does below, where I can upload an Image as many times as I want to that extended user model. With everything being in one model without having two separate models. Is there a way I can manipulate my extended user model to do that, without using a stacked inline model? -
Scrollspy not working at all - menu items not being highlighted
I'll preface by saying that I am a complete beginner with HTML, Bootstrap and CSS - I only started a few days ago. For the life of me I cannot seem to get Scrollspy to work. I know this question has been asked many times, and I've spent hours going through the solutions, but I have not found one that works for me. Below is my the start of my HTML, up to my nav: {% load static %} <!doctype html> <html lang="en" class="h-100"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Steven Cunden | Home</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/cover/"> <!-- Bootstrap core CSS --> <link href="/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"> <style type="text/css"> body{ position: relative; overflow-y: scroll; } </style> <!-- Custom styles for this template --> <!-- <link href="cover.css" rel="stylesheet"> --> </head> <section class="cover-thing first text-center"> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark" id='nb'> <div class="container-fluid"> <a class="navbar-brand" href="#">Steven Cunden</a> <div class="collapse navbar-collapse justify-content-end"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#test">TEST</a> </li> <li class="nav-item"> <a class="nav-link" href="#about-me">ABOUT ME</a> </li> <li class="nav-item"> <a class="nav-link" href="#aoi">INTERESTS</a> </li> <li class="nav-item"> <a class="nav-link" href="#skills">SKILLS</a> </li> </ul> </div> … -
Django model function implementation to auto initialize a particular field's value
I need to write a Django model function to calculate the value of an existing field. my models.py: class questionNumeric(models.Model): question = models.TextField() marks = models.IntegerField() correctAns = models.FloatField() class questionTureFalse(models.Model): question = models.TextField() marks = models.IntegerField() correctAns = models.BooleanField() class questionSet(models.Model): examName = models.CharField(max_length=200) questionNumeric = models.ManyToManyField(questionNumeric) questionTureFalse = models.ManyToManyField(questionTureFalse) totalMarks = models.IntegerField(default=0) As you can see here, each questionNumeric or questionTureFalse object has specific marks. Now I want to set my questionSet object's totalMarks field with- the summation of marks carried by all questionNumeric or questionTureFalse under this questionSet object. How can I write a Django Model function under questionSet to auto initialize totalMarks? -
Desing patterns in Django
I'm learning Desing Patterns and appling it into Python. I've work with Django, but I don't know how to apply a Factory method (for instance), into Django or I shouldn't use it in it. Thanks for your answers =) -
Django: Querying a stacked inline object (photo) that is connected to extended user model
I am trying to make an Instagram Clone. So what I'm trying to do here is query the user's photos that were uploaded and display them on the frontend. When I query into the stacked inline Uploads model I can get the photos to display on the frontend, but not the photos that belong to the user (all the photos in database display on the frontend). I tried to figure out a way to get all the photo's to go to the extended user model, but I couldn't figure a way to do that. Basically I'm trying to get the images that the user uploaded and if anyone could help that would be much appreciated. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True) first_name = models.CharField(max_length = 50, null = True, blank = True) last_name = models.CharField(max_length = 50, null = True, blank = True) phone = models.CharField(max_length = 50, null = True, blank = True) email = models.EmailField(max_length = 50, null = True, blank = True) bio = models.TextField(max_length = 300, null = True, blank = True) profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True) #uploads … -
django form field error_messages not working with IntegerField
This is my model : class Bid(models.Model): id = models.AutoField(primary_key=True) bid = models.IntegerField(verbose_name='Prix demandé', null=False, blank=False) note = models.TextField(verbose_name='Description', null=False, blank=False) date = models.DateField(auto_now_add=True) This is my form class BidForm(forms.ModelForm): class Meta: model = Bid fields = ['bid', 'note'] bid = forms.IntegerField(error_messages={'invalid': 'Please enter a valid bid'}) When the bid is invalid, I always get the default error message not the one I specificed Ensure this value is greater than or equal to 1 However it works if I add another field of another type, like CharField class BidForm(forms.ModelForm): .... bid = forms.IntegerField(error_messages={'invalid': 'Please enter a valid bid'}) text = forms.CharField(error_messages={'required': 'Please enter a valid text'}) Ensure this value is greater than or equal to 1. Please enter a valid text -
I deployed my app on digital ocean and every one can access the URL and the app except me I get error as shown in screenshot
it is a Django app on a ubuntu 20.04 server using nginx and gunicorn error i get -
Can Anyone Please solve this test Project (Django and Django Rest Framework)
Please solve this Test project. The instruction is available at the following link. https://bitbucket.org/staykeepersdev/bookingengine/src/master/ -
Disadvantages of launching multiple identical tasks in Celery (python)
could you please point this out... I have a task to generate a document (~5-6 seconds to generate a full doc) and also I have a platform with a user who can click on some choices (checkboxes) at the page (frontend part) and send a PATCH request with a new data. This action will change a model in database and also will launch described above task. So if user will click checkboxes multiple times (for fun or something like that) -> it will send multiple PATCH requests to update table in database and at the same time it will launch same tasks to generate document. But these tasks are useless except of the last one, because the last task will generate a document with the right data (final click of user by choice "checkbox" in choices) So my question is as follows: Do I need to worry about all other useless almost identical tasks if I need only the last one? Should I use cron at this case and to launch a generate document task (every 1 minute) if the table in database changed or should I leave the above described functionality with multiple tasks? Will it affect my application … -
this iç ã têstto sẽ a slũg in actón
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -
Comment doesn't submit to the database
I am having a hard time to get the comment object work, anytime i comment and submit it shows the the JsonResponse but wont submit to the database. Here is my view to create comments def blog_detail(request,post_id): user = request.user post = get_object_or_404(Post, pk=post_id) if request.method == 'POST': post_id = request.GET.get('post_id') body = request.POST['body'] user_obj = Account.objects.get(username=request.user.username) create_comment = Comment.objects.create(post=post_id, name=user_obj, body=body) create_comment.save() return JsonResponse({'body':body}) return render(request,'blog/blog_detail.html', {'post':post}) Here is my comment model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='commentts') name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="commentts") body = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) This is my HTML code for the comment form! <form for="id_body" action="." method="POST"> {% csrf_token %} <div class="bg-gray-100 rounded-full relative dark:bg-gray-800 border-t" for="id_body" > <input placeholder="Add your Comment.." name="body" id="id_body" class="bg-transparent max-h-10 shadow-none px-5"> <div class="-m-0.5 absolute bottom-0 flex items-center right-3 text-xl"> <a href="#"> <ion-icon name="happy-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon> </a> <a href="#"> <ion-icon name="image-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon> </a> <a href="#"> <ion-icon name="link-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon> </a> </div> </div> <input class="btn btn-outline-success my-3" id="send_btn" type="submit" value="Comment"> </form> This is the URL as well. path('post/<int:post_id>/',views.blog_detail, name='detail'), -
How to pass encrypted string in URL
I am encrypting user invite information and adding it to the URL so that when a user receives a registration link certain information will already be filled in. The way I am encrypting it is by using the django.core.signing package as such: def encrypt_object(self): """ Encrypts the Private Key. The cryptographic key is appended to the URL of the invite. """ return signing.dumps({"pk": f'{self.pk}'}) def decrypt_object(self, signed_obj): """ Decrypts the Private Key which is passed as an argument on the invite URL. """ return signing.loads(signed_obj) I would like to pass the encrypted pk in the URL like this: path('register/<str:encrypted_pk>/', views.register, name='register'), but I get a 404 error. How can I accomplish this?