Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Debug Toolbar BaseConnectionHandler.all() error
I am using docker and the debug toolbar gives the following error: BaseConnectionHandler.all() got an unexpected keyword argument 'initialized_only' I wrote the following code in the settings.py file : if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] import os import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] I wrote the following code in the urls.py file : if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] -
Django: Updating Old Migration Files that Have `django_mysql.models.JSONField`?
In older versions of Django, you could use JSON fields in models via django_mysql.models.JSONField. In new versions of Django, JSONField is no longer in django_mysql.models. I've updated my models.py files accordingly, but I still have old migrations files that look like this: # Generated by Django 2.1.7 on 2019-07-17 22:59 from django.db import migrations import django_mysql.models class Migration(migrations.Migration): dependencies = [ ('rss', '0009_delete_patternmatchingkeywords'), ] operations = [ migrations.AddField( model_name='rssoutput', name='industries', field=django_mysql.models.JSONField(default=list), ##<== ERROR ), ] Now when I run makeMigration, I get this error: AttributeError: module 'django_mysql.models' has no attribute 'JSONField' What is the correct procedure to address this? I'm using: Django 4.0 Python 3.9.13 django-mysql 4.7.0 -
forms.Select(attrs={'class': 'form-control' Edit form and get numbers 1-5 in dropdown
Am wondering how i can get this html code into a forms.py in my ReviewForm as widgets. This code: 'rating': forms.Select(attrs={'class': 'form-control',}), Should be as the html code under with 1-5. And also be saved in models so the rating still gets saved when edited. So basicly allow the forms.py when you edit it to render a dropdown with 1-5 atm its just a dropdown with no numbers cant figure out how to get numbers in the dropdown with the widget. <div> <label>Rating</label><br> <select class="form-control" name="rating"> <option value="1">1</option> <option value="2">2</option> <option value="3" selected>3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> forms.py class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ('content', 'rating') widgets = { 'content': forms.Textarea(attrs={'class': 'form-control'}), 'rating': forms.Select(attrs={'class': 'form-control',}), } Models.py class Product(models.Model): category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) description = models.TextField() has_sizes = models.BooleanField(default=False, null=True, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) rating = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name def get_rating(self): reviews_total = 0 for review in self.reviews.all(): reviews_total += review.rating if reviews_total > 0: return reviews_total / self.reviews.count() return 0 class Review(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) rating = … -
ValueError: Field 'id' expected a number but got 'shafquetnaghmi'
models.py After adding this model,when i run python manage.py migrate this problem arises,there i added default='shafquetnaghmi' in sender but i removed it ,still it is not working. class instantmessage(models.Model): sender=models.ForeignKey(User,related_name='sender', on_delete=models.CASCADE,blank=True,null=True) receiver=models.ManyToManyField(User,related_name='receiver') message=models.TextField(blank=True) def __str__(self): return f'{self.message}' Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, social_django, socialapp Running migrations: Applying socialapp.0006_remove_instantmessage_sender_instantmessage_sender...Traceback (most recent call last): File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1822, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'shafquetnaghmi' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\SHAFQUET NAGHMI\socialnetwork\manage.py", line 22, in <module> main() File "C:\Users\SHAFQUET NAGHMI\socialnetwork\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 253, in hanp_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 2461, in get_db_prep_value value = self.get_prep_value(value) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1824, in get_prep_value raise e.__class__(ValueError: Field 'id' expected a number but got 'shafquetnaghmi'. -
Not getting any data from request object using request.POST.get
I have a post view that receives an email and payment_method_id. However, when I send this data to this end_point I noticed that I am not retrieving any of the data from my request object. This is an example of what I am sending: {"email":"test@gmail.com","paymentMethod_id":"pm_1LFMSIDMftTw233Mz3S9xkqE"} This is my view @csrf_exempt @api_view(['POST']) def save_stripe_info(request): email = request.POST.get("email") payment_method_id = request.POST.get('payment_method_id') print('email is', email) print('payment method', payment_method_id) customer = stripe.Customer.create( email=email, payment_method=payment_method_id ) return Response(status=status.HTTP_200_OK, data={ 'message': 'Success', 'data': {'customer_id': customer.id} }) -
How to edit/change a field in a model without using a form in django
So im creating a Multiple choice quiz and I want to be able to add different quizzes with different difficulty and have around 20 questions for each quiz that i make. From those 20 questions the program should randomly select 10 questions and displays them SEPERATELY. So basically I got the questions to display seperately and created a few models but i also want to save the users results after they have answered the 10 questions to the database and how many times they attempted the same quiz. Is there a way to do this without using a form? models.py from django.db import models from django.contrib.auth.models import User class Quizzes(models.Model): CHOICES = ( ('Easy', 'Easy'), ('Medium', 'Medium'), ('Hard', 'Hard'), ) name = models.CharField(max_length=200) quizDesc = models.TextField() difficulty = models.CharField(max_length=200, null=True, choices=CHOICES) class Meta: verbose_name_plural = "Quizzes" def __str__(self): return self.name class QuestionList(models.Model): quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE) questNum = models.IntegerField(null=True) 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) class userQuizInfo(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE,null=True) quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE,null=True) correct = models.IntegerField(null=True) wrong = models.IntegerField(null=True) questOrder = models.CharField(max_length=10,null=True) views.py questions = list(QuestionList.objects.filter(quiz_id=pk)) questions = random.sample(questions,1) # userInfo = userQuizInfo.objects(pk=pk) # userInfo.questOrder += … -
Is there a way to EDIT databases (sqlite) in VSCode?
I am currently trying toed the database that comes with Django. Im tryin to use the VSCode Extension vscode-sqlite to edit the database. While I currently am able to look at the database without the gibberish that shows up when I try to open the database in a text editor, I can't find a way to actually edit the database. I think the buttons on the upper right corner of the UI might have something to do with whatever Im trying to achieve, but I dont really know what they do. Any help would really be appreciated. the unexplained buttons -
How to list available filters in drf for given api?
Is there a way to list all available filter/s for given api endpoint? -
How to use Django variable in JavaScript /jQuery?
I am passing a list of name subject in my HTML template from views.py but it's not working the way its working when I pass a list statically. Also, It's by default converting into Unicode (that I don't want) Following is my code, var data = "{{subject}}"; console.log("data before for loop",data) var i; for (i = 0; i<data.length; i++) { data = data.replace("&#39;", "'"); } console.log("data after for loop",data) var t2 = ['IT', 'Maths', 'History', 'Civics', 'Virtualization', 'BIO', 'EH', 'Chemistry']; console.log(typeof data); console.log(typeof t2) and following is the output of console.log, data before for loop [&#39;IT&#39;, &#39;Maths&#39;, &#39;History&#39;, &#39;Civics&#39;, &#39;VWE&#39;, &#39;BIO&#39;, &#39;EH&#39;, &#39;EHas&#39;] data after for loop ['IT', 'Maths', 'History', 'Civics', 'VWE', 'BIO', 'EH', 'EHas'] string object I want to know why it's not working.. and how can I make it work.. Thanks. -
Access Django M2M values in queryset without looping
I receive some data through Ajax that allows me to do some filtering on a model that has some m2m relations (say Model). I get a queryset, say "content" that I then need to send back using json. Here are simplified lines of code: content = Models.objects.all() content = content.values return JsonResponse({"data":list(content)}) It was working fine but the project changed and I now need to include the values of some of the m2m related models attached to Model to each queryset result instances, problem is that content=Model.objects.all() will of course not give me these values without some looping so I am stuck. I remember using a depth option in DRF that would have done the job here but unfortunately I cannot do this now as the project is too advanced and live. Any way to add directly in the queryset the results of the m2m related values ? Many many thanks -
How to add custom permissions to Django admin Groups page?
I want to create a Group that contains multiple custom permissions related to a custom Account model (extended from base User), then restrict access to routes/pages to Accounts only within that group. I have added the following custom permissions to my Account model (which is a working extension of the base AUTH_USER_MODEL)... class Account(models.Model): date_created = models.DateTimeField(auto_now_add=True, verbose_name='Date Created') date_modified = models.DateTimeField(auto_now=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) class Meta: permissions = ( ("can_access_x_pages", "To provide access to X pages"), ("can_access_y_pages", "To provide access to Y pages"), ("can_access_z_pages", "To provide access to Z pages"), ) ... but those permissions do not show up on the "New Group" page on Django Admin: Based on this GeeksForGeeks article, once the permissions have been added, they should simply be displayed. Any idea what I am missing? This self-answered StackOverflow question from 2016 is the same issue, but that OP cited a bug in django-admin-view-permission as the problem, but that is all they wrote. Edit: I checked my Adminer view of the database, and I do not see the new permissions there, so I'm guessing that they have not been migrated? -
Django channels unable to connect(find) websocket after docker-compose of project using redis
I have currently implemented websocket connections via django channels using a redis layer. I'm new to docker and not sure where I might have made a mistake. After the docker-compose up -d --build the "static files, media, database and gunicorn wsgi" all function, but redis won't connect. even though it is running in the background. Before trying to containerize the application with docker, it worked well with: python manage.py runserver with the following settings.py setction for the redis layer: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("0.0.0.0", 6379)], }, }, } and by calling a docker container for the redis layer: docker run -p 6379:6379 -d redis:5 But after the trying to containerize the entire application it was unable to find the websocket The new setup for the docker-compose is as follows: version: '3.10' services: web: container_name: web build: context: ./app dockerfile: Dockerfile command: bash -c "gunicorn core.wsgi:application --bind 0.0.0.0:8000" volumes: - ./app/:/usr/src/app/ - static_volume:/usr/src/app/staticfiles/ - media_volume:/usr/src/app/media/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db networks: - app_network redis: container_name: redis image: redis:5 ports: - 6379:6379 networks: - app_network restart: on-failure db: container_name: db image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ environment: - ./.env.psql ports: - 5432:5432 networks: … -
Django pytest running many migrations after tests
I am running pytest-django with a legacy database that was not created by Django (e.g. all my models use managed=False). In production, everything is fine but in testing Django wants to apply a bunch of curious migrations. For testing, I have a pre-populated test database and I want my tests to commit changes to the database (because we have logic in db views and triggers that needs to get run). All that is working fine but afterwards a ton of migrations are run and it takes my test suite time from 1s to 70s. The migrations are overwhelmingly this type: ALTER TABLE [DeprecatedLegacyTable] CHECK CONSTRAINT [FK_dbo.DeprecatedLegacyTable_dbo.User_DeprecatedServiceId]. The tables aren't even in any models.py, so I guess Django is digging this up with inspectdb. I've looked around a bit and it seems this is a "feature" of Django but it is hurting my workflow. Is there any way to apply these migrations once and for all rather than replay them every test run? (I'm also pretty curious why these migrations are all being done after the tests themselves. Seems backwards.) -
Django can't find admin page
I'm building a blog app in Django and I wanted to access the build-in admin page. However, when I try to reach it, it keeps throwing a 404 error and I have no idea why. So, when I try to access http://127.0.0.1:8000/admin/ I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: [name='index'] posts [name='posts'] posts/<slug:slug> [name='post'] The current path, admin/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Note: The porject is called 'my_site' and the app is called 'blog' Some code snippets below: my_site/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')) ] blog/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('posts', views.posts, name='posts'), path('posts/<slug:slug>', views.post, name='post'), ] blog/views.py from django.shortcuts import render, get_object_or_404 from .models import Author, Post # Create your views here. def index(request): all_posts = Post.objects.all().order_by("-date") latest_posts = all_posts[:3] return render(request, "blog/index.html", { "posts": latest_posts }) def posts(request): return render(request, … -
How to build MS Access like form in Python?
How would you go about building a form like the one attached in Python and having each metric/cell being filled in? For example, I enter someone's name and the other fields would get filled in with data from various tables. It's currently built in Excel and it's calling the data from multiple tabs but I'd like to transition to Python. I have built the backend data portion of it in Jupyter Notebook using Pandas but now would like to build the shell so that the data will auto-populate in its designated cell/location once a given variable has been entered into an input field (like 'Name' in the example). Can I do this in Jupyter Notebook (preferred)? Would I have to learn/use Django, Flask or HTML? Any tips, suggestions, or examples that you've seen would be greatly appreciated! Form Example -
SyntaxError: invalid syntax After complete installation of Qiime1
Traceback (most recent call last): File "/home/raju/miniconda2/envs/qiime1/bin/beta_diversity.py", line 4, in import('pkg_resources').run_script('qiime==1.9.1', 'beta_diversity.py') File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/pkg_resources/init.py", line 666, in run_script self.require(requires)[0].run_script(script_name, ns) File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/pkg_resources/init.py", line 1462, in run_script exec(code, namespace, namespace) File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/qiime-1.9.1-py2.7.egg-info/scripts/beta_diversity.py", line 13, in from qiime.util import make_option, parse_command_line_parameters File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/qiime/util.py", line 49, in from skbio.util import remove_files, create_dir File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/init.py", line 15, in import skbio.io File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/io/init.py", line 309, in import_module('skbio.io.clustal') File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/io/clustal.py", line 123, in from skbio.alignment import Alignment File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/alignment/init.py", line 230, in from ._alignment import Alignment, SequenceCollection, StockholmAlignment File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/alignment/_alignment.py", line 21, in from skbio.stats.distance import DistanceMatrix File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/stats/distance/init.py", line 193, in from ._base import (DissimilarityMatrixError, DistanceMatrixError, File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/skbio/stats/distance/_base.py", line 17, in from IPython.core.pylabtools import print_figure File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/IPython/init.py", line 48, in from .core.application import Application File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/IPython/core/application.py", line 23, in from traitlets.config.application import Application, catch_config_error File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/traitlets/config/init.py", line 6, in from .application import * File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/traitlets/config/application.py", line 17, in from decorator import decorator File "/home/raju/miniconda2/envs/qiime1/lib/python2.7/site-packages/decorator.py", line 162 print('Error in generated code:', file=sys.stderr) ^ SyntaxError: invalid syntax -
Can we make video conference app using django
Is it possible to make a video conferencing app with similar functionalities as of gmeet and zoom, namely, audio and/or video calling, screen share using django or do we have to use express.js for it? -
how set validation for password in django==4
Im useing this view for set new password for user But the output below this is always printed password not valid view.py from django.shortcuts import redirect, render from django.contrib.auth import login, logout, authenticate from django.urls import reverse_lazy from django.contrib import messages import re from .models import Users def edit_password(request): password_cahnged = False PASSVALID = r"^a" error = None if request.method == "POST": password = request.POST.get("password") password1 = request.POST.get("password1") password2 = request.POST.get("password2") username = None if request.user.is_authenticated : username = request.user.username user = authenticate(request, username=username, password=password) if user is not None: print(PASSVALID) print(password1) print(str(password1)) if re.fullmatch(PASSVALID, str(password1)): if str(password1) == str(password2): userr = Users.objects.get(username=str(user),password=password) print(userr) password_cahnged = True else: error = "password not math" else: error = "password not valid" else: error = "password its wrong" else: return redirect("login") print(error) context = {"password_cahnged": password_cahnged ,"error":error} return render(request, "edit_password.html", context=context) If you also have a better solution for changing the password is welcome (except forms) -
Django Rest Framework: why is my api call much slower in production than dev?
I've a django app that's deployed on an ec2 instance with docker and nginx. An api call that takes 700ms on my local system takes 15s on the production server. Even with debug set to false, on my local machine the call returns within 600-800ms but on production it consistently takes 15-20s to return. What causes this difference in performance? How does the way django handles api calls in debug differ from prod? I already use select_related and prefetch wherever possible. What changes could I make to speed up the api calls on the prod env? -
Django UploadFile Form not working with init overload
class UploadFileForm(forms.ModelForm): ALLOWED_TYPES = ['pdf', 'dwg'] class Meta: model = Files100 fields = ['project', 'category', 'file'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) categories = Category.objects.values_list("name", flat=True).distinct() categories = categories.exclude(kuerzel="AAAAAA") self.fields['category'].queryset = categories.filter(level__gt=0).order_by("level", "name") ö {% load django_bootstrap5 %} <div class="col-sm-3 col-md-3 col-sm-3 col-lg-2"> {% if file_upload_form %} <form method='post' enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form file_upload_form %} {% bootstrap_button button_type="submit" content="Upload File" %} {% bootstrap_button button_type="reset" content="Cancel" %} </form> {%endif%} When I take the init it works totally fine. But with the init the upload is passed without errors but also without uploading the file. I need the init to reduce my queryset. Is there another way of doing this. With self in the init I get error. If I put the super at the bottom I get error as well. Please help. Thanx -
module 'urllib.request' has no attribute 'POST' [closed]
Soy nuevo en Django y estoy tratando de crear una aplicación web simple. Cree formulario para registrarse utilizando CustomUserCreationForm. Desafortunadamente, recibí el siguiente error. módulo 'django.http.request' no tiene atributo 'POST'. Me podran ayudar??? A continuación encontrará el código view.py: from asyncio.windows_events import NULL from email import message from http.client import OK from urllib import request from django.shortcuts import render, HttpResponse, redirect, get_object_or_404 from django.http import HttpResponseRedirect from .models import personas, remito, detalle_remito, recursos from .forms import formularionuevo, CustomUserCreationForm from django.contrib import messages from django.core.paginator import Paginator from django.http import Http404 from django.contrib.auth import authenticate, login def registro(resquest): form = CustomUserCreationForm() if resquest.method=="POST": formulario = CustomUserCreationForm(data=request.POST) if formulario.is_valid(): formulario.save() user= authenticate(username=formulario.cleaned_data("username"), password=formulario.cleaned_data("password1")) login(resquest, user) messages.success(request, "Te has registrado correctamente") return redirect(to="home") form=formulario return render(resquest,"registration/registro.html", {'formulario':form}) Registro.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> {% load static %} <!-- Bootstrap --> <link href="{% static 'RemitoTicapp/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <title> Registro de usuario</title> </head> <body> <div class="container"> <br> <br> <br> <div class="row"> <div class="col-12 col-md-6 offset-md-3"> <div class="card"> <div class="card-body"> <h2> Registro de usuario </h2> <hr> <form action="" method="POST"> {% csrf_token %} {% for field in formulario %} <label> {{ field.label }} :</label> {{ field }} <br … -
Redirect Page Login google
I see this tutorial about Google Authenticantion: TUTORIAL But my button of google: Redirect to a page that needs to click continue to redirect to the login page, but what I would like is that as soon as I click on the google login button, I will be redirected to the login page, without this intermediate page Below my settings -
How to get a field's value by joining multiple querysets in Django
I am trying to display images in a list based on certain conditions. To that end, I have been trying to create a queryset join of a set of models (as shown below): models.py class ModeOfTransport(models.Model): mode_of_transport = models.CharField(unique=True, max_length=4... class Route(models.Model): route_id = models.AutoField(primary_key=True) route_start = models.ForeignKey(City, related_name='route_start') route_end = models.ForeignKey(City, related_name='route_end') class RouteLeg(models.Model): route_leg_id = models.AutoField(primary_key=True) route_id = models.ForeignKey(Route, related_name='route_hdr') leg_start = models.ForeignKey(City, related_name='leg_start') leg_end = models.ForeignKey(City, related_name='leg_start') mode_of_tptn = models.ForeignKey(ModeOfTransport, related_name='route_tptn_mode') class ImageType(models.Model): image_type_id = models.CharField(primary_key=True, max_length=1) image_type = models.CharField(max_length=4) class RouteImage(models.Model): image_id = models.AutoField(primary_key=True) image_name = models.CharField(max_length=125) image_type = models.ForeignKey(ImageType) image_route = models.ImageField(upload_to='images/route_images/') From a list of existing routes (a generic listview), I am trying to create a further drilldown like this: views.py def graf_display_route(request, pk): if request.method == 'GET': route_grafiks = RouteLeg.objects.all().filter(route_id=pk) return render(request, 'route_grafiks.html', {'route_grafiks': route_grafiks}) Now in order to get to the image field (RouteImage.image_route), I tried the following to get the image_type and then the image itself: qs_mode_of_tptn = ImageType.objects.filter(image_type_id__in= route_graphics.values_list('mode_of_tptn', flat=True)) The result (on printing the list of resultant queryset) I can see in the terminal as: [<ImageType: ImageType object (2)>, <ImageType: ImageType object (3)>]> Next, using the queryset qs_mode_of_tptn when I use another qset, I get the image table fields … -
How do I test all of my app's urls in Django to make sure they require authentication?
I want to write a Django test that looks at all the urls in one particular app, and makes sure that hitting them without being authenticated redirects me to the login page. Something like: from django.test import TestCase from django.urls import reverse from my_app.urls import urlpatterns class AuthTest(TestCase): def _test_url(self, url): response = self.client.get(url) self.assertRedirects(response, expected_url=reverse("login_app:login")+ "?next=" + url) def test_auth(self): for url in urlpatterns.SOMETHING: with self.subTest(url=url): self._test_url(url) Is there a way to get the actual list of urls in each urlpattern for my app? And, related question: for those URLs that require a pk, is there a way to automatically use pk=1? My fixtures will make sure that pk=1 exists for all those urls. -
Reverse for 'edit_review' with arguments '('',)' not found. 1 pattern(s) error when editing comment
When i try to click on my edit comment button in product_detail i get this error and i cant figure out how to fix it. would really appreciate some help thanks in advance. error when clicking edit comment button below: Am only writing out the needed code not the full code if there is anything u need tell me and i add. views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.db.models.functions import Lower from .models import Product, Category, Review from .forms import ProductForm, ReviewForm @login_required def edit_review(request, review_id): review = get_object_or_404(Review, pk=review_id) product = Product.objects.get(name=review.product) if request.method == 'POST': review_form = ReviewForm(request.POST or None, instance=review) if review_form.is_valid(): review_form.save() messages.success(request, 'Successfully updated Review!') return redirect(reverse('product_detail', args=[product.id])) else: messages.error(request, 'Failed to update product. Please ensure the form is valid.') else: review_form = ReviewForm(instance=review) messages.info(request, f'You are editing {edit_review}') template = 'products/edit_review.html' context = { 'review_form': review_form, 'Review': Review, } return render(request, template, context) Models.py class Review(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) rating = models.IntegerField(default=3) content = models.TextField() created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.product.name, self.created_by) forms.py from django import forms …