Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got '' in django
blog_id is not get. help me to solve this --- models.py class Blog(models.Model): title = models.CharField(max_length=500) body = models.TextField() last_updated_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add=True) author_instance = models.ForeignKey(AuthorInstance, on_delete=models.PROTECT) status_draft = models.BooleanField(default=False, blank=True, null=True) status_publish = models.BooleanField(default=False, blank=True, null=True) likes = models.ManyToManyField(UserInstance, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') def total_likes(self): return self.likes.count() views.py def like_post(request): post = get_object_or_404(Blog, id=request.POST.get('blog_id')) how to solve???? -
Sometimes website needs a refresh to show the website css django/python
Sometimes my website doesn't load css when redirected to other page. It needs to be refreshed to load and then it works fine. It doesn't happens everytime which is weird. I've seen some similar issues but none of them related to mine. Other people also tested it in different pc's, the same thing happens. Don't think it's a cache problem. Website uses: Python/Django as backend. How it looks like: -
ImportError: cannot import name 'Mapping' from 'collections' (C:\Users\User\AppData\Local\Programs\Python\Python310\lib\collections\__init__.py)
when I run project on my local machine gives this error ImportError: cannot import name 'Mapping' from 'collections' (C:\Users\User\AppData\Local\Programs\Python\Python310\lib\collections_init_.py) -
Django is not routing resource properly "Failed to load resource: the server responded with a status of 404 (Not Found) main.7ec538f6.chunk.js:1"
I was working on web development using Django for backend and react for frontend. react build files are working properly but the same build file is not serving properly by Django. when change debug == false media files are not serving and favicon is not fetched by Django. -
Django - Boolean field returns false in template while true in database
Yo ho there, so the issue i'm having is exactly as the title states. In the database, the boolean field can be set as true, but in the template html, it shows up as false. models.py class TrainingGoal(models.Model): forgeid = models.ForeignKey(ForgeUser, on_delete=models.CASCADE, default=None) strength = models.BooleanField(default=False) cardio = models.BooleanField(default=False) yoga = models.BooleanField(default=False) def __str__(self): return self.forgeid.forgepass views.py def profileView(request): if not ForgeUser.objects.filter(forgeid=request.user).exists(): return redirect('profileapp:create') forge_user_query = ForgeUser.objects.get(forgeid=request.user) training_goal_query = TrainingGoal.objects.filter(forgeid=forge_user_query) return render(request, 'profileapp/profile.html', {'forge_profile': forge_user_query, 'training_goals': training_goal_query}) abridged profile.html {% if training_goals %} <div class="goal-container"> <span class={{training_goals.strength | yesno:"training-true,training-false"}}>STRENGTH</span> <span class={{training_goals.cardio | yesno:"training-true,training-false"}}>CARDIO</span> <span class={{training_goals.yoga | yesno:"training-true,training-false"}}>YOGA</span> </div> {% endif %} The class value of span tag always shows up as training-false, and even expanding it into an if statement shows that the returned value is false. Not sure what I'm missing here. -
Django Form not submitting to database and not validating
In this django project the Form is not submitting to the database. I think it is not validating. What do you think is wrong with my it. Thanks [enter image description here][1] [enter image description here][2] [enter image description here][3] -
authenticate not working in django with my custom user model
i have a custom user model and custom login page based on djamgo forms: my forms.py is : from django import forms class LoginForm(forms.Form): Username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'username-in', 'placeholder': 'enter your username...' })) Password = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'password-in', 'placeholder': 'enter your password...', 'type': 'password' })) in my custom user model i add some fields like this : from django.db import models from django.contrib.auth.models import AbstractUser, User class UserDetails(AbstractUser): SuperUser = models.BooleanField(default=False) BranchManager = models.BooleanField(default=False) FinanceManager = models.BooleanField(default=False) BranchName = models.ForeignKey('stock.Branch', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.first_name + " " + self.last_name in my view.py for login : from django.contrib.auth.hashers import make_password from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from users.forms import LoginForm def LoginPage(request): forms = LoginForm() if request.method == 'POST': forms = LoginForm(request.POST) if forms.is_valid(): username = request.POST['Username'] password = request.POST['Password'] x = authenticate(username=username, password=password) if x: login(request, x) return redirect('/stock') context = {'form': forms} return render(request, "users/login.html", context) def UserRegister(request): return render(request, 'users/register.html') def LogoutPage(request): logout(request) return redirect('login') for checking data comes from form i use print() function to see what data will receive form form, username and password is what should be but when i print(x) that comes from this line … -
DJANGO FILTER DATE, where timedelta Day var is equal to a model field
I am trying to populate the timedelta param days with a model integer field but it says no defined. ''' query = POPlan.objects.filter(Q(status="INCOMPLETE") | Q(status="PARTIAL"), date_created__date__lte=timezone.now().date()-datetime.timedelta(days= (supplier__expectedDuration))) ''' The supplier field is foreign key relationship in my POPlan model and has an integer field of expected duration. Any suggestions on how to implement this code? Thank you kindly! -
How to show objects in a table in Django
I'm trying to add some objects with the input field, but they don't show up on the website. I can find them in the admin page, but not in the table, where i want them. How can i fix it? Here is my code: models.py class Kommentar(models.Model): user = models.CharField(max_length=25) comment = models.CharField(max_length=250) def __str__(self): return f"{self.user} {self.comment}" views.py def commentAction(request): user = request.POST["user"] comment = request.POST["comment"] print(user, comment) Kommentar.objects.create(user=user, comment = comment) return HttpResponseRedirect(reverse('literatur:index')) urls.py app_name = "literatur" urlpatterns = [ path('', views.index, name='index'), path('<int:literatur_id>/', views.detail, name="detail"), path('new', views.new, name="new"), path('deleteAction/<int:i>/', views.deleteAction, name="deleteAction"), path('commentAction', views.commentAction, name="commentAction"), ] index.html <table class="table"> <thead class="thead-dark"> <tr><th scope="col">Username</th><th scope="col">Kommentar</th></tr> {% for i in kommentar %} <tr> <td>{{i.user}}</a></td> <td>{{i.comment}}</td> </tr> {% endfor %} </table> -
django: reverse() fails when passing extra options to view function
I'm struggling with an annoying error with Django, I'm trying a reverse() passing metadata as a Python dictionary (I'm following the documentation but it does't work, can you help me figure out what I'm missing? ) This is my urlpattern (as you can see I'm passing extra options to my view function, as described in the docs): from django.urls import path from . import views urlpatterns = [ ..., path("items/<int:item_id>", views.item_page, { 'message': None }, name="item page") ] On my views.item_page function I have this: as ... reversed_url = reverse("item page", kwargs={'item_id': item_id, 'message': 'hello'} ) return HttpResponseRedirect(reversed_url) I'm getting this kind of error: Django Version: 4.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'item page' with keyword arguments '{'item_id': 2, 'message': 'hello'}' not found. 1 pattern(s) tried: ['items/(?P<item_id>[0-9]+)\\Z'] It's like it doesn't accept the "message" argument when reversing. -
Django, JavaScript, Python. Location of main Python code [closed]
I am trying to build an interactive website with Django, JavaScript and Python. The user selects and area on a map (Leaflet Geoman). That triggers some JavaScript. JS should trigger some Python code. And that Python code makes some calculations. My question: Where should I place the main Python code (the code that makes some calculations). My guess: JS should call an existing webservice, or a Django view. That Django view should then call the main Python code. You could also place your main Python code in the view itself, but that's a bit messy. The main Python code could be placed in the static folder. Is my assumption right???? -
Django: how to use .filter( ) method in django?
I am trying to display quiz only for users that are registered in a particular course, i.e if a user is registered in a Frontend Crash Course i want them to see only the quiz related to that course they are registered in, and not all the quiz from the db. i have a model UserCourse where i am storing all the courses a user have enrolled in, when i try filtering by that models while user_course is get like this below user_course = UserCourse.objects.get(user=request.user) quizzes = Quiz.objects.filter(course__usercourse=user_course).annotate(questions_count=Count('questions')) i get this error get() returned more than one UserCourse -- it returned 3! Now i have changed .get() to .filter() like this user_course = UserCourse.objects.filter(user=request.user) quizzes = Quiz.objects.filter(course__usercourse=user_course).annotate(questions_count=Count('questions')) i then get this error The QuerySet value for an exact lookup must be limited to one result using slicing. What is the right way to write this query. models.py class UserCourse(models.Model): user = models.ForeignKey(User , null = False , on_delete=models.CASCADE) course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="usercourse") class Quiz(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="quizzes") title = models.CharField(max_length=255) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True, related_name="quizzes") date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True) user_course = models.ForeignKey(UserCourse, on_delete=models.SET_NULL, null=True) def __str__(self): return self.title -
Want to call a 2 get api's using celery in django at sheduled time everyday byitself
Hi dear community members. I have created a django project which working totally fine with whatever api I called. But here I have one small query that there are 2 APIs from which from both APIs while get function is called a defined python script will run. Now I want to call those two APIs automatically at specific time daily. I tried going with celery.But not getting how to implement. I have created celery.py in main project folder and task.py in app folder with reference of this tutorial. But I'm not getting to what the code should be added in task.py to call the APIs daily (with get method).I watched and gone through several tutorials but not got any yet.It will be very helpful for me if any help with code example. Thanks in advance....Please help me with good code example as of above scenario. -
Are there cases where CORS errors do not occur?
I have created a React project within Django. And I called Django's api within the react project (*API that returns {"result": "Hello World"} when called with GET.) Even though no additional settings are made, CORS error does not appear and the api is successfully called and react can read the result of the response. Why am I not getting a CORS error? -
Filter query objects by date range in Django
Trying to filter queryset by date range in Django. If I choose period more than one day it's working fine, for example: the data in table was created on 06.07.2022 and I choose data start_date=06-07-2022, end_date=07.07.2022, the results will be shown. But if if choose start_date=06.07.2022 and end_date=06.07.2022 its giving me null. start_date = datetime.datetime.fromisoformat(params.get('start_date')) end_date = datetime.datetime.fromisoformat(params.get('end_date')) if start_date and end_date: if start_date > end_date: raise ValidationError('Start date cannot be greater than end date') queryset = queryset.filter(created__gte=start_date, created__lte=end_date) -
Pytest Fixture seeing Direct assignment to the forward side of a many-to-many set is prohibited
Not sure why I am getting this error when running my pytest with a fixture. Pretty new to this so I'm not exactly sure how to go about debugging this TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use tags.set() instead. Error ========================================================================================================================================================================================================================================== FAILURES ========================================================================================================================================================================================================================================== ______________________________________________________________________________________________________________________________________________________________________________________________________________________________________ test_new_address ______________________________________________________________________________________________________________________________________________________________________________________________________________________________________ address_factory = <class 'factories.address.AddressFactory'> def test_new_address(address_factory: Address): > address = address_factory.build() addresses/tests.py:7: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Strawberry GraphQL Django limiting filtering options in GraphiQL interface
So I have two graphql filters for a foreign key that works in Strawberry GraphQL Django v0.31. @strawberry.django.filters.filter(models.Client, lookups=True) class ClientFilter: id:auto name:auto @strawberry.django.filters.filter(models.Matter, lookups=True) class MatterFilter: id: auto client:'ClientFilter' category:auto In the GraphiQL page they produce a filter that looks like this: I don't need all the filter fields for the user because some of them don't make sense like using isNull or a regex field for an id. Is there a way to limit the filter options so it is less cluttered? -
Not able to do Insert operation in CRUD
I am making a CRUD of colors with color_name and color_description.While trying to insert the details the error :{'color_name': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]} below is the insert and show function that I have tried out def show_colors(request): showcolors = Colors.objects.filter(isactive=True) print(showcolors) serializer = ColorsSerializer(showcolors,many=True) print(serializer.data) return render(request,'polls/show_colors.html',{"data":serializer.data}) def insert_colors(request): if request.method == "POST": insertcolors = {} insertcolors['color_name']=request.POST.get('color_name') insertcolors['color_description']=request.POST.get('color_description') form = ColorsSerializer(data=insertcolors) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('colors:show_colors') else: print(form.errors) return redirect('colors:show_colors') else: insertcolors = {} form = ColorsSerializer(data=insertcolors) if form.is_valid(): print(form.errors) return render(request,'polls/insert_colors.html') model class Colors(models.Model): color_name = models.ForeignKey(Products, on_delete=models.CASCADE,default=None) color_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) html of insert_color <tr> <td>Colors Name</td> <td> <input type="text" name="color_name" placeholder="COLORS"> </td> </tr> <tr> <td>Colors Description</td> <td> <textarea name="color_description" id="" cols="30" rows="10"> </textarea> </td> </tr> html of show color <td><b>{{result.color_name}}</b></td> <td><b>{{result.color_description}}</b></td> I have checked the names assigned an they are matching ,so where am I going wrong? -
how to change the alias of the username in rest_framework_simplejwt using TokenObtainPairSerializer class?
I'm working on a project where user can register using his mobile no and password( after verifying with otp) what i'm doing is inside username field i'm saving user's phone no. as username is a mandatory field. And I'm using simple_jwt to get access token and refresh token. Everything is working fine urls.py from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns =[ path('register', RegisterView.as_view() ), path('otp/send', SendOtpView.as_view() ), path('otp/verify', VerifyOtpView.as_view() ), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] instead of creating a loginSerializer i'm using rest_framework_simplejwt inbuild class TokenObtainPairView But when i go to the url auth/api/token/ it ask me for username and password, which is confusing as a user . how can i change the name of the username to phone. I don't have any idea how to do it as I'm new to the djangorestframework serializers.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class LoginSerializer(TokenObtainPairSerializer): password = serializers.CharField(max_length=65, min_length=8, write_only=True) **phone = serializers.CharField(max_length=20, source='username')** class Meta: model = User fields = ['phone', 'password'] I tried doing this but then it add on another field with the name phone instead of replacing username. I even don't know whether it will work or not . -
Filtering by parameters using django-filters does not work
Why does django-filters stop working with this design? class Ads(generics.ListCreateAPIView): queryset = Ad.objects.all().order_by('id') serializer_class = AdSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = ProductFilter def list(self, request): queryset = self.get_queryset() serializer = AdSerializer(queryset, many=True) return Response({'info': serializer.data}) But if you change the Response, then everything works? return Response(serializer.data) -
Passing values from python to html with django in views.py does not work
Hello I am following a django tutorial and the tutorial (FreeCodeCamp btw, they deserve to be noticed more) showed how to make a simple word counter in django. Now the thing is: While rendering the html file he passes some data to it like this: def counter(request): words = request.GET['text'] numberOfWords = len(words.split()) return render(request, 'counter.html', {'amount_of_words': int(numberOfWords)}) (I noticed that after publishing it seems like there is not the right spacing for functions, there actually is) enter image description here For the youtuber it works really fine, but for me it seems there is no way to display the data. in the html file i put this: the number of words is {{amount_of_words}} Which is exactly the same thing the tutorial guy did. Even if I add proper html boilerplate it doesn't seem to work -
Can't find the file from views.py
I am stuck with a really weird problem. I have a file called: "test.txt". It is in the same directory with views.py. But I can't read it... FileNotFoundError. But if I create read_file.py in the same directory with views.py and test.txt, it works absolutely fine. What is wrong with views? Is this some sort of restriction by Django? This code works on read_file, doesn't work on views.py: fkey = open("test.txt", "rb") key = fkey.read() -
How to make bulk_updates in Django using Queryset
Here I am trying to do bulk updates in Django: Problem: In a model, there is a column name position whose value changes according to the drag and drop of the record position. so I am creating the Queryset for that, but not getting the required result, I can update the value of the particular id that got dragged but according to that need to update further makes little tricky using Queryset. Example: id name position 1 anil 1 2 ABC 2 3 XYZ 3 4 def 4 now if I drag id 1 to 4th place then I need to shift else by position - 1, Like: id name position 2 ABC 1 3 XYZ 2 4 def 3 1 anil 4 for this, I was using Queryset of bulk_update but not getting any correct way to do that, please let me know the best way to make update the positions. might be I elaborated on the question too long, but I posted this query thrice, in hope that now I will get the required result. Thanks in Advance -
error while redirecting one page to other in django
Basically, from and to both page have parameters so how can I redirect to page with parameters? if request.method == "POST": if request.POST.get('firstname') and request.POST.get('lastname') and request.POST.get('addln1') and request.POST.get('addln2') and request.POST.get('country') and request.POST.get('city') and request.POST.get('zip') and request.POST.get('smsno') and request.POST.get('whtspno') and request.POST.get('email') and request.POST.get('deptnm') and request.POST.get('brdctlst'): saverecord = AddContact() saverecord.f_name = request.POST.get('firstname') saverecord.l_name = request.POST.get('lastname') -
Unabe to load Dynamic images using loop counter in django
I am unable to load th image using loop counter. Its loading the page http://localhost:8000/static/images/png%7B%7Bforloop.counter%7D%7D.png instead of http://localhost:8000/static/images/png1.png http://localhost:8000/static/images/png2.png def html(request): # template = loader.get_template('index.html') # return HttpResponse(template.render()) params = {'movie':['Dr Strange','Shamsheera']} return render(request, 'index.html',params) <table style="width:100%"> {% for m in movie %} <tr> <td width="30%"><img src="{% static 'images/png{{forloop.counter}}.png' %}" alt="{{forloop.counter}}"></td> <td width="20%">{{m}}</td> <td width="50%">Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam explicabo asperiores est nostrum mollitia dignissimos unde sapiente quos deserunt eveniet placeat beatae neque incidunt quia nulla itaque voluptatum earum, repudiandae enim cum fugiat nisi magnam dolorem? Deserunt odit, repellat eius qui asperiores adipisci soluta blanditiis inventore dignissimos est et nesciunt porro, iusto, ex at consectetur obcaecati unde! Dolorem rerum veniam mollitia, provident, sunt officiis maxime maiores atque cumque consequatur quidem molestias amet ullam? Iure pariatur, tempora voluptatem sint, quidem eius vel nemo eveniet eaque unde doloremque. Adipisci, maiores corrupti, ut debitis, error odio omnis odit id ratione enim minima a!</td> </tr> {% endfor %} </table>