Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Testing - Accessing Site with authenticated user
I am trying to do a unit test for authenticated user url access, currently I am trying to authenticate a user but I am unable to do so... def setUp(self): self.user = User.objects.create_user(email='test@testmail.com', password='test_password', is_staff=True) self.user.save() self.client = Client() def test_portfolio_url(self): self.client.login(username='test@testmail.com', password='test_password') url = reverse('portfolio') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(resolve(url).func, portfolio) self.assertTemplateUsed(response, 'portfolio.html') -
Django rest framework post requests gets Forbidden (CSRF cookie not set.)
I'm trying to do some post requests to my Django project using DRF but it gives me this error : Forbidden (CSRF cookie not set.) .. here is my code : serializers.py from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['username','password','id'] views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer urls.py router.register(r'main_users', UserViewSet) urlpatterns = [ path('api/', include(router.urls)), -
Is there any way to use ajax-select AutoCompleteSelectMultipleField model like ModelMultipleChoiceField
I wanna use ajax-select AutoCompleteSelectMultipleField but I have a problem using typical django methods on it. I was using a custom model based on the django default ModelMultipleChoiceField for many to many select and I used to call queryset on the returned result from it: # form people = CustomizedModelMultipleChoiceField( Person.objects.exclude(is_healthy=True).filter(death_date=None)) # test people_list = form.fields['people'].queryset.values_list('id') but now I want to use AutoCompleteSelectMultipleField for lazy loading and it raises this error: AttributeError: 'AutoCompleteSelectMultipleField' object has no attribute 'queryset' -
Why are changes made with custom javascript not being registered
I have a custom javascript that autofills a CharField when I check a checkbox but when I click "Save" the text from the CharField doesn't save to the database, it's empty. How can I fix this? -
Is it possible to customize individual pages associated with the same template? dynamic URL django
I am working on a blog website and have set up dynamic URLs in Django for each blog article. Is it possible to change the layout of paragraphs and images of specific pages so that there are slight differences between each page? -
I want to make a custom author model with django but ı can't do that :(
I am trying to make a news site with django and there is a special author detail page in the template data structure that I received on the frontend. In the backend, I need to convert this author part to API and integrate it into the site, but the code I wrote does not work properly (I can add one author, but when I try to add the second one, I get a UNIQUE Constraint failed post_author.href error.) How do you think I should follow and what kind of structure should I create? This is my model code from django.db import models from django.contrib.contenttypes.models import ContentType from django.db import models from django.urls import reverse #from comments.models import Comment from .utils import get_read_time from django.conf import settings from django.utils import timezone from markdown_deux import markdown from django.utils.text import slugify from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils.safestring import mark_safe import uuid # from user_info.models import Profile class GENDER(models.TextChoices): Erkek = "Erkek" Kadın = "Kadın" Diğer = "Diğer" NONE = "Belirtmek İstemiyorum" class Category_Choices(models.TextChoices): BİLİNMEYENLER = '13İlinmeyenler' KİŞİSEL_GELİŞİM = 'Kişisel Gelişim' İLHAM_AL = 'İlham Al' YATIRIM_HABERLERİ = 'Yatırım Haberleri' GİRİŞİMCİLİK = 'Girişimcilik' ENGLİSH_NEWS = 'English News' BAŞARI_HİKAYELERİ = "Başarı Hikayeleri" … -
django.core.exceptions.FieldError: Cannot resolve keyword 'productcategory_id' into field. Choices are: country, country_id, id, name, vendor?
I am trying to use here Django dependent dropdown list. But at the same time, the error occurred. If I make an ajax request click the product category and the dependent dropdown not working togetherly and cannot make an ajax request shows an error. How to resolve this error? Kindly, someone please help. Models.py from django.db import models class ProductCategory(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class SubCategory(models.Model): country = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Vendor(models.Model): designer_name = models.CharField(max_length=100, default='') design_name = models.CharField(max_length=200) description = models.TextField(max_length=5000) productcategory = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True) def __str__(self): return self.designer_name forms.py from django import forms from .models import Vendor, ProductCategory, SubCategory class DesignerForm(forms.ModelForm): class Meta: model = Vendor descr = forms.CharField( widget=forms.Textarea ) fields = ('designer_name','design_name', 'description', 'productcategory', 'subcategory') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subcategory'].queryset = SubCategory.objects.none() if 'productcategory' in self.data: try: productcategory_id = int(self.data.get('productcategory')) self.fields['subcategory'].queryset = SubCategory.objects.filter(productcategory_id=productcategory_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subcategory'].queryset = self.instance.productcategory.subcategory_set.order_by('name') Views.py from .models import * from django.shortcuts import render, redirect from .forms import * def Products(request): if request.method == 'POST': form = DesignerForm(request.POST) … -
Django, taggit: When I try to filter objects associated with taggit tags, the query is very slow
I have about 300,000 queries, and when I go through objects that are tied together, such as the following The query becomes very slow (about 2-3 seconds). How can I speed up the query? Also, in this case, should I implement the tags in m2m field instead of using dkango-taggit? # models.py from taggit.managers import TaggableManager from taggit.models import GenericUUIDTaggedItemBase, TagBase class MyCustomTag(TagBase): slug = None created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") class TaggedWhatever(GenericUUIDTaggedItemBase): tag = models.ForeignKey( MyCustomTag, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_items", ) class Video(models.Model): tags = TaggableManager(through=TaggedWhatever, blank=True) def __str__(self): return self.title # views.py MyCustomTag.objects.annotate(count=Count("video")).order_by("-count") Also, just trying to retrieve an object that contains a tag like this will result in a very slow query. A very slow query will be issued. Video.objects.filter(tags__name='tag_name') -
How to use Django's inbuilt authentication with custom forms (html templates)
I am trying to create a website using Django where user can register and login currently I am storing the user registration data in my custom database table. But I am not finding any sold way to do user authentication using the data from my custom tables So I am in search of a way where I can use Django's inbuilt user auth but with my custom forms( html templates) on top Please Help me !! -
django didn't shows the pictures
when i add posts in django admistration it did't show the photos(.jpg) -
Model form is not able to save in database
I am a beginner in Django I want to save a form data in database but i am not able to save, followed some tutorials also. form.py: from django.forms import ModelForm from .models import * class listsForm(ModelForm): class Meta: model = todo fields = "__all__" views.py: from django.shortcuts import render from .models import * from .form import * def index(request): lists = todo.objects.all() form = listsForm() context = { 'lists':lists, 'form':form, } if request.method == 'POST': form = listsForm(request.POST) if form.is_valid: form.save() return render(request, 'index.html', context) models.py: from django.db import models class todo(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) created = models.DateField(auto_now_add=True) def __str__(self): return self.title -
How to get total quantity of each kind of task in Django?
I have 1 table for tasks, those tasks can be in 3 status"todo","in-progress" and "done", I want to calculate total number of each status' task, and put it into an array like ('todo total','progress total','done total'), any idea how can I achieve that? my final goal is to display the 3 subtotal in Chartjs, Thanks in advance. models.py ''' class Todo(models.Model): status_option = ( ('to_do', 'to_do'), ('in_progress', 'in_progress'), ('done', 'done'), ) status = models.CharField(max_length=20, choices=status_option, default='to_do') # todo_list's content team = models.ForeignKey('Team', on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) create_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) project_code = models.CharField(max_length=20) details = models.TextField() def __str__(self): return self.status # return self.team['team'].queryset def update_status(self): if self.status == 'to_do': self.status = 'in_progress' elif self.status == 'in_progress': self.status = 'done' self.save() ''' -
How to add a random serial number generator in models.py of Django project?
I am creating a Asset Management System project using Django. I am simultaneously learning django framework. Now the problem is Suppose I have an Asset whose serial number is not specified that how i generate a random unique serial number for an asset. class Asset(models.Model): asset_type=models.ForeignKey(Asset_type,on_delete=models.CASCADE) asset_name=models.CharField(max_length=50) asset_serial=models.CharField(max_length=20) asset_date_pur=models.DateField() asset_price=models.FloatField() asset_vendor=models.CharField(max_length=50,null=True,blank=True) person_assigned=models.CharField(max_length=50,default=None) department_assigned=models.CharField(max_length=50,default=None) -
How do I get reverse reference in Django template?
Apologies if the title doesn't make much sense. I don't quite understand what I lack in knowledge. I have a Post and Comment models in my Django project. What I'm trying to do is list out all the Blog posts, and show NUMBER OF COMMENTS OF EACH POST. Please see my codes below. models.py class Blog(models.Model): objects = models.Manager() title = models.CharField(max_length=100, blank=True) body = models.CharField(max_length=10000, blank=True) created_at = models.DateField(auto_now_add=False) class Comment(models.Model): objects = models.Manager() post = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comment') views.py def main_page(request): all_blogs = Blog.objects.all() context = { 'blog' : blog, } return render(request, 'main/home.html', context) template {% for b in blog %} <div> <p>{{b.title}}</p> <div> {{WHERE THE NUMBER OF THIS POST'S COMMENTS IS DISPLAYED}} </div> </div> {% endfor %} All I need is the number of the comments, but have no idea how to do it. Is there a way to make this possible in the template? Or do I have to add some codes in views.py? Thanks. -
The context processor that will pass the variable to the template year
I'm trying to write a context processor that will pass a variable year to the template, the value of which will be the current year as a number: © {{ year }} Copyright from datetime import datetime, date def year(request): return { request, datetime.now().date() } -
How to provide data to react with drf without extra requests?
I build a single page application with react and django rest framework. I want to have an ability to change "static" info through django admin interface to avoid unnecessary extra deploy every time. Such info like background image and text from about section. To edit it I create cms django app and register models in admin. To serve frontend in production I use TemplateView from django.views.generic package. It serves html file from bundled react app directory. here's part of root urls.py: urlpatterns = [ path('admin/', admin.site.urls), # ... # api endpoints here # ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] to serve it in development I use react-scripts start from create-react-app How can I pass information like the current url of the background image, text for about section, etc. there? Simple option is to create bunch of views to get this info and request all the data from react app, but I don't really like this approach. another option is to redefine TemplateView like this from django.views import generic class TemplateView(generic.TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context_data = dict() # get all data from db here return context_data But how then I use this in react app? … -
MultipleObjectsReturned at /profile/ get() returned more than one CustomUser -- it returned 2
What I am trying to achieve CustomUser model is storing user account detail. After logging in, the particular user profile must be fetched using the token generated during signup. Issue I have made phone_number as the primary key and unique attribute is set to True. MY code behaves properly when there is only one user but >1 user, data of all existing users are fetched which is why this error is showing up! Here is the model structure class CustomUser(AbstractUser): first_name = models.CharField(null=True, blank=True, max_length= 50) last_name = models.CharField(null=True, blank=True, max_length= 50) username = models.CharField(null=True, blank=True, max_length= 12) phone_number = models.CharField(primary_key=True, max_length= 10,unique=True) dob = models.CharField(max_length=12, null=True, blank=True) email = models.EmailField(null=True, blank=True) address = models.CharField(max_length= 500,null=True, blank=True) pincode = models.CharField(max_length=10, blank=True,null=True) state = models.CharField(max_length= 256,null=True, blank=True) district = models.CharField(max_length= 56,null=True, blank=True) otp_verified = models.BooleanField(null=True,blank=True, default=False) date_joined = models.DateTimeField(null=True,blank=True) last_login = models.DateTimeField(null=True,blank=True) loyality_level = models.IntegerField(null=True,blank=True) loyality_points = models.IntegerField(null=True,blank=True) gender = models.CharField(max_length= 2,null=True, blank=True) user_type = models.CharField(max_length= 2,null=True, blank=True) objects = MyUserManager() search_fields = ("",) USERNAME_FIELD = 'phone_number' def __str__(self): return self.phone_number @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): return str(AccessToken.for_user(self)) Here is my view for fetching Profile using APIView class ProfileView(APIView): authentication_class = [JWTAuthentication] permission_classes = [IsAuthenticated] try: def get(self, request): … -
Reading django_settings from Google Cloud Platform's Secret Manager does not work
When running the command python manage.py makemigrations locally on my laptop, I get the following error on my console: (mywebsite) C:\Users\Sander\PycharmProjects\mywebsite>python manage.py makemigrations Invalid line: echo DATABASE_URL=postgres://myuser:mypassword@//cloudsql/mywebsite:europe-west6:mywebsite-db/mydb > .env Invalid line: echo GS_BUCKET_NAME=mybucket >> .env Invalid line: echo SECRET_KEY=$(cat /dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n Note that the echo [... etc. ...] > .env instructions are actually the content of a secret I configured on Google Cloud Platform's Secret Manager, when following Google Cloud Platform's instructions for deploying my Django website on Google Cloud Run. Now I do know these echo [... etc. ...] > .env instructions are supposed to create a file .env with the variables DATABASE_URL, GS_BUCKET_NAME and SECRET_KEY in it, but it doesn't, of course, since it reports the error "Invalid line: ..." instead. I found this StackOverflow answer, stating that these bash instructions (echo [... etc. ...] > .env) simply can't be executed by python and that I can simply execute them locally by running them from a shell script instead, so executing this create-env-file.sh works: DATABASE_URL=postgres://myuser:mypassword@//cloudsql/mywebsite:europe-we st6:mywebsite-db/mydb > .env GS_BUCKET_NAME=mybucket >> .env echo SECRET_KEY=$(cat /dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n However, this generates … -
How to add custom field in manytomany through table in Django
I have a model which has manytomany relation with another model. This creates a hidden through table with two foreign key field of previous two tables. Now I want to add custom field in addition to the existing two foreign key field in the through table. Model One: class ModelOne(models.Model): field_one = models.CharField(max_length=264) Model Two: class ModelTwo(models.Model): many_field = models.ManyToManyField(ModelOne, related_name='some_name') field_one = models.CharField(max_length=264) Auto created hidden through table: class appname_modeltwo_modelone(models.Model): model_one_id= models.ForeignKey(ModelOne) model_two_id= models.ForeignKey(ModelTwo) custom_field= models.CharField(max_length=264) # New Custom Field I want to add How can I add new custom field here? -
Not able to run the command "wfastcgi-enable"
So I am trying to deploy a python Django project on windows server 2012R2. But when trying to run the command I get this error. When trying to open the link in IIS manager it show error 500. I am running command prompt as administrator so that did not solve the problem. Python version:3.8.8 IIS 8 If you need to know version of any other library to answer please comment. -
Django Rest Framework. added new list element to request.data, but getting the new element as a double list
I am building a small Django Rest Framework API with APIView. It generates a post with tags which are gotten from the DB, but if there are no tags or I want to add a new tag, a list of tag names is passed into the payload and creates them along the post, then the new tag IDs are added to the request.data['tags']. This is the payload I am passing for new tags: { 'title': 'Test Creating with new tags', 'new_tags': ['newest', 'newer'] } This is the post method: def post(self, request, format=None): """ Creates a Post instance """ if isinstance(request.data, QueryDict): request.data._mutable = True tmp_new_tags = request.data.get('new_tags', None) if tmp_new_tags: new_tags = request.data.pop('new_tags') request.data.update({'tags': []}) for new_tag in new_tags: tag = Tag.objects.create(name=new_tag, user=self.request.user) request.data['tags'].append(str(tag.id)) serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) this is the request.data with existing tags that I am expecting for new tags: <QueryDict: {'title': ['Test Creating'], 'tags': ['1', '2']}> But I got the tags with double [] <QueryDict: {'title': ['Test Creating with new tags'], 'tags': [['3', '4']]}> This is the response.data: {'tags': [ErrorDetail(string="“['3', '4']” is not a valid UUID.", code='invalid')]} How can I append a single List instead of a double … -
Enable post of HTML form to Django database backend
I'm trying to write the code to enable form data to be sent to the backend database. The form is just a few fields, name, website, and portfolio address created in html <div class="card-body"> <form class="needs-validation" form action="/elements/forms/add_investor/" novalidate method="post"> <div class="row"> <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="validationCustom01">Investor Name</label> <input type="text" class="form-control" id="validationCustom01" placeholder="InvestorName" value="MyInvestor" required> <div class="valid-feedback"> Looks good! </div> </div> </div> <div class="col-md-6"> <div class="mb-3"> <label for="example-url-input" class="form-label">Investor Website</label> <input class="form-control" type="url" value="https://example.com" id="example-url-input" requried> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> Please provide a valid web address. </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="mb-3"> <label for="example-url-input" class="form-label">Investor Portfolio</label> <input class="form-control" type="url" value="https://example.com/portfolio" id="example-url-input" requried> <div class="invalid-feedback"> Please provide a valid web address. </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="mb-3"> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-header"> <h4 class="card-title">Comments</h4> <p class="card-title-desc">Please add any comments or notes</p> </div> <div class="card-body"> <div id="ckeditor-classic"></div><br> <button class="btn btn-primary" type="submit">Submit form</button> </div> </div> </div> </form> <!-- end col --> </div> I'm struggling to get understand how I map the fields to the database and then get the submit button posted to the database. I've gone through the Django forms section, but can't … -
Clean way to work with Django UpdateView from preventing it to override and do append to existing data?
I have a modelform that I am rendering on the frontend. One of the field is a select2 dropdown and the user selects an option and adds in relevant detail in the other field e.g class MyForm(forms.ModelForm): name = models.ModelChoiceField(queryset=Test.objects.all(),required=False) data = models.CharField(required = False) ..... Now, the url responsible for handling the POST is as follows /example/<str:name/ Here is my issue, I already have existing data value in the DB for a specific name . What I want is that when the user selects a name in the frontend and adds in some value in the data, the data gets appended to the existing value in the db for that name. I am inheriting from UpdateView and so when I do something like this, it simply overrides the existing data. def form_valid(self,form): obj = form.save(commit=False) #here is where I would like to do something with the existing data for that instance obj.save() One approach that I had in my mind, is actually doing something like this in form save() #modelform save() def save(self,commit=True): #do a fetch from the db about the existing data obj = MyModel.objects.get(id=instance.id) self.data = obj.append_data(obj.data,self.data) #can be a model method return super().save(commit) Is this a … -
Filtering between two datetime in django
How to filter out records that lie in between two datetimes inclusively in django? I have an example code below, however it does not return expected results. # based on the Developer's Tool in Chrome, # request.POST['startDate'] == '2021-10-22T16:00:00.000Z' # request.POST['endDate'] == '2021-10-22T16:00:00.000Z' startDate = timezone.now().strptime(request.POST['startDate'], '%Y-%m-%dT%H:%M:%S.%fZ') endDate = timezone.now().strptime(request.POST['endDate'], '%Y-%m-%dT%H:%M:%S.%fZ')+timedelta(days=1, microseconds=-1) statistics = models.MemberCard.objects.filter(createDate__gte=startDate, createDate__lte=endDate).order_by("-createDate") if len(statistics) > 0: for item in statistics: dateFound.append(item.createDate) Would like to know any issues with the code above that I have written? or any better solutions for this problem are more than welcomed -
Form is saving multiple instances at once
I am building a simple question answer site and I am trying to build comment system in question's answer. But when I add a comment then comment is saving multiple times, For Example :- There are 5 answers and if i comment on one then same five instances are saving and if a question has 3 answers then 3 same comments are saving. models.py Class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() class Answer(models.Model): answered_by = models.ForeignKey(User, on_delete=models.CASCADE) question_of = models.ForeignKey(Question, on_delete=models.CASCADE) body = models.TextField() class Comment(models.Model): commented_by = models.ForeignKey(User, on_delete=models.CASCADE) commented_on = models.ForeignKey(Answer, on_delete=models.CASCADE) text = models.TextField() views.py def save_comment(request, answer_id): if request.method == 'POST': comment = request.POST['comment'] answer = Answer.objects.get(pk=answer_id) commented_by = request.user if comment != "": Comment.objects.create(commented_on=answer, text=comment, commented_by=commented_by) return JsonResponse({'bool':True}) else: return JsonResponse({'bool':False}) template.html {% for answer in answers %} <div class="card my-3"> <h6 class="card-header">Add Comment</h6> <div class="card-body"> <textarea class="form-control comment-answer-text-{{answer.id}}"></textarea> <div class="contain"></div> <button type="button" data-data="{{answer.id}}" class="btn btn-dark my-3 save-answer-comment">Submit</button> </div> </div> <script> $(document).ready(function(){ $(".save-answer-comment").on('click',function(){ var _answerid=$(this).data('data'); var commented=$(".comment-answer-text-"+_answerid).val(); var by = $(".uncommen-text-"+_questionid).val(); // Ajax $.ajax({ url:"{% url 'save_comment' answer.id %}", type:"post", data:{ comment:commented, answerid:_answerid, by : by, csrfmiddlewaretoken:"{{csrf_token}}" }, dataType:'json', }); }); }); </script> {% endfor %} I have tried many times but it …