Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assigning Objects to Many-to-many relationships - Django
I have a django project where I have a list with checkboxes, to select and assign students to teachers. I have attached my code below - I am getting no errors, but it doesn't seem to be assigning the student to the "students" many-to-many field in my "teachers" model. I have a GET function that is called earlier to select the teacher, then it is meant to pull that GET record and assign the student to that teacher. Any ideas? Views.py if 'assign_student' in request.POST: form = StudentForm(request.POST) selected = request.GET['select_teacher'] selected_teacher = Teacher.objects.all().filter(pk=selected)[0] if form.is_valid(): student_selected = request.POST('assign_student') student = Student.objects.all().filter(pk=student_selected)[0] selected_teacher.students.add(*student) Template.html <div class="student-list"> {% for instance in all_students %} <div class="input-group" style="border-bottom: 1px solid;"> <div class="item-details"> <div class="form-check"> <form method="POST" class="form-group" name="assign_student"> {% csrf_token %} <input onChange="this.form.submit()" class="form-check-input" type="checkbox" value={{ instance.pk }} id="flexCheckDefault" name="assign_student"> </form> <p> <b>{{ instance.fullname }}</b> <br> {{ instance.homeschool }} - {{ instance.schoolclass }} Class </p> </div> </div> </div> {% endfor %} </div> -
Display and render django admin permissions on a template
I am creating a school management system. I want to display the Django permissions generated on the Django admin page to be rendered and attached (by clickable buttons) to users. I want the administrator to have access to all the CRUD functionality of each model so that he can attach permissions to users on a custom dashboard. I am doing all that so as to prevent the school administrator from using the Django admin panel. Confused as to even where to start -
ValueError: attempted relative import beyond top-level package when trying to import models from another app in django
I have two django applications in my project in my project named electron: the first api and the second elec_meter. The directories are organized as follows: electron / api/ views.py ... elec_meter/ models.py ... In the api / views.py file I want to import elec_meter / models.py.This is how I do it: from ..elec_meter.models import * But I get the following error message: ValueError: attempted relative import beyond top-level package or from electron.elec_meter.models import * In this case I receive this error message: ModuleNotFoundError: No module named 'electron.elec_meter' Here is a picture of my code How can I solve this problem? -
Django Models Select a car model based on Car Make
Somewhat new to Django and I'm trying to create a car listing site. I've already ran into problems with the models. I can't seem figure out how I can create a model where if you select a particular make (e.g. Dodge) then you can select a model related to that make (e.g. Charger, Challenger, Viper etc.) models.py class Make(models.Model): make = models.CharField('Make', max_length=150) class Meta: ordering = ['make'] unique_together = ["make"] verbose_name_plural = "Manufacturers" def __str__(self): return self.make class CarModel(models.Model): year = models.IntegerField(default=datetime.datetime.today().year) make = models.ForeignKey(Make, on_delete=models.CASCADE) model = models.CharField('Model', max_length=150) trim = models.CharField('Trim', max_length=150, help_text='Trim level') class Meta: ordering = ['make', 'model', 'trim', 'year'] unique_together = ("year", "make", "model", "trim") verbose_name_plural = "Models" def __str__(self): return f' {self.year} {self.make} {self.model} {self.trim}' class CarListing(models.Model): content = models.FileField("Media") make = models.ForeignKey(Make, on_delete=models.CASCADE) make_model = models.ForeignKey(CarModel, on_delete=models.CASCADE) class Meta: ordering = ['make_model'] verbose_name_plural = "Car Listings" def __str__(self): return f' {self.make_model.year} {self.make_model.make} {self.make_model.model} {self.make_model.trim} ' -
Endless Databse in Django
I'm building a web app where I can give objects attributes. But I don't want to specify the maximum number of possible attributes. How can I make this database or model.py "endless". -
How shall I "Unsuspend" my suspended Heroku Application?
I got a mail some moments ago saying my deployed Django application has been suspended. I deployed it a few weeks ago and it has been running fine. No reason was given as to the cause of the suspension. And when I try to access the application, all I see is the image below. I'd appreciate any advice on what to do. Thank you. -
Value Error: invalid literal for int() base 10: 'null'
I am working on a e-commerce site with Django. I built a filter tags cart.Py where I compared two variables.one was str and another int. If Int(I'd)==product.id: Return true But the server shows Value Error: invalid literal for int() with base 10 : 'null' Help to figure out please. -
how to append a <hr> to a form element selected in JQuery?
Some introduction: I'm creating a form in Django. In my template I'm trying to select the final element of that form and attach a <hr> html element to help clean up the visual clutter. I've tried selecting the Forms ID and inserting adjacenthtml as well as appending raw html. I have also tried passing raw html into bootstrap in my form but this has also failed to render. tldr; I am trying to append a <hr> element to something I am targeting in Jquery function addHoriztonalRule() { document.getElementById("form").insertAdjacentHTML( "<hr>"); } -
How to server django media files with docker and nginx?
My setup for dockerizing & serving the Django app is a bit different when it comes to Nginx so the solutions I found didn't help. I have dockerized the django app and its working fine except the media files. I am not using nginx inside the container but on the actual server. All the requests even static files are served perfectly except media files. Here is my docker-compose file: version: "3" services: backend: image: gitrepo:latest #image: 731d5d7e9296 ports: - 8400:8000 links: - database command: bash -c "python manage.py migrate && python manage.py collectstatic --noinput && python manage.py runserver 0.0.0.0:8000" volumes: - media-cdn-data:/app/media_cdn deploy: restart_policy: condition: on-failure tty: true database: image: "postgres:12" # use latest official postgres version env_file: - database.env # configure postgres volumes: - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down volumes: database-data: # named volumes can be managed easier using docker-compose media-cdn-data: This is my nginx file: server { server_name app.platformname.com; location /media/ { proxy_pass http://127.0.0.1:8400/; alias /app/media_cdn/; } location / { proxy_pass http://127.0.0.1:8400/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 3600; proxy_set_header Connection ''; # these two lines here proxy_http_version 1.1; } } Any help is appreciated,I have been … -
Can I automatically add a filter to a MongoEngine query in Django?
I'm using MongoEngine with Django and I want to add a default filter on all queries that retrieve data, as well as some further logging. MongoEngine has signals, but does not appear to have any signal for pre-query. Am I missing something or can anyone recommend an elegant solution? -
Can't get Django-Simple-Captcha to work, posts even when using wrong captcha
I think this is a simple issue to solve, but I've been trying for a couple of hours now and I think that my View file is messed up. The captcha shows up on my page, but when i create a post and fill out the completely wrong captcha it get sent and updated anyway. My views-file: def discussions(request): posts = Post.objects.filter(created__lte=timezone.now()).order_by('-created') if request.method == 'POST': captcha = CaptchaTestModelForm(request.POST) if captcha.is_valid(): human = True else: captcha = CaptchaTestModelForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.created = timezone.now() post.save() return redirect('discussions') else: form = PostForm() captcha = CaptchaTestModelForm() -
Dynamically Build Q Filter in Django, with AND and OR Operators?
I have a database table of articles which includes a field link, which is the link to the article. I'd like to filter for articles in a given date range, that come from domains in a given list. I've got a string array like this: domain_names = [ 'domain_name_1', 'domain_name_2', 'domain_name_3', 'domain_name_4', ] ...and I have a filter like this which works: data = (myArticles.objects .filter(Q(creation_datetime__range=[from_date, to_date]) & (Q(link__contains=domain_names[0]) | Q(link__contains=domain_names[1]) | Q(link__contains=domain_names[2]) | Q(link__contains=domain_names[3]))) ) I'd like to dynamically build the filter, so that if an object is added to or removed from the domain_names list, the filter will dynamically update. I've tried this: q_object = Q() for name in domain_names: q_object.add(Q(link__contains=name), Q.OR) q_object = q_object.add(Q(creation_datetime__range=[from_date, to_date]), Q.AND) ...but I'm getting back all the objects in the date range, and the filter that's supposed to be filtering on domain_names isn't doing anything yet. What's the correct way to dynamically build a Q filter in this case? -
Django migrate from sqlite3 to mysql
I am trying to migrate my Django app from SQLite3 to MySql. I took following steps Configured a new empty database on MySql. I did not create any tables because I assumed that the tables will be created by the migrate command. Created a new user who has access to this database CREATE USER 'djangouser'@'%' IDENTIFIED WITH mysql_native_password BY 'password';GRANT ALL ON djangoappdb.* TO 'djangouser'@'%'; Stopped the server Dumped all the data to a file using python3 manage.py dumpdata > currData Deleted all the existing migrations reran python3 manage.py makemigrations. This step created a single new migration file Changed the setting.py file to use MySql and djangoappdb with correct username and password. ran python3 manage.py migrate command. I get following error ... File "/usr/local/lib/python3.8/dist-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1146, "Table 'djangoappdb.djangoapp_customuser' doesn't exist") customuser is one of the models in the app. Am I supposed to create the tables manually? -
Detect Every Third Loop in a HTML Forloop - HTML - Django
I have a website and on one page there is repeating information from a for loop that is made to print. The problem is that every item in the forloop is about 10 lines of text. When I go to print, the 10 lines of text will sometimes break between pages. I need them to stay together no matter what and I have tried "page-break-inside: avoid;" but I can't get it to work. It is somewhat irrelevant however because I need to make sure every page only has three blocks on it because 4 already overdose the margins. My plan is to loop through the blocks just fine and detect every third loop and add extra spacing below it to get it to go to the next page. Question: How do I detect every third loop in my html forloop? {% for post in filter.qs %} {% if forloop.first %} <div style="position:relative; top: -12px; left: -2px; margin-bottom: 180px;"> <div style="position:absolute;left:21.79px;top:435.49px" class="cls_0030"><span class="cls_0030">{%if post.department%} {{post.department}}{%endif%}</span></div> <div style="position:absolute;left:248.82px;top:435.54px" class="cls_014"><span class="cls_014">Inspection #</span></div> <div style="position:absolute;left:355.58px;top:435.52px" class="cls_013"><span class="cls_013">{{ post.count_building }}</span></div> <div style="position:absolute;left:21.70px;top:453.54px" class="cls_014"><span class="cls_014">Inspection Date</span></div> <div style="position:absolute;left:96.52px;top:453.52px" class="cls_013"><span class="cls_013">{%if post.date%}{{post.date}}{%endif%}</span></div> <div style="position:absolute;left:248.82px;top:453.54px" class="cls_014"><span class="cls_014">Inspection Time</span></div> <div style="position:absolute;left:338.10px;top:453.49px" class="cls_008"><span class="cls_008">{%if post.time%}{{post.time}}{%endif%}</span></div> <div style="position:absolute;left:21.70px;top:471.54px" class="cls_014"><span class="cls_014">Floor(s)</span></div> <div … -
how use more than one routings file in django-channels?
I am making a project in which i use channels in two different apps.but how can i make two different routings files for each app import os from channels.routing import ProtocolTypeRouter,URLRouter from django.core.asgi import get_asgi_application from channels.http import AsgiHandler from channels.auth import AuthMiddlewareStack from consultation import routings as consultation_routings from chat import routings as chat_routings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sqh.settings._base') application = ProtocolTypeRouter({ "http":AsgiHandler(), "websocket":AuthMiddlewareStack( URLRouter( consultation_routings.websocket_urlpatterns, chat_routings.websocket_urlpatterns, ) ) }) when i add a second routings file address to URLRouter in asgi.py it raises following error : URLRouter( TypeError: __init__() takes 2 positional arguments but 3 were given -
How do I download a Django webpage into a PDF with all the css when user clicks "PDF" button? (Exactly how it looks, into a PDF)
I have tried using multiple technologies like weasyprint and reportlab but have not been able to make the webpage that the user is seeing into a pdf. I have read the documentation but maybe I am missing steps but I eventually want to take the exact page they are looking at and when the press the "PDF" button, it downloads the entire web page into a PDF with all the css and everything. The webpage does contain heatmap charts made with plotly, at times the webpage can have 2 charts or sometimes up to 20 charts. I currently just call the 'window.print()' function but it cuts off the charts and I was hoping that if I utilize weasyprint or a similar technology then I can have the charts be displayed correctly. Thank you in advance. -
Is it possible to define only a reference to a text in django templates, and change it later?
First of all, I am sorry for my English! If I have a multi-language app, in one button for registration I would do something like this: <button>{% trans 'Register now!' %}</button> Then I have to generate the dictionary for translations and then, a translator of my team will assign the value for "Register now". Right? #: templates/file.html:30 msgid "Register now!" msgstr "Regístrate ahora!" But what happens if the texts are not yet defined, or are going to change? Is it possible with a Django plugin, to just define a reference to a given text of a component in my HTML and then someone from my team will fill in the text and generate the translations? Something like: <button>{% text 'button_text_for_registration' %}</button> // Maybe this will change Rosetta adds an interface for translations, but it is not possible to change the default dictionary text. Is there a plugin that does this? Or what would be the best way to manage this dynamic content? -
Django model method not making changes to object
I have a method on my model to change an object from being published to unpublished. The redirect works alright but in my database, nothing happens. If the object is published it remains so with no changes to it when the button is clicked to unpublish the object(blog post article) This is the model and the method class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) published = models.BooleanField(default=False, null=True, blank=True) def unpublish(self): self.published == False self.save() My view def unpublish_post(request, slug): post = get_object_or_404(Post, slug=slug) post.unpublish return redirect('dashboard') My urls.py path('unpublish-post/<slug>/', unpublish_post, name='unpublish-post'), -
django shell - some querysets are empty in the shell but they shouldn't be
I am using the django shell to look at some querysets. I am able to retrieve all of my Student objects with .all() but if I then try to retrieve one object with .get() or filter on a field, I'm getting empty returns. The project seems to run ok on the browser (I'm still in the progress of writing all my tests but functionally it is working). I am able to successfully use get() or filter on a field with my Objectivemodel. Here is what I get with all(): >>> from gradebook.models import Student, Objective >>> s = Student.objects.all() >>> for i in s: ... print(i.student_first) ... John Sally Keith Terrance Henry Analise Ron >>> Now if I try to use get(): >>> qs = Student.objects.get(student_first='Analise') Traceback (most recent call last): gradebook.models.Student.DoesNotExist: Student matching query does not exist. Or filter on a field: >>> s.filter(student_first='Ron') <QuerySet []> >>> Student model class Student(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) student_first = models.CharField(max_length=30) student_last = models.CharField(max_length=30) nickname = models.CharField(max_length=31) fullname = models.CharField(max_length=60) attend = models.BooleanField(default=True) student_number = models.IntegerField() email = models.EmailField(max_length=50) def __str__(self): return self.fullname -
Why does my django app fail to deploy to heroku ("building wheel for psycopg2")?
While trying to deploy a django app to heroku I am running into an issue that I can not seem to fix, and I am getting increasingly desperate. When I enter the command git push heroku master it runs into the following error remote: Collecting sqlparse>=0.2.2 remote: Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) remote: Building wheels for collected packages: Pillow, psycopg2 remote: Building wheel for Pillow (setup.py): started remote: Building wheel for Pillow (setup.py): finished with status 'done' remote: Created wheel for Pillow: filename=Pillow-5.2.0-cp39-cp39-linux_x86_64.whl size=1316371 sha256=cb80053184568f78e761e74c93e38682de7c3000417f9d12e7b37971f12dfcd0 remote: Stored in directory: /tmp/pip-ephem-wheel-cache-4bhzio_g/wheels/2e/0c/21/df64563df0fe8750c4bff3e38b90f223df6c02aa5c5b570905 remote: Building wheel for psycopg2 (setup.py): started remote: Building wheel for psycopg2 (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-tajnjqcx/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-tajnjqcx/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-9ekv4vgu remote: cwd: /tmp/pip-install-tajnjqcx/psycopg2/ As far as I understand it, it tries to install the dependencies in my requirements.txt file. I tried to change psycopg2 to psycopg2-binary change the version number of psycopg2 remove it entirely all to no avail: It still tried to "build wheel" for it. I really have no idea what the error means and I am at a complete loss here. … -
Integrating Sagepay (Opayo) with Django - How to create a merchant session key
Longtime stackoverflow user first time asking a question. I am trying to integrate Opayo (SagePay) with Django and I am having problems generation the merchant session key (MSK). From sagepays docs they say to use the below curl request and that I should receive the key in the response curl https://pi-test.sagepay.com/api/v1/merchant-session-keys \ -H "Authorization: Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=" \ -H "Content-type: application/json" \ -X POST \ -d '{ "vendorName": "sandbox" }' I have tried to implement this in my Django view with the following code but I receive a 422 response (Unprocessable Entity response). import requests def BasketView(request): headers = { "Authorization": "Basic aEpZeHN3N0hMYmo0MGNCOHVkRVM4Q0RSRkxodUo4RzU0TzZyRHBVWHZFNmhZRHJyaWE6bzJpSFNyRnliWU1acG1XT1FNdWhzWFA1MlY0ZkJ0cHVTRHNocktEU1dzQlkxT2lONmh3ZDlLYjEyejRqNVVzNXU=", "Content-type": "application/json", } data = {"vendorName": "sandbox"} r = requests.post("https://pi-test.sagepay.com/api/v1/merchant-session-keys", headers=headers, params=data) print(r) Any ideas where I may be going wrong with this? Thanks -
LIke functoin view keep throwing DoesNotExist at /group/3/ after a second user in the group post when liked by another user
I am currently challenge with a like functionality on a group page for that I'm creating, the problem is that when a first user of the group post on the group page other users can comment and like at his post, but as soon as a second user of the same group post, then when the post get liked or commented on, it throws thess error DoesNotExist at /group/3/. i wonder why am getting this error, because when the first user posted it didn't throw that error, when his post got liked or commented on, but the error only shows up when a another user on the same group post and it got like or commented on. I would appreciate some help. Here is my like function view. def like(request, pk): user = request.user post = Post.objects.get(pk=pk) group = GroupEx.objects.get(group=pk) liked= False like = Like.objects.filter(username=user, post=post,group=group) if like: like.delete() else: liked = True Like.objects.create(username=user, post=post, group=group) resp = { 'liked':liked } response = json.dumps(resp) return redirect('group:main', pk=pk) return HttpResponse(response,content_type = "application/json") Here is my comment view. def comment(request, pk): context = {} user = request.user post = get_object_or_404(Post, pk=pk) group = get_object_or_404(GroupEx,pk=pk) if request.method == 'POST': form = NewCommentForm(request.POST) if … -
id null on django API with mongo and djongo
I need help. My API get me "id": null instead of the uuid given in mongoDB. Here's the results : Result in RestER Result in NoSqlManager And Here's my code : serializers.py from testapp.models import Test class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields=fields='__all__' models.py class Test(models.Model): testChar = models.CharField(max_length=255) testTwo = models.CharField(max_length=255) views.py from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse # Create your views here. from testapp.models import Test from testapp.serializers import TestSerializer @csrf_exempt def testApi(request,id=0): if request.method == 'GET': test = Test.objects.all() test_serializer = TestSerializer(test,many=True) return JsonResponse(test_serializer.data,safe=False) elif request.method == 'POST': test_data = JSONParser().parse(request) test_serializer = TestSerializer(data=test_data) if test_serializer.is_valid(): test_serializer.save() return JsonResponse("Added successfully", safe=False) return JsonResponse("Failed to Add",safe=False) elif request.method == 'PUT': test_data=JSONParser().parse(request) test=Test.objects.get(TestId=test_data['TestId']) test_serializer = TestSerializer(test,data=test_data) if test_serializer.is_valid(): test_serializer.save() return JsonResponse("Update successfully", safe=False) return JsonResponse("Failed to Update") elif request.method == 'DELETE': test=Test.objects.get(TestId=id) test.delete() return JsonResponse("Deleted successfully", safe=False) -
Django: how to solve several Foreign key relationship problem?
I'm currently learning Django and making electronic grade book. I am completely stuck after trying everything, but still cannot solve the problem. I will explain in detail and post all the relevant code below. I need to have two url pages "class_students" and "teacher_current". The first page is for the teacher to see the list of students of a certain class. The table on this page has "action" column. In every cell of this column there is View button, so that the teacher could be redirected to "teacher_current" page and see the list of current tasks, given to a certain student. On this page there is a "Mark" column, its cells may contain EITHER mark given to this student with link to another page to update or delete this mark OR "Add mark" link to add mark on another page. Here comes the problem: everything works correctly, except the thing that each mark is related to a Task class via Foreign key and NOT to a Student class. So every student of the same class has the same marks for the same tasks. But it certainly won't do. Here is all my relevant code: 1) views.py models.py urls.py: https://www.codepile.net/pile/qkLKxx6g 2) … -
Page not found (404) No post found matching the query
I am working with Django and I am just a beginner. I am following this tutorial to create a contact form. But I have this error when I want to go to this URL: http://127.0.0.1:8000/contact/. I have 3 apps in my project(Posts, Users and Contact): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Posts', 'Users', 'crispy_forms', 'Contact', And here is the urls.py in my project : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('' , include('Posts.urls')), path('',include('Contact.urls')), ] And it is urls.py in my Contact app: from django.urls import path from Contact import views app_name = "Contact" urlpatterns = [ path('contact/', views.context, name="contact"), ] And this is views.py in my Contact app: from django.shortcuts import render, redirect from .forms import ContactForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse def context(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Website Inquiry" body = { 'first_name' : form.cleaned_data['first_name'], 'last_name' : form.cleaned_data['last_name'], 'email' : form.cleaned_data['email_address'], 'message' : form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message,'admin@example.com', ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect("Posts:home") form = ContactForm() return render(request, "Posts/templates/contact/contact.html", {'form':form}) I have a templates folder in Posts app and …