Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Django how to solve saving empty form problem?I am trying take 2 different forms in one page in my Django project. They have different form models but they are in the same page and use the same view function. When I try them both of them works, but when I post one of them, the other one is also saving as a empty form. But I do not want this. Why this is happening? views.py def ocr(request, id): .... pdf = get_object_or_404(Pdf, id=id) approval = ApprovalProcess(user_id=request.user, highest_rank=1) #FORM 1 if request.method == 'POST': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): form.save() if pdf.risk_rating == "Low Risk": n = len([x for x in doa_low_list if x < pdf.credit_limit]) approval.highest_rank = n elif pdf.risk_rating == "Medium Risk": n = len([x for x in doa_medium_list if x < pdf.credit_limit]) .... approval.save() else: form = PdfRiskForm() #FORM 2 if request.method == 'POST': form_2 = CommentForm(request.POST or None) if form_2.is_valid(): form_2.instance.comment_other = form.cleaned_data.get("comment_other") form_2.instance.username = request.user form_2.instance.comp_name = userP[0].company form_2.instance.doc_id = pdf if form_2.comment_others is not None: form_2.save() else: form_2 = CommentForm() models.py class PdfRiskForm(forms.ModelForm): risk_rating = forms.ChoiceField(label='Risk Rating', choices=Pdf.RISK_RATING) credit_limit = forms.IntegerField() comments = RichTextField letter_portion = forms.IntegerField(min_value=0, max_value=100, required=False, label="Guarantee Portion (%)") class Meta: model = Pdf fields = ['risk_rating', …
- 
        how to predefine associated model foreign key in djangoi created 2 model and both are linked to each other, i created create function view inorder to create the model object. just check my code and read more to know models class group(models.Model): group_name = models.CharField(max_length=100) group_user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'{self.group_name} group' class comments(models.Model): userId = models.AutoField(primary_key=True) name = models.CharField(max_length=100) group = models.ForeignKey(group,on_delete=models.CASCADE,null=True) user = models.ForeignKey(User,on_delete=models.CASCADE) message = models.TextField() date = models.TimeField(auto_now_add=True) def __str__(self): return f'{self.user} comments' views def create(request,pk): if request.method == "POST": name = request.user author = request.user message = request.POST['message'] group = group.objects.GET[pk] message = comments(user=author,message=message,name=name,group=group) message.save() return HttpResponse('') for user i can just type request. user in this case how can auto insert group id from the google adress bar eg: group = self.request['pk'] pls help me in this case
- 
        Dynamically added data not saving into database using djangoclick here for code Dynamically added value not saving into data base. the value are saved only what we are given first time. and the additional added data not saving into database.
- 
        How to get parameters in django pagination url?I have a paginator for my category page. everything is working when I enter the URL manually, but I don't know how to get my category name, since my paginator button doesn't show up. I must go to this link with my paginator : http://127.0.0.1:8000/category/category_name/2 but it only works when I enter it in the addressbar. How should I change my URL ? <a href="{% url 'website:category' cat_articles.next_page_number %}">
- 
        'NoneType' object has no attribute 'views'I am getting a nontype object error in my views I was adding views functionality to my blog but when I use slugify in my tempate it throws nontype object error My models looks like this class Post(models.Model): sno=models.AutoField(primary_key=True) user=models.ForeignKey(User, on_delete=models.CASCADE, null=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) views= models.IntegerField(default=0) timeStamp=models.DateTimeField(blank=True) content=models.TextField() and views looks like def blogPost(request, slug): post=Post.objects.filter(slug=slug).first() allPosts= Post.objects.all() post.views= post.views +1 post.save() comments= BlogComment.objects.filter(post=post, parent=None) replies= BlogComment.objects.filter(post=post).exclude(parent=None) replyDict={} for reply in replies: if reply.parent.sno not in replyDict.keys(): replyDict[reply.parent.sno]=[reply] else: replyDict[reply.parent.sno].append(reply) context={'post':post, 'comments': comments, 'allPosts': allPosts, 'user': request.user, 'replyDict': replyDict} return render(request, "blog/blogPost.html", context) and I am getting this error AttributeError at /blog/cyber-security 'NoneType' object has no attribute 'views' Request Method: GET Request URL: http://127.0.0.1:8000/blog/cyber-security Django Version: 3.1.4 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'views' Exception Location: D:\www\allinfo\blog\views.py, line 21, in blogPost Python Executable: D:\www\venv\Scripts\python.exe Python Version: 3.9.0 Please help me out
- 
        Django-Oscar 3.1.6 Frobshop NullBooleanField warningFollowing the Frobshop docs, I installed django-oscar v3.0.0, which pulled in django v3.1.6. Every time I run manage.py I get this warning: WARNINGS: catalogue.ProductAttributeValue.value_boolean: (fields.W903) NullBooleanField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use BooleanField(null=True) instead. I grepped for NullBooleanField in the Frobshop source, but there were no results. Is there a way to either fix the problem or suppress the message?
- 
        TypeError: create() missing 1 required positional argument: 'validated_data' - djangoi have a table that contains many to many and foreign key relation class TableRelation(models.Model): table1 = models.ForeignKey(table1, on_delete=models.CASCADE) table2 = models.ForeignKey(table2, on_delete=models.CASCADE) table3 = models.ManyToManyField(table3) iam using mixins and generic view set for listing and updating. listing retrieve works fine . but when i update or create it shows AssertionError: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer table1.serializers.TableRelationSerializer, or set read_only=True on nested serializer fields. so i have written a create methode in the serializer class TableRelationSerializer(serializers.ModelSerializer): table1 = Table1Serializer() table2 = Table2Serializer() table3 = Table3Serializer(many=True) class Meta: model = TableRelation fields = ('id', 'table1', 'table2', 'table3',) def create(self, instance, validated_data): remove_table1 = validated_data.pop('table1',) remove_table2 = remove_role.pop('table2') table_data = remove_permission.pop('table3') table1 = Table1.objects.create(**validated_data) table2 = Table2.objects.create(**validated_data) table3 = Table3.objects.create(**validated_data) TableRelation.objects.create( table1=table1, table2=table2, table3=table3, **table_data) return "fhfh" then iam getting this error TypeError: create() missing 1 required positional argument: 'validated_data' i have tried some other method then also iam getting this error
- 
        Get queryset is showing/saving my model twice because of 'or' statementI have been using code below in admin.py to show me users that are only in these two groups (test1 and/or test2, user can be in one or both of them in the same time. I want to show in the model only users that are in the group). def get_queryset(self, request): qs = super(PersonUser, self).get_queryset(request) return qs.filter(groups__name='test1') | qs.filter(groups__name='test2') But the problem occurs with the 'or' statement, because when user is in both, then he is shown/saved twice, which is causing a bug. How can I properly change it?
- 
        Show category according to location of a userI am trying to show categories to a user according to their location. The 'City' is listed in the User Model and 'Category Details' are in a different model called CategoryModel. The added_by field contains the 'email' of the users. How do I query the users model and get the list of all users in that city and filter the list with the category model and get all the categories available under that particular city? Here is the models: class UserList(AbstractUser): UserMiddleName = models.CharField(max_length=100, null=True) usertype = models.ForeignKey(UserType, on_delete=models.CASCADE) Application = models.ForeignKey(AppliationList,on_delete=models.CASCADE, null=True) ContactCell = models.CharField(max_length=100, null=True) City = models.CharField(max_length=30) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'usertype', 'username', 'first_name', 'last_name', ] AbstractUser._meta.get_field('email')._unique = True def __str__(self): return self.email class CategoryList(models.Model): CategoryName = models.CharField(max_length=300) AddedBy = models.ForeignKey(UserList, on_delete=models.CASCADE) AddedDate = models.DateField(auto_now_add=True) UpdatedBy = models.ForeignKey(UserList, related_name="Category_Updated_By", on_delete=models.CASCADE, null=True) UpdatedDate = models.DateField(auto_now_add=True) IsActive = models.BooleanField(default=True) def __str__(self): return self.CategoryName Here is the query I wrote that pulls the list of users from a particular city but how do I modify it to get all the categories listed by these users? USE [testenr] GO CREATE PROCEDURE [dbo].[getCategory] @city varchar(30) = NULL AS SELECT * FROM [dbo].[accounts_userlist] WHERE [City]=@city AND [usertype_id] = 1 GO
- 
        Query a M2M related field in DjangoI have a Model Return in my projects like the following: class Kit(models.Model): kit_name = models.CharField(max_length=500, default=0) kit_info = models.CharField(max_length=500, default=0) kit_client = models.ForeignKey(Client, on_delete=models.CASCADE) class ReturnKits(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) items = models.ManyToManyField(ReturnKitsProducts) class Return(models.Model): transaction_date = models.DateTimeField(default=datetime.now) transaction_no = models.IntegerField(default=0, blank=True, null=True) is_delivered = models.BooleanField(default=False) How can I select all the Return objects which contains the kit with kit_client = 4? I know we can query directly related objects using __ but how to query nested ones ?
- 
        Django best practices for testing built-in authentication viewsI read somewhere that: In testing a web-application, one should test all aspects of one's own code, but not any libraries or functionality provided as part of Python or Django. Now I'm trying to figure out what this means in regard of the built-in authentication system provided by Django. More precisely, I use the built in authentication system, i.e., urlpatterns = [ path('', include('django.contrib.auth.urls')), ] and now I want to write some tests. First Question: Should I write tests for checking that every url exists and uses the right template for every view? I.e., should I write def test_view_url_exists_at_desired_location(self): response = self.client.get('/login/') self.assertEqual(response.status_code, 200) def test_view_url_accessible_by_name(self): response = self.client.get(reverse('login')) self.assertEqual(response.status_code, 200) def test_view_uses_correct_template(self): response = self.client.get(reverse('login')) self.assertTemplateUsed(response, 'registration/login.html') for all 8 views? I feel like I should test something, but at the same time it feels kind of redundant to test the same thing 8 times. Second Question: I guess I don't have to test the functionality of the views if I use the built in user model, for example, I don't have to test that the login view actually logs-in a user etc. However, I'm using a custom user model (based on AbstractBaseUser) where email is used instead of …
- 
        How I can calculate if time is more than one minute in dajngo?I am working on django rest APIs where I have to expire a random generated code after one minute. But I am having problem that how I can check weather the time is more than one minute? Thanks in advance for your addition in my knowledge.
- 
        How to fix Django ImageField upload error on admin panel?I have a model in django named MainPagePicture: class MainPagePicture(models.Model): image = models.ImageField(upload_to='gallery/', null=False) when I try to upload a big image (1 MB and bigger) using admin panel I get this error Error Picture I have no problem with small images (I tried 30 Kb and 16 KB Images) and it works good. my admin.py class is: @admin.register(MainPagePicture) class MainPagePictureAdmin(admin.ModelAdmin): class Meta: model = MainPagePicture my django version is 3.1.6 and pillow version is 8.1.0 and Database is PostgreSQL.
- 
        Django Form is not submitting, after clicking submit it's redirecting to the same pageIt's supposed to redirect to detail page after storing the data. However, through Admin it allows to add post. I've checked multiple times views, forms and models there's no error while rendering or after clicking submit button I've also removed the reverse fnc in models and then tried also removed the views fnc but still it doesn't give any errors...I think I made some error in the very beginning. models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from django.db.models import Max #from ckeditor.fields import RichTextField BU_CHOICES = ( ('Selection','Selection'), ('Discoverability and Availability', 'Discoverability and Availability'), ('Buying Experience' , 'Buying Experience' ), ('Post-Buying Experience','Post-Buying Experience'), ('Flex','Flex'), ) MP_CHOICES = ( ('AE','AE'),('AU','AU'),('BR','BR'),('CA','CA'), ('CN','CN'),('DE','DE'),('ES','FR'),('GB','GB'), ('IN','IN'),('IT','IT'),('JP','JP'),('MX','MX'), ('NL','NL'),('PL','PL'),('SA','SA'),('SE','SE'), ('SG','SG'),('TR','TR'),('US','US') ) FNCT_CHOICES = ( ('NIS','NIS'), ('DR', 'DR'), ('FLEX','FLEX'), ('VSP-SELECTION','VSP-SELECTION'), ('INSTOCK-VCM','INSTOCK-VCM'), ('MARKETING & VENDOR ATTRITION','MARKETING & VENDOR ATTRITION'), ('PROFITABILITY','PROFITABILITY'), ('VCM','VCM'), ('PROGRAM','PROGRAM'), ('TRAINING AND ACES','TRAINING AND ACES'), ('AUTOMATION','AUTOMATION'), ('MIS','MIS'), ('DATA ENGINEERING','DATA ENGINEERING'), ) TASK_CHOICES = ( ('NIS','NIS'), ('DR', 'DR'), ('FLEX','FLEX'), ('VSP-SELECTION','VSP-SELECTION'), ('INSTOCK-VCM','INSTOCK-VCM'), ('MARKETING & VENDOR ATTRITION','MARKETING & VENDOR ATTRITION'), ('PROFITABILITY','PROFITABILITY'), ('VCM','VCM'), ('PROGRAM','PROGRAM'), ('TRAINING AND ACES','TRAINING AND ACES'), ('AUTOMATION','AUTOMATION'), ('MIS','MIS'), ('DATA ENGINEERING','DATA ENGINEERING'), ) NUM_CHOICES =( ('1','1'),('2','2'),('3','3'),('4','4'),('5','5') ,('6','6'),('7','7'),('8','8'),('9','9') ) class Risk(models.Model): id = models.CharField(primary_key=True, editable=False, max_length=10) time = models.DateTimeField(default=timezone.now) header …
- 
        dont work staticfiles on prod (django docker nginx)heelp!! i containerize my django app, but static filese in debug=false have 404. What i doing incorrectly? django_gunicorn_1 | Not Found: /static/admin/js/nav_sidebar.js django_gunicorn_1 | Not Found: /static/admin/css/base.css etc dockerfile for django FROM python:3.9.0-slim WORKDIR /app COPY ["./commondev", "./requirements.txt", "./entrypoint.sh", "./"] RUN pip install --upgrade pip && pip install -r requirements.txt EXPOSE 8000 ENTRYPOINT ["sh", "./entrypoint.sh"] and for nginx FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf
- 
        django rest with JWT authentictionI would like to know how to perform a full login with django rest framework using JWT tokens for authentication. Here is part of the login code: @api_view(['POST']) def login_user(request): data=request.data serialized=UserSerializer(data=data) if serialized.is_valid(): email=serialized.data['email'] password=serialized.data['password'] user=authenticate(request, username=email, password=password) if user is not None: try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) login(request,user) message="Logged in successfully" except User.DoesNotExist: message="User does not exist" else: message="User does not exist " data={ "message": message, "token": jwt_token } return JsonResponse(data) I am a bit lost. Could anybody guide me please
- 
        How to auto refresh the page without left the last place of userI am building a BlogApp and I am stuck on a Problem. I am making a Blog Page in which Users can upload Blogs. What i am trying to do I want Blog page to auto refresh the Page. without auto going at the Top of the Page. I want user to stay still on that place where user was before refresh. What have i tried <script> window.setTimeout(function () { location.href = 'http://127.0.0.1:8000/blog_posts'; }, 5000); //refresh/redirect after 5 seconds. </script> What's the problem in this JavaScript Code ^ In the JavaScript code below. It is working fine, It refresh the page very well in every 5 seconds. BUT when it refresh the page then if i am scrolling down while seeing blogposts then Page Refresh, then after refresh i find myself on top of the page. ( If a user is scrolling down and JavaScript refresh the page then the user find himself/herself on top the page ). That's Why its a Big Problem. I don't know what to do. Any help would be Appreciated. Thank You in Advance.
- 
        Is it possible to create snake case `related_name` from class interpolation in Django related fields?Django allows us to use '%(class)s' to automatically create related name from mixins. But when I have a ClassName I'd rather access it using class_name, not classname. I know it's only semantics but I was wondering if it's possible to adjust model field to make it snake case instead. I was browsing through django.db.models.fields but I can't find where the class interpolation is happening. Example code from django.db import models class User(models.Model): pass class UserRelatedMixin(models.Model): user = models.OneToOneField( to=User, parent_link=True, on_delete=models.CASCADE, related_name='%(class)s', related_query_name="%(class)s", ) class Meta: abstract = True class HomeAddress(UserRelatedMixin): pass user = User.objects.first() What I have user.homeaddress What I want instead user.home_address Right now I'm using a @property but it won't allow ORM queries so it's a partial solution.
- 
        Django rest framework update ManyToManyFieldmodels.py class Game(models.Model): name = models.CharField(max_length=255) gamemodes = models.ManyToManyField(GameMode, related_name='gamemodes', blank=True) class GameMode(models.Model): name = models.CharField(max_length=255) serializers.py class GameModeSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ['pk', 'name'] model = GameMode class GameSerializer(serializers.HyperlinkedModelSerializer): gamemodes = GameModeSerializer(many=True, required=False) class Meta: model = Game fields = ['pk', 'name', 'gamemodes'] Updating name works perfectly with PATCH. But how can I add a "gamemode" to the Game object in the rest framework? Best
- 
        Django + Postgres - slow postgres queries revert previous model changesI'm facing a strange issue where a model instance in django is updated several times in succession, but the first update statement sometimes hangs/takes a while in postgres and when it does execute, it overrides previous updates. This all happens in a pipeline of different tasks that alter the model. A simplified example: A simple model (the actual one has more fields, but no too large ~20-25 fields) and the processing logic: class Foo(models.Model): status = models.CharField(...) number = models.CharField(...) foo = models.CharField(...) bar = models.CharField(...) # As it's part of a framework, this method is expected to save the whole models instance def set_status(self, status): with transaction.atomic() self.status = status self.save() self.process_status(status) # A pipeline of different tasks that will be executed based on Foo.status processing_pipeline = { 'a': 'set_status_to_b', 'b': 'set_number', 'c': 'set_foo', 'd': 'set_bar' } def process_status(self, new_status): # finds a task from the pipeline based on new status and executes it task = self.processing_pipeline.get(new_status, None) if task: getattr(self, task)() def set_status_to_b(self): self.set_status('b') def set_number(self): self.number = 1 logger.info('Setting number to 1') if self.foo: self.set_status('d') else: self.set_status('c') def set_foo(self): self.foo = 'foo' logger.info('Setting foo') self.set_status('d') def set_bar(self): # this creates some related models self.create_m2m_relationships_somewhere() self.bar = 'bar' …
- 
        The current path, chat/room/1/, didn't match any of theseI am practicing with Django 3 and I have a chat project with the name of educa . I try to run the project by python manage.py runserver and access http://127.0.0.1:8000/chat/room/1/ . I always get the following error messages: “Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/chat/room/1/ Using the URLconf defined in educa.urls, Django tried these URL patterns, in this order: 1.accounts/login/ [name='login'] 2.accounts/logout/ [name='logout'] 3.admin/ 4. course/ … ** The current path, chat/room/1/, didn't match any of these.” ** I really don’t know what’s wrong. Please someone help me .Thank you. The following are the files : educa/ruls.py : urlpatterns = [ … path('chat/', include('chat.urls', namespace='chat')), ] chat/urls.py: app_name = 'chat' urlpatterns = [ path('room/int:course_id/', views.course_chat_room, name='course_chat_room'), ] chat/views.py: @login_required def course_chat_room(request, course_id): ... return render(request,'chat/room.html', {'course': course}) chat/templates/chat/room.html: {% extends "base.html" %} {% block title %}Chat room for "{{ course.title }}"{% endblock %} {% block content %} …. {% endblock %} {% block domready %} ... {% endblock %} educa/settings.py: INSTALLED_APPS = [ ... 'chat', 'channels', ]
- 
        how to add the multiple row data into postgresql db using djangoI want to create a table inside the Django forms and the table consists of number of rows with different data. Whenever I run the code in database it shows only the 1st row data and not the next row data pls solve me this...
- 
        Django ModelViewSet increase foreign key list limitI'm using the django-rest-framework to make entries into the database, and can make POST requests from there, and select foreign keys from a drop down list for each attribute. However, the limit of entries to select is set to 1000, so when it surpasses this then I cannot select what I want. In my example below I have more than 1000 Owner entries in the database. How can I increase this limit? class CatViewSet(viewsets.ModelViewSet): queryset = Cats.objects.all() serializer_class = CatSerializer filter_fields = '__all__' class CatSerializer(serializers.ModelSerializer): class Meta: model = Cats fields = '__all__' class Cat(models.Model): pwner = models.ForeignKey(Owner, on_delete=models.CASCADE) name = models.CharField() router = routers.DefaultRouter() router.register(r'cats', CatViewSet) urlspatterns = [ path(r'', include(router.urls)) ]
- 
        django admin : string index out of range errorFollowing is the traceback for the django admin erorr I am getting. I am able to open all admin pages except this one. I am using django with mongodb. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/datarepo/production/ Django Version: 2.2.8 Python Version: 3.7.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'datarepo', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Abhi\Office\django\virtualenv1\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 62 string index out of range 52 : {% endblock %} 53 : </div> 54 : {% endif %} 55 : {% endblock %} 56 : {% block nav-global %}{% endblock %} 57 : </div> 58 : <!-- END Header --> 59 : {% block breadcrumbs %} 60 : <div class="breadcrumbs"> 61 : <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> 62 : {% if t itle %} &rsaquo; {{ title }}{% endif %} 63 : </div> 64 : {% endblock %} 65 : {% endif %} 66 : 67 : {% block messages %} 68 : {% if messages %} 69 : <ul class="messagelist">{% for message in messages %} 70 : <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li> 71 : {% endfor %}</ul> 72 : {% …
- 
        Django - Tastypie inegrate url from third party-appI'm writing a reusable app for a django application. The API endpoints of the application are written in tastypie I want to add a new endpoint (always with tastypie)from my app to the existing ones without touching the original app. This is my urls.py in my external app from myapp.views import MyResource from originalapp.urls import api from originalapp.urls import routers api.register(MyResource()) router = routers.DynamicRouter() The api imported is the origin Api() object needed for tastypie Even if i update the app via pip the new endpoint is not available in the urls list of the application. Any suggestion?