Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF - Inconsistency in Throttling
Hi I am facing extreme inconsistency in Throttling mechanism in Django rest framework. I have the api endpoint to throttle 10 requests/sec but when I send 20 requests at the same time using Apache Benchmark the api should throttle 10 requests whereas it throttles 4, 6 and it is inconsistent. sometimes it does not even throttle any requests. class StatusApiThrottle(CustomeRateThrottle): rate = '10/s' scope = 'status' def allow_request(self, request, view): # independent throttle for GET request on view if request.method == "POST": return True return super().allow_request(request, view) cache configuration CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "myapp" } } Run the app using gunicorn gunicorn app --workers 2 --threads=2 Testing using Apache benchMark $ ab -n 20 -c 20 -v 1 http://127.0.0.1:8080/api/v1/access/842b1012-53ef-4e98-9a20-484e681c3789 result #1 Complete requests: 20 Failed requests: 6 result #2 Complete requests: 20 Failed requests: 3 -
PermissionError: [Errno 13] Permission denied: '/app/vol/web/static'
So I deployed my Django Project on local server, using docker, but I got this error: PermissionError: [Errno 13] Permission denied: '/app/vol/web/static' Here is my settings.py: STATIC_URL = '/static/static/' MEDIA_URL='/static/media/' MEDIA_ROOT = 'vol/web/media' STATIC_ROOT = 'vol/web/static' my settings.py is located in app/app/settings.py -
comment on a blog post django
I m trying to make a comment system on a blog website with using the slug instead of pk im running into not NULL constraint failed: home_comment.post_id error my error is coming in the form_valid function in the class based view form.instance.post_id = self.kwargs['pk'] how do i do this ^ with the slug form.instance.post__slug = self.kwargs['slug'] (this is showing an error) views.py class AddCommentView(CreateView): model = Comment form_class = AddCommentForm template_name = "add_comment.html" def form_valid(self, form): form.instance.post__slug = self.kwargs["slug"] form.instance.name = self.request.user return super().form_valid(form) models.py class Post(models.Model): title = models.CharField(max_length=1000, default="Title") author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=1000, default="Category") body = models.TextField(default="This is the Body of the Post.") slug = models.SlugField(max_length=1000, null=True, blank=True) created_time = models.DateTimeField(auto_now_add=True) created_date = models.DateField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) updated_date = models.DateField(auto_now=True) likes = models.ManyToManyField(User, related_name="blog_posts_likes") dislikes = models.ManyToManyField(User, related_name="blog_posts_dislikes") class Meta: verbose_name_plural = "Blogs & Posts" def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = generate_slug(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return f"/blogs/post/{self.slug}" class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") name = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateField(auto_now_add=True) time_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Post Comments" def __str__(self): return "%s - %s" % (self.post.title, self.name.username) def get_absolute_url(self): return f"/blogs/post/{self.post.slug}" html file {% … -
Insert data using serializer class django-rest-framework
I am a beginner with Django and especially with the Django REST framework. Inside "UserRegistration" class, I want to create a new user and ExtendUser using "UserSerializer". how can I do that? this is my models.py class ExtendUser(models.Model): user = models.OneToOneField(User, related_name='user_name', on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=16) picture = models.ImageField(upload_to='userImages/', default="default.webp", blank=True) def __str__(self): return str(self.user) this is my serializers.py class UserSerializer(serializers.ModelSerializer): password2 = serializers.CharField(write_only=True, style={'input_type':'password'}) class Meta: model = User fields = ['email', 'first_name', 'password', 'password2'] extra_kwargs = {'password' : {'write_only':True,}} def save(self): name = self.validated_data['first_name'] password = self.validated_data['password'] password2 = self.validated_data['password2'] if len(password) < 8: raise serializers.ValidationError({'error':'Password must be 8-16 Characters '+ 'and contain both numbers and letters/special character.'}) if password != password2: raise serializers.ValidationError({'Password':'Password and Confirm Password Should be Same!'}) email = self.validated_data['email'] if User.objects.filter(email=email).exists() == True: raise serializers.ValidationError({'E-mail': f"{email} this email already been used. Try another email."}) user = User.objects.create_user(username=email, email=email, password=password, first_name=name) return user class ExtendUserSerializer(serializers.ModelSerializer): class Meta: model = ExtendUser fields = '__all__' this is my views.py class UserRegistration(APIView): def post(self, request): user = UserSerializer(data=self.request.data) if user.is_valid(raise_exception=True): user.save() refreshToken = RefreshToken.for_user(user) context = {'access': str(refreshToken.access_token), 'refresh': str(refreshToken)} return Response(context, status=status.HTTP_201_CREATED) return Response(user.errors, status=status.HTTP_400_BAD_REQUEST) -
Best practice to read and filter a big CSV file in Django
I'm researching the way to read a big CSV file and display it as a datatable in Django admin. I need the filter function as well. Could anyone suggest to me which library to support? -
Block Content Tag Not Working In Django When Inheriting From Base.html
I have seen other questions like this but none of them solve my issue. I have been using Django for a while and i have been exploring the block content part now. But i have run into a problem. The base.html looks like this: and my home.html looks like this: as per the internet the home.html page should have hello and replaced text. But I only see hello in the page it would be amazing if you would be able to help me on this as soon as possible. :) -
Saving logged in user info in django model
I am trying to update planTable model with the current logged in user automatically. In my planForm form, I have excluded "user" field. These are my code snippets. views.py def createPlan(request): form = planForm if request.method == "POST": form = planForm(request.POST) if form.is_valid(): form.save() return redirect('index') context = {'form':form} return render(request, 'workoutapp/create_plan.html', context) @login_required(login_url='/register_user/') def myPlan(request): my_plan = planTable.objects.filter(user=request.user) print('user : ', request.user) #print('data : ', my_plan) context = {'my_plan':my_plan} return render(request, 'workoutapp/my_plan.html', context) models.py class planTable(models.Model): DAYS = ( ("sunday", "sunday"), ("monday", "monday"), ("tuesday", "tuesday"), ) day = models.CharField(null=True, max_length=10, choices=DAYS) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) category = models.ForeignKey(workoutTable, null=True, on_delete=models.CASCADE) exercise = models.ForeignKey(itemTable, null=True, on_delete=models.CASCADE) def __str__(self): return self.day forms.py class planForm(ModelForm): class Meta: model = planTable fields = 'day', 'category', 'exercise' create_plan.html <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="submit"> </form> My requirement is that when the logged in user clicks on submit button, the fields in planTable should get populated with the values. But after logged in user click on submit button, only day, category and exercise gets populated, the user field stays blank. Is there any way for the user field to get populated depending on the logged in user? -
MultipleObjectsReturned() in Django error
I have posted the code below, when I try to view this model as an object in http://127.0.0.1:8000/admin/ I get the following error: MultipleObjectsReturned at /admin/configuration/epemployeeposition/2/change/ get() returned more than one Epemployeeposition -- it returned more than 20! Does anyone know how to fix this? I would greatly appreciate the help! This is my model of the object giving me an error in models.py. To create this model I autogenerated it from the postgres database using python manage.py inspectdb. I have only removed manage = False in the Meta class postgres database: Postgres Database View models.py: class Epemployeeposition(models.Model): companyid = models.IntegerField(db_column='CompanyID', primary_key=True) employeeid = models.IntegerField(db_column='EmployeeID') linenbr = models.IntegerField(db_column='LineNbr') isactive = models.BooleanField(db_column='IsActive') positionid = models.CharField(db_column='PositionID', max_length=20, blank=True, null=True) startdate = models.DateTimeField(db_column='StartDate', blank=True, null=True) startreason = models.CharField(db_column='StartReason', max_length=3) enddate = models.DateTimeField(db_column='EndDate', blank=True, null=True) isterminated = models.BooleanField(db_column='IsTerminated') termreason = models.CharField(db_column='TermReason', max_length=3, blank=True, null=True) isrehirable = models.BooleanField(db_column='IsRehirable') noteid = models.UUIDField(db_column='NoteID') createdbyid = models.UUIDField(db_column='CreatedByID') createdbyscreenid = models.CharField(db_column='CreatedByScreenID', max_length=8) createddatetime = models.DateTimeField(db_column='CreatedDateTime') lastmodifiedbyid = models.UUIDField(db_column='LastModifiedByID') lastmodifiedbyscreenid = models.CharField(db_column='LastModifiedByScreenID', max_length=8) lastmodifieddatetime = models.DateTimeField(db_column='LastModifiedDateTime') tstamp = models.BinaryField() class Meta: db_table = 'EPEmployeePosition' unique_together = (('companyid', 'employeeid', 'linenbr'), ('noteid', 'companyid'),) Here is the full Traceback of the error Traceback: Traceback (most recent call last): File "/home/descartes/source/bitserf/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in … -
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?