Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Improperly Configured
I am trying to make a https://dog.ceo/dog-api/ clone with Django Rest Framework. I got the error: "ImproperlyConfigured at /breeds/ Could not resolve URL for hyperlinked relationship using view name "breedimage-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.", and I am not sure how to solve it. Here is some of my code: models.py from django.db import models # Create your models here. class Breed(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BreedImage(models.Model): breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE) breedImage = models.ImageField(upload_to='photos') serializers.py from rest_framework import serializers from .models import Breed, BreedImage class BreedSerializer(serializers.ModelSerializer): BreedImages = serializers.HyperlinkedRelatedField(view_name='breedimage-detail', many=True, read_only=True, lookup_field='breed') class Meta: model = Breed fields = ['name', 'BreedImages'] views.py from django.shortcuts import render from rest_framework import generics from .models import Breed from .serializers import BreedSerializer # Create your views here. class BreedList(generics.ListCreateAPIView): queryset = Breed.objects.all() serializer_class = BreedSerializer class BreedDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Breed.objects.all() serializer_class = BreedSerializer urls.py from django.contrib import admin from django.urls import path from Breed import views urlpatterns = [ path('admin/', admin.site.urls), path('breeds/', views.BreedList.as_view()), path('breeds/<name>', views.BreedDetail.as_view()), ] I have followed this tutorial - https://www.django-rest-framework.org/api-guide/relations/#example. Thank you in advance for your help. -
How To Unit Test Crispy Error Messages Which Fail To Submit
Im unit testing my form and am wanting to test that if a user attempts to submit this blank field, the appropriate error message is displayed. I understand the problem I am having, that the form is not successfully submitting therefore is returning error 302, but I dont know how to test such cases. def test_error_message_for_incorrect_data(self): user = User.objects.create_superuser('username') self.client.force_login(user) response = self.client.post(reverse('study'), { 'years_of_study': '', } ) self.assertContains(response, escape('Please select an item in the list.')) the error message i am getting AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) Thank you -
Syntax error with return function in Django application
I am working on a Django application that is meant to be a website for a pizza company. I have an error that I cannot figure out, and I cannot find a solution in the other forums. The line of code that has the error is return (f"{self.name} - $ {self.price}") The error says this: SyntaxError: invalid syntax -
How to add Search Index in elasticsearch document django?
I want to implement elasticsearch to search through the name field in the profiles. Suppose there are two users Hariharasudhan and Harish. Search query Hari should give me two users Hariharasudhan and Harish Search query Harish should give me only Harish But my code is returning two users for Harish also. I think it is because the search query is also using the edge_ngram tokenizer declared. I need help to resolve this issue. My elastic search document : from django.conf import settings from django_elasticsearch_dsl import Document, Index, fields from elasticsearch_dsl import analyzer, tokenizer from profiles.models import UserProfile #Signals from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_elasticsearch_dsl.registries import registry # Name of the Elasticsearch index INDEX = Index('profiles') # See Elasticsearch Indices API reference for available settings INDEX.settings( number_of_shards=1, number_of_replicas=1, max_ngram_diff = 50, ) html_strip = analyzer( 'html_strip', # tokenizer="standard", tokenizer=tokenizer('serializer','edge_ngram', min_gram=3, max_gram=6), filter=[ "lowercase"], ) @INDEX.doc_type class ProfilesDocument(Document): """User Profiles Elasticsearch document.""" id = fields.IntegerField(attr='id') name = fields.TextField(analyzer=html_strip) email = fields.TextField(analyzer=html_strip) user_details = fields.ObjectField( attr = "user_details", properties ={ "nickname" : fields.TextField(), "date_of_birth" : fields.DateField(), "roll_no" : fields.TextField(), "course" : fields.TextField(), "department" : fields.TextField(analyzer='keyword'), "batch" : fields.TextField(analyzer='keyword'), "gender" : fields.TextField(), "current_location" : fields.TextField(), "work_title" : fields.TextField(), "company_name" … -
Django: Search Form in Base Template
So I have a simple form to search for a zip code that I want in my base template so I don't have to render it in every view. I'm aware of this question but I can't seem to get their answer using context_processors to work for me. Not sure if it's because something's changed in Django or I'm just doing something wrong. Here's what I have: base.html {% load static %} <html> <head> <title>Restroom Rater</title> </head> <body> <h1>Restroom Rater</h1> <!-- THIS IS THE FORM I WANT ON EVERY PAGE --> <form action="{% url 'venue_list' %}"> {{ new_zip_form }} <input type='submit' value='Search'> </form> {% block content %} {% endblock %} </body> </html> views.py # import requests from django.shortcuts import render, redirect, get_object_or_404 from .forms import get_zip from . import yelp_api from .models import Venue def homepage(request): new_zip_form = get_zip() return render(request, 'restroom_rater/homepage.html', { 'new_zip_form': new_zip_form }) def venue_list(request): new_zip_form = get_zip() search_zip = request.GET.get('zip_code') if not Venue.objects.filter(zip_code=search_zip).exists(): venues = yelp_api.get_name(search_zip) venues = Venue.objects.filter(zip_code=search_zip).order_by('name') else: venues = Venue.objects.filter(zip_code=search_zip).order_by('name') return render(request, 'restroom_rater/venue_list.html', { 'venues': venues, 'new_zip_form': new_zip_form, 'search_zip': search_zip}) def venue_detail(request, venue_pk): venue = get_object_or_404(Venue, pk=venue_pk) return render(request, 'restroom_rater/venue_detail.html', {'venue': venue}) forms.py from django import forms class get_zip(forms.Form): zip_code = forms.CharField(required=True, label='Zip … -
how to run a django project (made on linux) on windows?
I am new to programming and started working on Linux, now I want to switch to windows and open my project there, look at the tutorials, it is written to activate the virtual environment in the Settings / activate.bat folder. but in my project there is no such folder and such file with the extension .bat. what should I do? -
Django inlineformset_factory with many to many relation
I need to make an inlineformset_factory in a CreateView, the relation between the parent and child models are many to many using the through argument to add an extra field on the intermediary model as described in django documentation. I've little experience on django and web development so I’ve a problem that I haven't been able to solve yet. Thanks before hand. The next sketch represents the result I need, in practice this sketch is form3 in my template; Final result These are my models; class TipoDiscapacidad(models.Model): tipo = models.CharField("Tipo de discapacidad", max_length=20) def __str__(self): return self.tipo class Persona(models.Model): primer_nombre = models.CharField("Primer nombre", max_length=30) segundo_nombre = models.CharField("Segundo Nombre", max_length=30, blank=True, null=True) apellidos = models.CharField("Apellidos", max_length=100) fecha_nacimiento = models.DateField() discapacitado = models.ManyToManyField(TipoDiscapacidad, through='Discapacidad', blank=True, null=True) nacionalidad = models.ManyToManyField(Nacionalidad) email = models.EmailField() tipo_sangre = models.ForeignKey(TipoSangre, on_delete=models.PROTECT) sexo = models.ForeignKey(Sexo, on_delete=models.PROTECT) estado_civil = models.ForeignKey(EstadoCivil, on_delete=models.PROTECT) licencia_conducir = models.BooleanField() titulo_academico = models.ManyToManyField(TituloAcademico) def __str__(self): return "{} {}".format(self.primer_nombre, self.apellidos) class Discapacidad(models.Model): discapacidad = models.ForeignKey(TipoDiscapacidad, on_delete=models.CASCADE) persona = models.ForeignKey(Persona, on_delete=models.CASCADE) porcentaje = models.FloatField() As you can see I'm using the through argument to point to the model that will act as an intermediary. Parent Model -> Persona Intermediary Model -> Discapacidad Child Model -> TipoDiscapacidad This … -
AttributeError: 'LoginUser' object has no attribute '_client'
I'm working on a GraphQL project using graphene-django. I wrote tests and after writing, I noticed that I had the following lines of code in all units that require authentication: response = self.query( ''' mutation tokenAuth($username: String!, $password: String!) { tokenAuth(username: $username, password: $password) { token } } ''', op_name='tokenAuth', variables={ 'username': '+2340000000001', 'password': 'testuser' } ) token = response.json()['data']['tokenAuth']['token'] For example, if there's a unit test_something_user in my User test case that requires authentication, I'd have to add the code as shown below and I have to do the same to every unit that requires it. class UserTestCase(GraphQLTestCase) ... ... def test_something_user(self): response = self.query( ''' mutation tokenAuth($username: String!, $password: String!) { tokenAuth(username: $username, password: $password) { token } } ''', op_name='tokenAuth', variables={ 'username': '+2340000000001', 'password': 'testuser' } ) token = response.json()['data']['tokenAuth']['token'] So I decided to write a reusable function that I could call whenever auth is required. from graphene_django.utils.testing import GraphQLTestCase from cnapi.schema import schema class LoginUser(GraphQLTestCase): def __init__(self, username, password): self.username = username self.password = password def token(self): response = self.query( ''' mutation tokenAuth($username: String!, $password: String!) { tokenAuth(username: $username, password: $password) { token } } ''', op_name='tokenAuth', variables={ 'username': self.username, 'password': self.password } ) return response.json()['data']['tokenAuth']['token'] … -
Django pagination without serializer
My api return json with data based in key/store etcd , so no queryset I would like add pagination , but i don't use model and serializer It's possible to add pagination without this ? -
Implementing Object-Dependent Condition on Django Model
I have a django model, for which I want to ensure first-last name combos are unique. One way of doing this is by adding constraints, such as with the following: class Meta: constraints = [UniqueConstraint(fields=['first_name', 'last_name'], name='unique_name')] However, this will not handle a situation with two objects where the names differ by capitalization (I want to identify 'First Last' with 'first last'). One can add a Q object to the constraint that defines a constraint, condition = Q(first_name__iexact=None) & Q(last_name__iexact=None) but I can't figure out what to put in place of None. How can I reference the first and last name fields there (simple first_name or self.first_name do not work)? On a related note, when is this sort of constraint preferable to implementing it in a clean() function? example models.py class Speaker(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) -
Can I use urls parameter again in Django?
path('list/<location_id>/', views.MyView.as_view(), name='myview'), path('list/<location_id>/<category_id>/', views.MyView.as_view(), name='myview_category') I use homepage 'myapp/list/2/', 'myapp/list/4/', ... I want to use category function in myview. But I can't write urls links that use location_id again in HTML. <li><a href="{% url 'cafeyo:myview_category' location_id=# category_id=1 %}">category 1</a></li> How can I use location_id??? Please Help me... -
How much knowledge do I need to have about object-oriented programming before I hit into the Django framework?
I finished the basics of python and I have two weeks start learning the object_oriented programming Actually, I do not want to spend so much time on it like what I did in the basics so I was wondering How much knowledge do I need for the Django framework is the basics enough or I have to dig into deeper topics? -
Print table information after onclick event in Django
I want to print table row information after button onclick event with Javascript Fuction. [Current Source] -view.py def table(request): test_list = TestInformation.objects.order_by() context = { 'test_list' : test_list, } return render(request, '/test.html', context) -test.html <label ~~ id="btn_click" onclick="btn()"> <table class="table table-bordered" id="data_table"> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> {% for li in test_list %} <tr> <td> {{ li.Id }} </td> <td> {{ li.Name}} </td> </tr> {% endfor %} </tbody> </table> <Script type="text/javascript"> function btn { //I'd like to put above {for~~ endfor} source here! } </Script> -
Why is my Javascript not working for checking is Username already exists?
I am super new to Javascript, and I'm trying to implement some code that will search if a username already exists and then display an error if it does dynamically rather than having to hit submit and then finding out the username already existed. I tried implementing some JS but it's not working. What am I doing wrong? reg.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} {% block javascript %} <script> $("#id_username").change(function () { var username = $(this).val(); $.ajax({ url: '/ajax/check_if_username_exists_view/', data: { 'username': username }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }); </script> {% endblock %} <br> <h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1> <form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" > <div class="is-valid"> {% bootstrap_form registration_form%} </div> {% csrf_token %} {% for field in bootstrap_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color:grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: red;">{{error}}"</p> {% endfor %} </p> {% endfor %} <div class="form-check"> <input type="checkbox" id="accept-terms" class="form-check-input"> <label for="accept-terms" class="form-check-label">Accept Terms &amp; Conditions</label> </div> <div> <br> <button type="submit">Register</button> </div> </form> {% endblock content … -
Why am I getting a WinError 32 while deleting a file on django?
I added a function to my code that deletes files and text, when there is just text it deletes it with no problem but when there is a file(video) involved it returns a permission error [WinError 32], I dont know where am I bad but I think it might be on the views.py because I initially setted that code to just delete text. views.py def delete_video(request, video_id): delete_v = Post.objects.get(id=video_id) delete_v.delete() return HttpResponseRedirect('/') models.py (it has a @property that when a file is deleted, it also deletes it from the media folder) class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank="True") user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') def __str__(self): return str(self.text) @receiver(models.signals.post_delete, sender=Post) def auto_delete_file_on_delete(sender, instance, **kwargs): if instance.video: if os.path.isfile(instance.video.path): os.remove(instance.video.path) urls.py urlpatterns = [ path('delete_clip/<int:video_id>/', views.delete_video, name='delete_video'), ] home.html <form action="delete_clip/{{ content.id }}/" method="post"> {% csrf_token %} <button type="submit">Delete</button> </form> -
Why do I keep getting a multiValueDictKey Error in my Django/Bootstrap project?
Here is the code for my login form: <form class="user" action="/returningAgent/" method="post" > <div class="form-group"> <input type="email" class="form-control form-control-user" id= "InputEmail" name="InputEmail" aria-describedby="emailHelp" placeholder="Enter Email Address..."> </div> <div class="form-group"> <input type="password" class="form-control form-control-user" id="InputPassword" name="InputPassword" placeholder="Password"> </div> <div class="form-group"> <div class="custom-control custom-checkbox small"> <input type="checkbox" class="custom-control-input" id="customCheck"> <label class="custom-control-label" for="customCheck">Remember Me</label> </div> </div> <a href="/returningAgent/" class="btn btn-primary btn-user btn-block"> Login </a> <hr> <a href="/returningAgent/" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Login with Google </a> <a href="/returningAgent/" class="btn btn-facebook btn-user btn-block"> <i class="fab fa-facebook-f fa-fw"></i> Login with Facebook </a> </form> and here is the code that the form submission triggers: def returningAgent(request): #try: x = Agent.objects.get(bizEmail = request.POST["InputEmail"], password = request.POST["InputPassword"]) diction = { 'f' : x.firstName, 'l' : x.lastName, 'e' : x.bizEmail } return render(request, 'index.html', diction) #except: #return HttpResponseRedirect('/404/') I have tried switch request.POST to request.POST.get, and have the name of the field within the HTML form code, yet I still continue to get an error everytime I try to use credentials that are already in my database. Any ideas? -
Google Maps integration with Django
I am looking to integrate Google Maps or some sort of mapping system such that the user can just enter an address and it appears in a drop-down or they can drag across a map. I have tried using PostGIS, however, I couldn't figure it out. Further, I tried looking up some API's and messed around with them extensively, but due to the lack of documentation, I couldn't figure it out. Any advice? -
geodjango ubuntu upgrade reads coordinates backwards
Im updating a geodjango project from ubuntu 16 to 20, Ive tried with yml file, and with setting up a new env, but i cant figure out why the admin iis reading the database features coordinates backwards, it works fine in the ubuntu 16 prohect, I cant solve it, heres how it looks: the feature in the django admin the complete layer on qgis (postgres database connection) -
How to show data in template Django without refreshing the page
I have a django/python project, where i need to check every url and show its status on template, the urls are in a excel file, i was able to do this check with Python and print the status but i want to show a list of urls on template then every url will be checked and changed color according to the status( Ok or Ko) without refresing the page, i want to check every line on excel file then send the status to template and keep checking , i know i should use ajax but i don't know how to do this, i'm really lost, can i have your help pleaase! this is my code : (as you see i used to send a list but i want to show the status afetr every check ) check.py data_xls = pd.read_excel(r'C:....Check.xlsx', index=False) df = DataFrame(data_xls) s = requests.session() headers = {'accept': 'application/json;odata=verbose'} for index, row in df.iterrows(): res =s.get(login_url) if res.status_code == 200: list2 += row['login_url'] + "," + row['portail'] + ";" else: list1 += row['login_url'] + "," + row['portail'] + ";" return JsonResponse({'portails': list1,'names':list2}, status=200) Thank you in advance! -
Is accessing foreign key ID field directly faster in Django?
Please reference these example models: class Player(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) class Team(models.Model): captain = models.ForeignKey(Manager, on_delete=models.CASCADE) country = models.CharField() class Manager(models.Model): networth = models.FloatField() I am trying to figure out if the following is faster than the alternative (ie. accesses the database less): team = Team.objects.get() Player.objects.filter(team_id=team.id) Alternative: team = Team.objects.get() Player.objects.filter(team=team) -
Can't get Profile object that belongs to User in django
I have a blog app in Django and on the home page I display all posts as well as the user that posted. However, I'm now trying to add the user's profile image next to the usernames and I can't seem to pull any data from the Profile object. In my templates, when I loop through the posts, code such as {{ post.user }} works fine, but when I try to extend beyond that like post.user.profile.profile_image.url nothing shows up. models.py: class Post(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) class Profile(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) profile_image = models.ImageField(default='image.png', upload_to='profile_images', blank=True, null=True) views.py: def home(request): posts = Post.objects.annotate(comments_count=Count('comments')).order_by('-created_date') common_tags = Post.tags.most_common()[:4] title = "" return render(request, 'post/home.html', {'posts': posts, 'common_tags': common_tags}) And in my html template I'm just doing a {% for post in posts %} loop. Any ideas? Thanks!! -
Django-taggit. How to add a tag to all the items in a category
I'd like to have the ability to add the same tag to all the items within a category. Let's say I have a category named Service and Service has 42 posts. I would like to be able to add a tag named "tire" for instance to every post in Service From admin, perhaps, how could this be done? Thanks in advance for any help. -
How give 2 parameter in PUT method?
I have a model of books with name and id. I want to change the name using PUT method requests, but I don't know how to handle put requests in django. I want to receive 2 parameter in PUT request: new name and id. the older name will be replaced by new name but the id won't change. this is my incomplete function: def change_book_name(request): put = QueryDict(request.body) new_name = put.get("name") -
django how to generate QR code in my model
I'm new to Django and I came to the part where I need to generate a QR barcode for each product in my App I found two libraries django-qr-code and django-qrcode what is the deference between these two libraries and which one I should use the other point is there any good tutorial I can follow to generate a QR code in a model ? -
I want to configure AWS S3 on my django project but many of my client's media files are on my pythonanywhere server already
I want to integrate AWS S3 now in my django project and i have done all that but the problem is many of my client's media files are already on the pythonanywhere server and now i want to change it to AWS S3 so the upcoming media files should be stored in S3 and the previous should be stored in pythonanywhere. But now what happens is that the new files are storing correctly and i can open them but the previous files, when i open them because of the media files url i suppose django looks it in AWS S3 but they are not there. So i need to django to understand to look for the media files where they are stored like for the previous files i want django to look in the server directory and for new files in S3 instance. Hope that makes sense. This is my AWS S3 configurations file for my django project This is my django settings file, mainly focuses on media files