Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select only the options that are related to another model in Django
I'm building a student/school app in which a student can belong to only one school and can choose Course options for that School they're in. Currently, I'm doing it the wrong way by having the course field at Student relate do Course, which will of course provide the entire list of courses in my app. What I'd like my app to be able to do is select only from courses that that school have added as their courses. How to do that? class Course(models.Model): name = models.CharField(max_length=32) class School(models.Model): name = models.CharField(max_length=32) courses = models.ManyToManyField(Course) class Student(models.Model): name = models.CharField(max_length=32) school = models.ForeignKey(School, on_delete=models.CASCADE) course = models.ManyToManyField(Course) # change 'Course' for ??? -
How to display content from many-to-one relationship
So I'm going crazy trying to figure out what seems like it should be a dead-simple task. I'm making a portfolio site. It has 2 models, Project and Image. Project contains most of the data for each project, while Image is in a many-to-one relationship to supply Project with a variable number of images per Project. On the homepage, I would like to show each project in its own section, and the images for each project in their respective sections. Currently, I have the projects displayed, and I'm able to display all the images from the database under each section: {% for image in images.all %} <img src="{{ image.image.url }}" alt=""> {% endfor %} I cannot, for the life of me, figure out how to display just the images for each respective section in the template, despite diving through pages of documentation, stack answers, and web posts. I've seen so many examples of how to query a model in this type of relationship from the views/model layers, but none of these seem to work in the template layer. I also don't know how I would perform the query on a different layer and send that through to the template, if … -
Django session variable not working when using AJAX
I have to delete an item and, for that, the user clicks in some "Delete" button in the page and Javascript makes an AJAX request (including the CSRF token in the header of the request) for a Django view to proceed with the deletion. My Django view is processing the request properly and deleting the item. But, in the same view, I do the following: Delete the item Put a message on the request.session['message'] Redirects to the 'list page' The 'list page' view checks if there is some 'message' in request.session and returns it to the page to show in some alert to the user. However, this mechanism is not working for this case, when using AJAX. It is like both the 'delete' view session and the 'list page' session are not the same, because it does not find the 'message' in the request.session. Here are some of the files involved. urls.py: ... urlpatterns = [ path('agenda', views.agenda, name='agenda'), path('<int:reuniao_id>/excluirReuniao', views.excluirReuniao, name='excluirReuniao'), ] views.py: def agenda(request): reunioes = ReuniaoEmpresa.objects.all() if 'message' in request.session: message= request.session['message'] del request.session['message'] else: message= '' context = { 'reunioes' : reunioes, 'message' : message } return render(request, 'agenda/agenda.html', context) def excluirReuniao(request, reuniao_id): reuniao = get_object_or_404(ReuniaoEmpresa, … -
Django - struggling to submit input data to database
I'm having some trouble sending data from a form to my database. The form: <form method="POST"> {% csrf_token %} <div class="banner" style="border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px;"> <h1 style="font-family: 'Baloo Chettan 2', cursive; font-size: 50px;">Title</h1> </div> <div class="colums" style="padding-left: 8px; padding-top: 20px;"> <div class="item"> <label for="i1"> Input One<span>*</span></label> <input id="i1" type="text" name="i1" placeholder="Data point 1" required/> </div> <div class="item"> <label for="i2"> Input Two<span>*</span></label> <input id="i2" type="text" name="i2" placeholder="Data point 2" required/> </div> <div class="item"> <label for="i3">Input Three<span>*</span></label> <input id="i3" type="text" name="i3" placeholder="Data point 3" required/> </div> <div class="item"> <label for="i4">Input Four<span>*</span></label> <input id="i4" type="text" name="i4" placeholder="Data point 4" required/> </div> <div class="btn-block"> <button type="submit" value="CalcData" style="width: 1052px; align-content: center; background-color: #3E828F;">Calculate</button> </div> </form> views.py: def save_data(request): if request.method == 'POST': if request.POST.get('i1') and request.POST.get('i2') and request.POST.get('i3') and request.POST.get('i4'): data=CalcData() data.i1= request.POST.get('i1') data.i2= request.POST.get('i2') data.i3= request.POST.get('i3') data.i4= request.POST.get('i4') data.save() return render(request, 'home.html') else: return render(request,'home.html') models.py: class CalcData(models.Model): i1 = models.DecimalField(max_digits = 100, decimal_places = 5) i2 = models.DecimalField(max_digits = 100, decimal_places = 5) i3 = models.DecimalField(max_digits = 100, decimal_places = 5) i4 = models.DecimalField(max_digits = 100, decimal_places = 5) datetime = models.DateTimeField(default=timezone.now) This POST doesn't end up in my database, so I'm not sure where it's going. I … -
Django rest_framework User Authentication with Android Firebase Auth
I want my users to login in my AndroidApp with Firebase Auth via their email or their Googleaccount. When the User logged in successfully how i authenticate the user in my django rest_framework backend? Can anyone help or found a tutorial to follow?? I really appreciate it. Thanks for help -
Django ModuleNotFoundError: No module named 'multiselectfield'
Just like the heading says. Everything works when I run the server locally but when I deploy i get this error. First time posting and I am very new to Django. I have re installed multiselectfield using pip3 and I have checked the version. I have also run pip freeze to check all the packages and I can see that multiselectfield is there. I checked my migrations and i can see it added to the database. File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'multiselectfield' from django.db import models from django.urls import reverse from phone_field import PhoneField from multiselectfield import MultiSelectField import datetime WEEKS = ( ('1', 'Week 1'), ('2', 'Week 2'), ('3', 'Week 3'), ('4', 'Week 4'), ('5', 'Week … -
TypeError: Cannot read property 'map' of undefined - react js
Please help me! I am stacked with this problem as I am undergoing this React + Django E-commerce project. This happens when I try bringing Redux to the Home Screen. The list of products in my store are unable to load and returns "TypeError: Cannot read property 'map' of undefined". Below are my codes, please help me. Thanks. FIRST CODE import React, { useState, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Row, Col } from "react-bootstrap"; import Product from "../components/Product"; import { listProducts } from "../actions/productActions"; function HomeScreen() { const dispatch = useDispatch(); const productList = useSelector((state) => state.productList); const { error, loading, products } = productList; useEffect(() => { dispatch(listProducts()); }, []); return ( <div> <h1>Latest Products</h1> <Row> {products.map((product) => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> </div> ); } export default HomeScreen; SECOND CODE import axios from 'axios' import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL } from '../constants/productConstants' export const listProducts = () => async (dispatch) => { try{ dispatch({ type: PRODUCT_LIST_REQUEST}) const { data } = await axios.get('/api/products/') dispatch({ type:PRODUCT_LIST_SUCCESS, payload: data }) }catch(error){ dispatch({ type:PRODUCT_LIST_FAIL, payload:error.response && error.response.data.message ? error.response.data.message : error.message, }) } } Screenshot … -
how do I create a regex for this in urls.py?
I want to create a regex that matches urls like this filmslist?name=allaboutmymother?director=pedroalmodovar in urlpatterns, I've put this: path('api/filmslist\?name=?P<name>(.*)\?director=?P<director>(.*)', views.filmslist) but it doesn't match. Thanks in advance -
Http redirects to https even though on free dyno
For some reason, even though I'm using the free dyno, my website still redirects http to https. This is what I want to happen, but I just don't understand why it is, since doesn't this only work for paid dynos? (I'm using Django and followed this guide to do the redirecting) Thank you. -
Django join sqlite
Hi fellow devs i have 3 simple tables which i want to retrive in one list as single objects and i have no clue how to start it. My models are: class Person(models.Model): name= models.CharField(max_length=50) surname= models.CharField(max_length=50) class Phone(models.Model): person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE) phone= models.CharField(max_length=50) class Email(models.Model): person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE) email = models.EmailField() -
'NoneType' object is not iterable problem solving
I want to show a list of question on my quiz.html templates... Here is my models.py from django.db import models # Create your models here. DIFF_CHOICE = ( ('easy','easy'), ('medium','medium'), ('hard','hard'), ) class Quiz(models.Model): name = models.CharField(max_length=120) topic = models.CharField(max_length=120) number_of_question = models.IntegerField() time = models.IntegerField(help_text="Duration in Minutes") required_score_to_pass = models.IntegerField(help_text="Required Score to Pass in %") difficulty = models.CharField(max_length=6,choices=DIFF_CHOICE) def __str__(self): return f"{self.name}-{self.topic}" def get_questions(self): self.question_set.all()[:self.number_of_question] class Meta: verbose_name_plural = 'Quizes' Here is my views.py def quiz_data_view(request,pk): quiz = Quiz.objects.get(pk=pk) questions = [] for q in quiz.get_questions(): answers = [] for a in q.get_answers(): answers.append(a.text) questions.append({str(q):answers}) return JsonResponse({ 'data' : questions, 'time' : quiz.time, }) and here is my quiz.html....and here i want to show my question list {% extends "base.html" %} {% load static %} {% block scripts %} <script src="{% static 'quizes/quiz.js' %}" defer></script> {% endblock scripts %} {% block title %} {{obj.name}} {% endblock title %} {% block content %} {{obj.name}} <hr> <form id ="quiz-form" class="mt-3 mb-3"> {% csrf_token %} <div id="quiz-box"></div> <button type="submit" class="btn btn-primary mt-3">Save </button> </form> {% endblock content %} Here is my js file...in my js file i used ajax... const url = window.location.href const quizBox = document.getElementById('quiz-box') let data $.ajax({ type: 'GET', … -
Django Report Card connection to Student model design
I have the two classes that will be used by Admin users to generate Forms in the Django's admin interface and displayed on the front-end using modelformset_factory. # Math, Language Arts, Physical Development etc... class Domain(models.Model): name = models.CharField(max_length=100, blank=False, null=True) grade = models.SmallIntegerField() def __str__(self): return self.name # Numbers, Math Operations, Shapes, Gross Locomotor Movement Skills etc... class Standard(models.Model): domain = models.ForeignKey('reportforms.Domain', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100, blank=False, null=True) assessed = MultiSelectField(choices=ASSESSED, max_choices=3, max_length=50, blank=False, null=True) # Trimesters this Standard is assessed (1,2,3) grading_scale = models.CharField(default='PROGRESS_INDICATOR', max_length=50, choices=GRADING_SCALE, blank=False, null=True) #A,B,C,D vs 1,2,3,4 ...etc display_order = models.SmallIntegerField(default=99, help_text="Order in which standard is displayed.") # Trimester Grade Received by Student # Hidden in admin.py t1 = models.CharField(choices=PROGRESS_INDICATOR, max_length=50, blank=True, null=True ) t2 = models.CharField(choices=PROGRESS_INDICATOR, max_length=50, blank=True, null=True) t3 = models.CharField(choices=PROGRESS_INDICATOR, max_length=50, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['domain', 'display_order'] My Question How do I create the relationship to a Student model and be able to enter grades for the student on the front-end. Front-End Screenshot I tried adding something like student = models.ForeignKey(Student) to my Standard model but this created a new Standard for every student report card created #view.py def EditStudentReportGrades(request, student_id): student = … -
i have some problems to deploy django project
I hope to deploy django-tutorial project. but when i excute the command, somthing wrong. uwsgi --http :8000 --home /home/ubuntu/myvenv/ --chdir /srv/django-tutorial/ -w mysite.wsgi this command is okay. sudo /home/ubuntu/myvenv/bin/uwsgi -i /srv/django-tutorial/.config/uwsgi/mysite.ini but it return "Internal Server Error" this is /srv/django-tutorial/.config/uwsgi/mysite.ini i think this file have some problems. [uwsgi] chdir = /srv/django-tutorial/ module = mysite.wsgi:application home = /home/ubuntu/myvenv/ uid = deploy gid = deploy http = :8000 enable-threads = true master = true vacuum = true pidfile = /tmp/mysite.pid logto = /var/log/uwsgi/mysite/@(exec://date +%%Y-%%m-%%d).log log-reopen = true -
Annotated queryset, same name as property on model instance not working
I would like some property to always be there on a model instance. But I also need to annotate it on a queryset for some views. Is this possible? Pseudo-code: Friend(models.Model): name= models.CharField() @property def current_location(self): return self.friendlocation_set.filter(departure_date=None).order_by( '-arrival_date').first() Location(models.Model): name=models.CharField() FriendLocation(models.Model): arrival_date = models.DateField() departure_date = models.DateField(blank=True, null=True) friend = models.ForeignKey('Friend', on_delete=models.CASCADE) location = models.ForeignKey('Location', on_delete=models.CASCADE) class FriendQueryset(models.Queryset): def annotate_current_location(self): last_location = Subquery(FriendLocation.objects.filter( friend=OuterRef('id'), departure_date=None).order_by('-arrival_date').values('location')[:1]) return self.annotate(current_location=last_location) What is the best way to do this? I'd like to keep the name the same. -
Continuous Query Notification (CQN) with Django rest framework python + oracle
im having troubles how to implement the CQN with django rest framework and python. I want when a change happen in the database (ORACLE DATABASE), my django could know about that and make the refresh of the information. Please guys help me, i was trying to find information about weeks -
How to nest two many-to-many field in Django ORM
I have a table that relates two tables, table Author and table Book. +----+------------+-----------+ | ID | Author(FK) | Book (FK) | +----+------------+-----------+ | 1 | 20 | 12 | | 2 | 20 | 35 | | 3 | 20 | 70 | | 4 | 25 | 15 | +----+------------+-----------+ I am using a serializer and my output looks like this: { "1": { "Author": "20", "Book": "12" }, "2": { "Author": "20", "Book": "35" }, "3": { "Author": "20", "Book": "70" }, "4": { "Author": "25", "Book": "15" }, } The desired output would be like this: [ { "author": 20, "books": [ 12, 35, 70 ] }, { "author": 25, "books": [ 15 ] } ] This is my serializer: class AuthorBooksSerializer(serializers.ModelSerializer): class Meta: model = AuthorBooks fields = '__all__' What should I do to merge all the books of an author into one array? -
Update profile changes with signals
There are two models and I want to update the profile bio via signals Models from django.contrib.auth.models import User from django.db import models class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) nickname = models.CharField(blank=True, null=True, max_length=50) location = models.CharField(blank=True, null=True, max_length=50) weight = models.DecimalField(null=True, max_digits=5, decimal_places=2) Signals from .models import * from django.dispatch import receiver from django.db.models.signals import post_save, m2m_changed @receiver(post_save, sender=User, dispatch_uid='') def receiver_func(sender, instance, created, update_fields, **kwargs): if created and update_fields == None: profile = Profile.objects.create(user=instance) @receiver(m2m_changed, sender=Website.users.through) def AutoUpdateBio(sender, instance, action, reverse, pk_set, **kwargs): if action == 'post_add': # ** Add user to website - instance: website if not reverse: # ! HOW TO IMPLEMENT THESE TWO LINES # ** Add website to user - instance: user else: # ! HOW TO IMPLEMENT THESE TWO LINES bio contains a list of websites for each user and the list has to be sorted and I need profile bio updated when websites are added or users are added in both ways I want profile to be updated. I commented on the lines that I have problems with -
How should I authenticate users in Nodejs with Django authentication
I'm using socket io from Nodejs to create a chat feature in my application which is mainly built using React+Django. I need to use Django's user authentication in Nodejs, so that users are authenticated before they can chat with other users. Here's my plan: When the user opens the chat feature, a post request is sent to the Django server containing the user's id and the user is authenticated. After successful authentication, the Django server sends a code to the Nodejs server, and the same code is sent to the user at the client side. Now, whenever the user sends a message, the codes are compared in the Nodejs server, and if they match, the message is sent. I'm not a pro in web technologies, and I'm pretty sure there are drawbacks to using this method so any help on its validity would be appreciated! (I know how to code it, just need to know if it's the right approach) -
heroku postgres psycopg2.errors.UndefinedTable
Would anyone have any tips for deploying heroku django app with the hobby free postgres version that heroku provides? This error below in the traceback almost seems similar when I was testing locally if I didnt do a python manage.py migrate in the django build process. Also new to django, heroku, and postgress to so tips greatly help. These are my steps using the heroku pipeline to deploy: git push heroku master heroku ps:scale web=1 heroku open This is the trace back through heroku logs when I try to view the webpage: 2021-04-28T15:42:39.226298+00:00 heroku[web.1]: State changed from crashed to starting 2021-04-28T15:42:46.842959+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -` 2021-04-28T15:42:50.000000+00:00 app[api]: Build succeeded 2021-04-28T15:42:50.613040+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-04-28T15:42:50.614019+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [4] [INFO] Listening at: http://0.0.0.0:38735 (4) 2021-04-28T15:42:50.614239+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [4] [INFO] Using worker: sync 2021-04-28T15:42:50.624501+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [9] [INFO] Booting worker with pid: 9 2021-04-28T15:42:50.648659+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [10] [INFO] Booting worker with pid: 10 2021-04-28T15:42:51.320006+00:00 heroku[web.1]: State changed from starting to up 2021-04-28T15:43:08.733160+00:00 app[web.1]: Internal Server Error: / 2021-04-28T15:43:08.733171+00:00 app[web.1]: Traceback (most recent call last): 2021-04-28T15:43:08.733172+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute 2021-04-28T15:43:08.733173+00:00 app[web.1]: … -
NGINX not serving media files
I'm hosting a django (wagtail) app on nginx and nginx does not seem to want to serve static files on a certain path. When i host the exact same path in my file structure on two different paths on the website, oen works and the other doesn't. Configuration seems to be exactly the same. I set it up to the same folder for testing purposes. My nginx config is as following server { server_name www.clt.be clt.be; location = /favicon.ico { access_log off; log_not_found off; } location /media/ { autoindex on; root /datadrive/apps/website_prod/clt_website/clt_website/clt_website; } location /static/ { root /datadrive/apps/website_prod/clt_website/clt_website/clt_website; } location / { include proxy_params; proxy_pass http://unix:/run/www-prod-gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.clt.be/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.clt.be/privkey.pem; # managed by Certb> include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = clt.be) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = www.clt.be) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name www.clt.be; return 404; # managed by Certbot } Has anyone encountered this problem before? I'm at a loss. Edit: the /media/ url is not working. -
Login with token django-rest-framework
how are you all? i working on a project with django rest framework i create the registration view without any problem,but in the login view i have an issue, when i try to log in the response return Invalid credentials note : i tried to login with email instead of username. the code: view.py class ObtainAuthTokenView(APIView): authentication_classes = [] permission_classes = [] def post(self, request): context = {} email = request.POST.get('username') password = request.POST.get('password') account = authenticate(email=email, password=password) if account: try: token = Token.objects.get(user=account) except Token.DoesNotExist: token = Token.objects.create(user=account) context['response'] = 'Successfully authenticated.' context['pk'] = account.pk context['email'] = email.lower() context['token'] = token.key else: context['response'] = 'Error' context['error_message'] = 'Invalid credentials' return Response(context) urls.py urlpatterns = [ path('login', ObtainAuthTokenView.as_view(), name="login"), ] i used this data to post : {"username":"x@example.com","password":"123456"} so why i facing this issue? thanks. -
Adding new object but change not binding data in form
I have problem when i add get_form in ModelAdmin to get request and current user i can add new object but when i what to change object data doesn't appear in form admin.py @admin.register(StaffLeave) class StaffLeaveAdmin(admin.ModelAdmin): model = StaffLeave exclude = [] readonly_fields = [] form = StaffLeaveForm list_display = ['staff', 'leave_type', 'date_of_leave', 'leave_end_date', 'academic_year'] def get_form(self, request, obj=None, **kwargs): StaffLeaveF = super(StaffLeaveAdmin, self).get_form(request, obj, **kwargs) class RequestStaffLeaveF(StaffLeaveF): def __new__(cls, *args, **kwargs): kwargs['request'] = request kwargs['user'] = request.user kwargs['instance'] = obj return StaffLeaveF(*args, **kwargs) return RequestStaffLeaveF forms.py class StaffLeaveForm(forms.ModelForm): current_user = "" class Meta: model = StaffLeave fields = ['staff', 'leave_type', 'reason', 'academic_year', 'date_of_leave', 'leave_end_date', 'status','approved_at'] #TODO this is working well when adding new object but on change data not visible in form def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.user = kwargs.pop('user') instance = kwargs.pop('instance') super().__init__(*args, **kwargs) how can i make data to appear in form when am changing object -
Best way to store Article with Wagtail CMS?
I am trying to understand what is the best way to store Articles in Wagtail website. I see two ways - to store Article as Wagtail Page, and store it as standard Django Model. I’m only at the beginning of my way, so I would like to ask more experienced users to share their approach for this situation. -
How to use template tags in Django
How to use url template tags without model, db in Django I am creating a bulletin board that communicates by DB <> API <> WEB method. Can django templates url parameter be used on 'Web' without model, db? I need to get two acquisitions, how should I use them? I've Googled and tried many things, but there was nothing I wanted to find. I must use the url tag. please help me. THANK YOU urls.py path('board/<int:pk>/comment/<int:id>/delete/', views.Commentapi_delete.as_view(), name="comment_delete"), template <form action="{% url 'comment_delete' ? ? %} method='POST'"> -
How to append GMT+ to datetime object in python
I have a datetime filed in my models.py and another field that saves the selected timezone as well (like Asia/Tehran). I need to append the the utc info of this timezone to my datetime object like this: '20/4/2021 18:33:00 Gmt+4:30 How can i do that?