Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: static files not connected
i cannot undestand why django can't load my static files. This is the structure: Here my settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] Here my main.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'styles/main.css' %}" /> <script src="{% static 'js/script.js' %}"></script> And this is the result: Can someone help me found the mistake? Thanks a lot! -
Pass Javascript variable into Django tag
as the title says I'm trying to replace a value in my Django tag with a Javascript variable. I'm not sure if it's even possible but here is what I have (The tag is between ``): const myTemplate = (list) => html` <form method="post" class="notes-form"> {% csrf_token %} {{ user.profile|meet_notes:15 }} <div> <button type="submit">Send</button> </div> </form> ` I would like to replace the 15 by a variable like ${list.met_profile.id} for exemple (this tag will render an input with a value of this variable, here 15). Thank you! -
Django Authentication module for connecting with Directory Service
I am building an web application using Python Django REST framework.I am looking for authentication module in Django that can be bind with Active Directory. Any suggestions ? -
Django TypeError - TypeError: issubclass() arg 1 must be a class
I want to migrate my config in django application, but below console isn 't working. python3 manage.py migrate python3 manage.py makemigrations Traceback (most recent call last): File "/usr/src/frontend/manage.py", line 22, in <module> main() File "/usr/src/frontend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mungmung01/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/mungmung01/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/mungmung01/.local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mungmung01/.local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/mungmung01/.local/lib/python3.9/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class I don't know what was wrong. My config in django application is very shorts. Here is my urls.py from django.contrib import admin from django.urls import path from mungmung01.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', MainPage.as_view()) ] And here is my models.py from django.db import models from django.db.models.deletion import CASCADE # 전체 데이터모델은 이곳에 구현되어 있습니다. # PositiveInteger = unsigned int입니다. class MainPageVisitor(models.Model): VisitorNum = models.PositiveIntegerField(primary_key=True, null=False) # 방문객번호 NumVisit = models.PositiveSmallIntegerField(null=False) # 방문한 횟수 ipAddress = models.GenericIPAddressField() # ip주소 TimeVisited = models.DateTimeField(null=False) # 방문시간 TimeLeft = models.DateTimeField(null=False) # 떠난시간 Service = models.SmallIntegerField() # 이용한 서비스. 1=홀랜드 | 2=철학 | 3=엔지니어링 | 4=질의응답 Here is my views.py from django.http import request … -
I need JavaScript to calculate the quantity and total price
if you select the Django option, you can select the quantity, and we are writing a code that calculates the total price by adding the option price and the product price. How can I write JavaScript that calculates quantity and total price in my code? When you select an option, the information for the option appears, and then adjusting the quantity is also recommended. I'd appreciate your help. <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div> </div> /*value.extra_cost = Option Additional Price*/ /*happgae = value added to product and option price*/ <script> $().ready(function() { $("#optionSelect").change(function(){ var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price … -
How can I change django default logout success template?
enter image description here by default its showing admin logout page. I tried path('logout/',auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), this is not working -
reverse referencing in query lookups that span relationships
In Django official doc, there is an example as below, from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline In below lookup, >>> Blog.objects.filter(entry__headline__contains='Lennon') Q: Even though one foreign key defined in Entry class is pointing to Blog, but there is no entry field defined in Blog class, how can above lookup refer to Entry class from Blog in the form of entry__headline? I did not see anywhere in official doc authorize this kind of usage.. -
Pass django templatetag return value in if statement
I want to use the return value of my templatetag in if statement. This is the templatetag # validate_bookmark.py from django import template from user.models import Bookmark register = template.Library() @register.simple_tag def validate_bookmark(post, user): if Bookmark.objects.filter(user=user, post=post).first() != None: return True return False Template {% load validate_bookmark %} {% if (validate_bookmark post_obj request.user) == True %} <!-- Something like this --> <button data-postpk="{{i.pk}}" class="**fw-bold** bookmarkBtn mx-3 n-border-outline n-border-outline far fa-bookmark px-0 py-0" style="font-size: 1.1rem;"></button> {% else %} <button data-postpk="{{i.pk}}" class="bookmarkBtn mx-3 n-border-outline n-border-outline far fa-bookmark px-0 py-0" style="font-size: 1.1rem;"></button> Any help is appreciated Thank you -
How can I use a serializer to retrieve data from a django model in a nested way?
I have a django model with 3 fields: "product", "price_1" and "price_2". I would like to serialize this model in a way that the result would be: { "product": "some product", "price": { "price_1": 15.00, "price_2": 25.00 } } I was able to reach this result by creating a model for the price and connecting it to the product model with a foreign key. #Models class Product(models.Model): product = models.CharField() price = models.ForeignKey(Price) class Price(models.Model): price_1 = models.FloatField() price_2 = models.FloatField() #Serializers class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ['price_1', 'price_2'] class ScheduleSerializer(serializers.ModelSerializer): price = PriceSerializer() class Meta: model = Product fields = [ "product", "price", ] It worked, but it's very ineffective. Is there a way for me to achieve the same result, but having only one model such as: class Product(models.Model): product = models.CharField() price_1 = models.FloatField() price_2 = models.FloatField() And it would be even better if I could have only the numbers without the word "price": { "product": "some product", "price": { 1: 15.00, 2: 25.00 } } Although the second result is better, I'd already be very happy if I could achieve the first one using only one model. Thanks in advance! -
Restrict notifications to following users with Django-Channels
I'm working on a concept and try to analyse how to set it up. To make it easier let's imagine it's a social network. You can follow people and people can follow you. When you follow someone and this person do actions on the app, all the followers should receive a notification about it. The app will be developped with Django and Django-channels. My question is what is the best architecture to implement for these notifications. I was thinking about creating a group for each user on connection then select every follower connected and add them to this group, then select every following and add the user to the groups but that will make me a huge number of groups. I'm a bit scared that it could impact the performances. Would love to have your opinion :) -
Django CSRF Middleware: Why is my request CSRF token different to the one sent in the request header?
For initial background information, I have a similar setup to this post - please note this is NOT my issue. My configuration is working, the browser accepts the CSRF Set-Cookie from the response. CSRF cookie is http only. I have the appropriate CORS settings. I have a separately hosted SPA where I'm currently testing this flow: SPA pings the backend server for a CSRF token. Make a login post request. Login is denied by 403 on the server due to the CSRF token not matching. See my screenshots. The first part of the screenshot shows that Djangos CSRF middleware found a token in my request starting with 'q1jHW', the second part of the screenshots shows that the same middleware is expecting the request to have a token starting with 'Mrmh9'. The final part of my screenshot shows that the login request my browser made DOES have the 'Mrmh9' CSRF Token in it's headers. Why is my requests token being changed by the backend and not having the expected token being updated? I believe the issue may be with HOW I'm setting the initial token: I'm simply using the get_token function from django.middleware.csrf and doing something like: response["X-CSRFToken"] = get_token(request) I … -
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?