Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setup Django reusable app with management commands
I'm trying to create a reusable Django app with setuptools (doc) and the app has some custom management commands (that can be run with manage.py) and they are inside the management directory as they should. However, when I run python setup.py sdist to pack everything, this management directory is ignored and not included in the package and thus, when I install the package with pip I can't use those commands. How should I have those commands available in the package and future projects that use this package? -
in Django project. When annotate in views, getting error that item is not defined
I know, that this subject has been mentioned few times, but I can't find a solution for my problem. So please accept my apologies for a repeat request. I have a condition-based filter, that doesn't work for me. here is my models.py file: from __future__ import unicode_literals from django.db import models from django.conf import settings from math import * from decimal import * from django.urls import reverse from django.contrib.auth.models import User class Itemslist(models.Model): safety_stock = models.DecimalField(blank=True, null=True, max_digits=19, decimal_places=0) current_stock = models.DecimalField(max_digits=19, decimal_places=0) def above_below_ss(self): ab = Decimal(self.current_stock-self.safety_stock) return round(ab,0) def __str__(self): return self.item_n Sorry, have to correct indentation, as it all belongs to one model class. and here is what I have in views.py file: from django.shortcuts import render, redirect, get_object_or_404 from .models import * from .forms import ItemsForm, PostForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm, User from .forms import SignUpForm, EditProfileForm from django.views import View from django.views.generic import ListView, DetailView from .filters import UserFilter from decimal import Decimal from django.http import HttpResponseRedirect from math import * from decimal import * from django.db.models import Count, Q, F, Func #(I have tried it to make it work) def toorder(request): … -
Testing get_context_data() on ListView throws 'AttributeError: object has no attribute 'object_list'
I am trying to test my custom get_context_data() method on a ListView and I keep running into this error: AttributeError: 'Home' object has no attribute 'object_list' The view works fine. Testing that the view responds with 200 status code works fine. I just cannot seem to be able test my custom get_context_data method. Test import pytest from mixer.backend.django import mixer from django.test import RequestFactory from django.urls import reverse from tracker.views import * from tracker.models import Peak pytestmark = pytest.mark.django_db @pytest.fixture def factory(): return RequestFactory() def test_number_of_peaks_completed(factory): mixer.cycle(7).blend(Peak, complete=True) mixer.cycle(10).blend(Peak) path = reverse('home') request = factory.get(path) view = Home() view.setup(request) context = view.get_context_data() assert context['number_of_peaks_completed'] == 7 View from django.views.generic import ListView from tracker.models import * class Home(ListView): model = Peak template_name = 'tracker/home.html' context_object_name = 'peaks' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['number_of_peaks_completed'] = Peak.objects.filter(complete=True).count() return context Error Trace FAILED [ 16%] tracker/tests/test_views.py:24 (test_number_of_peaks_completed) factory = <django.test.client.RequestFactory object at 0x7efbfb8093a0> def test_number_of_peaks_completed(factory): mixer.cycle(7).blend(Peak, completed=True) mixer.cycle(10).blend(Peak, completed=False) path = reverse('home') request = factory.get(path) view = Home() view.setup(request) > context = view.get_context_data() tracker/tests/test_views.py:33: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
i want data life ,if i type 'a' all data related to a appears,i want this for all alphabets
#what should i do if i want the data as per my alphabet(FOR ANY ALPHABET) def list(self,request): try: user=add_category.objects.filter(i) users=[] for i in user: users.append({ 'addcategory':i.addcategory }) return Response({'data':users}) except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
Template rendering error by unicodeDecodeError in Django
I launched the Django project to maintain service. Then I got the following error. UnicodeDecodeError at /register/ 'utf-8' codec can't decode byte 0xb7 in position 3: invalid start byte It was very simple operation that render the page with template. Django says error happened in template file but it was decoded as UTF-8. The working environments are, - Python 3.6.10 installed by pyenv. - Django 2.1.8 - macOS Catalina -
Django Multiple Inheritance avoid, method conflict
class Piece(models.Model): pass class Article(Piece): article_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True) ... class Book(Piece): book_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True) ... class BookReview(Book, Article): pass Im looking at some documentation, it said that the above code can be used to provide additional fields and methods to BookReview without any conflicts Im getting the error You are trying to add a non-nullable field 'article_piece' to article without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 2 What would the default even be and what instance of article_piece, book_piece would i use when instantiating BookReview? -
how to run django server seccond time I have install a django successfully
how to run django server seccond time I have install a django successfully in my localhost with cmd yesterday now i want to run the django again so how can i run now.than you in advantge. -
import class from another/folder into views, django
I am making a scraper function with tidy folder structure. But when I try to import scraper class into views.py it's giving an error: 'module' object is not callable This is the Tree: ├── api_services │ ├── spiders │ │ ├── spiderAtom.py │ │ └── spiderEbis.py │ └── views │ └── viewApi.py In spiders folder I have this class: class spiderAtom: def atom(): string = "return this method" return string and trying import it in viewApi from ..spiders import spiderAtom def atomApi(request): spider = spiderAtom() response = spider.atom() return HttpResponse(response) But with the the way I am doing is not working. -
Conditional Choice field in django model
Is it possible or good practice to set choice field relative to another choice field as in example below : CHOICES = ( (1,'a'), (2,'b) ) choice1 = (()()) choice2 = (()()) class ABC(models.Model): choice = models.IntegerField(choices = CHOICES) nested_choice = models.IntegerField(choices = [if 1 then choice1 elif 2 then choice2]) -
How to create multiple class attribute with a for loop?
I need to create 16 identical forms.Charfield in a Django form. So, basically I need something like this: Class MyClass(forms.Form): a_1 = forms.CharField() .... a_16 = forms.CharField() Is there a way to create them in a for loop so I do not have to type the same thing 16 times? I have tried: Class MyClass(forms.Form): for i in range(1, 17): i = forms.CharField( label = str(i), required = False, max_length = 100, ) but this only creates one field because of course i is not expanded into 0, 1, 2 ... 16 I also tried to use setattr outside the class and to store the forms.CharField objects in a list but these did not work either. No field is shown in the rendered page. Class MyClass(forms.Form): b = forms.CharField() for i in range(1, 17): setattr( MyClass, 'qt_'+str(i), forms.CharField( label = 'Other TMT labeling', required = False, widget = forms.Textarea(attrs={'rows':4,}), ) ) Class MyClass(forms.Form): l = [] for i in range(1, 17): l.append(forms.CharField( label = str(i), required = False, max_length = 100, ) ) -
How to use django-bootstrap-datepicker-plus TimePickerInput with am/pm?
Using django-bootstrap-datepicker-plus was super easy to set up. But using the TimePickerInput has been tricky. It defaults to 24-hour time. So I was able to change it to US am/pm time by doing this: widget = TimePickerInput(format='%I:%M %p') which created this strange looking but functional time picker: My issue is at form validation. 03:39 am is not a valid time. If I remove the am/pm from the TimePickerInput format (so dates appear like 03:39) it validates successfully. But I obviously need to keep am/pm - which is preventing the save. <ul class="errorlist"><li>disposal_time<ul class="errorlist"><li>Enter a valid time.</li></ul></li></ul> I've modified the clean method in the form def clean(self): cleaned_data = super(TempForm, self).clean() form_disposal_time = self.data.__getitem__('disposal_time') form_disposal_time = datetime.strptime(form_disposal_time, '%I:%M %p').time() cleaned_data['disposal_time'] = form_disposal_time return cleaned_data This creates what I believe to be a valid Python time 03:39:00. But the form still rejected it as an invalid time. And adding validation to the model is too far along in the process. I'm not sure if my clean() method is not working or if I need to intercept form validation somewhere else. So besides moving to Europe and adopting the 24-hour clock is there any way I can fix this? -
How to get requests post body on django?
requests post: requests.post('http://643f3392.ngrok.io/test_linux/', data={"jsondata": "here", "you_got":"data"}) I want to get data like this(views.py): def get_data(request): request.POST.get("data", None) How to get {"jsondata": "here", "you_got":"data"} on django? -
Following each other django model
I want to build model to follow each other, I tried to folow this link But I'm facing some error. class InstagramBot(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) email = models.CharField(verbose_name='Email', max_length=55) ............ and another model is here class Following(models.Model): target = models.ForeignKey(InstagramBot, on_delete=models.CASCADE, related_name='followers_set') follower = models.ForeignKey(InstagramBot, on_delete=models.CASCADE, related_name='targets_set') Here i want to make sure that, -> same bot cannot follow itself -> same bot cannot follow other bots multiple times -> I want to get list of all the bot with number of followers -
Best practice for localization in Django?
I am trying to provide translation for the opera librettos (texts). Right now I have the following model: libretto_original is the original language that the opera is written in (German). libretto_trans is the language that it is translated into from the original language (English). Libretto(models.Model): libretto_original = models.TextField(max_length=8000, null=True, blank=True) libretto_orig_lang = models.CharField(max_length=100, null=True, blank=True) libretto_trans_1 = models.TextField(max_length=8000, null=True, blank=True) libretto_trans_1_lang = models.CharField(max_length=5, null=True, blank=True) I check the original_language against the user's default lang (e.g. English). If it is the same, I will not show the libretto translation. If it is different than I will show the original and the translated libretto side by side. I know that Django has localization modules. But reading the documentation it seems like it's for short snippets of text, not for long formatted text with special characters (like ß, ü). I was wondering what is the best way to implement this? A few things to consider. 1) There may be more many many translations of the original libretto I want to store. 2) It's very difficult to mark snippets of text (i.e. {% trans %}). I have wrong pages of the text I want to translate. -
How to place all related records under one parent key in python dictionary
My query is as follows. query_result = [{'ID': 61, 'CAMP_DETAIL_ID': 1462, 'CAMP_START': datetime.datetime(2020, 1, 1, 0, 0), 'CAMP_END': datetime.datetime(2020, 2, 1, 0, 0), 'ISACTIVE': 1, 'ACTIVETRACKING': 1, 'TRACKINGCYCLE': 5, 'MAILSUBJECT': 'MCBAH Testing Campaign', 'CAMPAIGN_CODE': 'Testing', 'CAMPAIGN_DESCRIPTION': 'First Testing Campaign', 'ACCOUNT_SNO': 1810028081, 'CUSTOMER_EMAIL': 'm.fawadkhalid@gmail.com', 'MOBILE_NO': '923000704342', 'ACCOUNT_NAME': 'MOHAMMAD FAWAD KHALID', 'MAILSTATUS_APP': 'D', 'CAMPAIGN_OBJECTIVE_ID': 2, 'OBJECTIVE': 'SIP Payment', 'CAMPAIGN_DOCS_ID': 121, 'DOCUMENT': 'App_download_urdu_1.html', 'LAST_CYCLE': '2'}] By list comprehension i created a nested dictionary. But the parent key is repeating multiple times qr_dict = [{'ID':i.pop('ID'), 'data': i} for i in query_result] output of above comprehension is [{'ID': 61, 'data': {'ACCOUNT_NAME': 'MOHAMMAD FAWAD KHALID', 'ACCOUNT_SNO': 1810028081, 'ACTIVETRACKING': 1, 'CAMPAIGN_CODE': 'Testing', 'CAMPAIGN_DESCRIPTION': 'First Testing Campaign', 'CAMPAIGN_DOCS_ID': 121, 'CAMPAIGN_OBJECTIVE_ID': 2, 'CAMP_DETAIL_ID': 1462, 'CAMP_END': datetime.datetime(2020, 2, 1, 0, 0), 'CAMP_START': datetime.datetime(2020, 1, 1, 0, 0), 'CUSTOMER_EMAIL': 'm.fawadkhalid@gmail.com', 'DOCUMENT': 'App_download_urdu_1.html', 'ISACTIVE': 1, 'LAST_CYCLE': '2', 'MAILSTATUS_APP': 'D', 'MAILSUBJECT': 'MCBAH Testing Campaign', 'MOBILE_NO': '923000704342', 'OBJECTIVE': 'SIP Payment', 'TRACKINGCYCLE': 5}}, {'ID': 61, 'data': {'ACCOUNT_NAME': 'MOHAMMAD FAWAD KHALID', 'ACCOUNT_SNO': 1810028081, 'ACTIVETRACKING': 1, 'CAMPAIGN_CODE': 'Testing', 'CAMPAIGN_DESCRIPTION': 'First Testing Campaign', 'CAMPAIGN_DOCS_ID': 121, 'CAMPAIGN_OBJECTIVE_ID': 2, 'CAMP_DETAIL_ID': 1462, 'CAMP_END': datetime.datetime(2020, 2, 1, 0, 0), 'CAMP_START': datetime.datetime(2020, 1, 1, 0, 0), 'CUSTOMER_EMAIL': 'm.fawadkhalid@gmail.com', 'DOCUMENT': 'App_download_urdu_1.html', 'ISACTIVE': 1, 'LAST_CYCLE': '2', 'MAILSTATUS_APP': 'D', 'MAILSUBJECT': 'MCBAH Testing Campaign', 'MOBILE_NO': '923000704342', 'OBJECTIVE': … -
Create directory of username in s3 from django
I want to create directory on s3 by taking name from Django SQL database how can I do this? I am trying to do this but it shows '{}' directory name in s3 bucket -
Does changing Django's TIME_ZONE have any negative effects?
I'm using Postgres I have USE_TZ=True I have TIME_ZONE='America/Los Angeles' I am about to switch TIME_ZONE to UTC. Will there be negative effects, gotchas, or anything I need to consider? Or will it just work since the date time is standardized? (I notice in my db rows that dates are stored with +08, which is indeed America/Los Angeles.) The documentation mentions that if I use Postgres, I can swap USE_TZ freely, but doesn't mention changing TIME_ZONE. -
Django ORM "filter" method produces SQL query without quotes
I am building an app with Django relying on several PosgreSQL databases which I do not manage, let's call them database A and database B. For each database, I've used python manage.py inspectdb to build my models.py files. I am trying to use Django ORM to perform the following query (significantly simplified here): sample = my_model_in_B.objects\ .filter(a_column=instance_of_a_model_in_A.name)\ .exclude(another_column='Useless things') My issue is that it produces the following SQL query: SELECT "myschema"."mytable"."a_column", "myschema"."mytable"."another_column" from "myschema"."mytable" WHERE "myschema"."mytable"."a_column" = Here is the name of instance_of_a_model_in_A AND NOT ("myschema"."mytable"."another_column" = Useless things AND "myschema"."mytable"."another_column" IS NOT NULL)) In other terms, my issue is that the Django ORM does not automatically add quotes where I need them. I don't understand what I did wrong. I don't know if that matters but note that: I use Django 2.2. and my database B is POSTGRESQL 8 only, All the columns that I use correspond to "CharField" in my models. Any help appreciated. Thank you in advance. -
Hi there, i need a help, i want to display total post count in parents category , how do i that?
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['category_list']=Category.objects.filter(parent__isnull=True).annotate(num=Count('products')) return context index.html {% for category in category_list %} <div class="single-category"> <a href="{{category.get_absolute_url}}"> {{category.title}} {{category.num}} <span style="color: gray;"> </span> </a> </div> {% endfor%} # i got data like this Electronic 0 Jobs 0 but in child category i have two post, i wanna display in parent category total post count in all subcategories -
User matching query does not exist; User.DoesNotExist exception handler is defined
I'm attempting to create a new user through a view that implements a subclass of UserCreationForm called ChefRegisterationForm. The test data that has been supplied in a test case has been validated. However if I'm querying for an existing user with Model.get(), I get the following error... django.contrib.auth.models.DoesNotExist: User matching query does not exist. I'm not clear on what is causing this error as there is an User.DoesNotExist exception handler defined if the query fails. forms.py class ChefRegisterationForm(UserCreationForm): username = forms.CharField(validators=[validate_username]) def clean(self): cleaned_data = super().clean() submitted_username = cleaned_data.get('username') submitted_password = cleaned_data.get('password1') if submitted_username == submitted_password: raise ValidationError( "Your password cannot be your username.", code="invalid_password" ) class Meta: model = User fields = ['username', 'password1', 'password2'] views.py def register_chef(request): if request.method == 'POST': new_user_form = ChefRegisterationForm(request.POST) if new_user_form.is_valid(): try: username = new_user_form.cleaned_data['username'] user = User.objects.get( username=username ) except User.DoesNotExist: user = authenticate( username=new_user_form.cleaned_data['username'], password=new_user_form.cleaned_data['password2'] ) login(request, user) messages.info(f"Logged in: Chef {user}") return HttpResponseRedirect(reverse("menu:menu_list")) else: stored_password = check_password( new_user_form.cleaned_data['password1'], user.password ) if stored_password: messages.info( request, "You already registered an account. Please log in." ) else: messages.info( request, f"Username {username} exists. Choose another username." ) return HttpResponseRedirect(reverse("chef:create_chef")) messages.info( request, "Registeration failed. Please try again." ) new_user_form = ChefRegisterationForm() return render(request, "chef/register_chef.html", {'form': … -
How to apply django lazy loading to load my comments?
I am tried but i am not getting the desired output for lazy loading views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) content_type = ContentType.objects.get_for_model(Post) obj_id = post.id comments = Comment.objects.filter( content_type=content_type, object_id=obj_id) parent_id = request.POST.get("parent_id") csubmit = False if parent_id: content_type = ContentType.objects.get_for_model(Comment) Comment.objects.create(content_type=content_type, object_id=parent_id, parent_id=parent_id, user=request.user, text=request.POST.get("text")) if request.method == 'POST': form = CommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.content_type = content_type new_comment.user = request.user new_comment.save() csubmit = True else: form = CommentForm() return render(request, 'post_detail.html', {'post': post, 'comments': comments, 'csubmit': csubmit, 'form': form}) I want to apply lazy loading in the above view and want to apply on template. Can someone help me to do so. Thank you -
django-tables2 doesn't sort columns properly
In the project, I have used RequestConfig(request).configure(table) to apply sorting across the columns. All of them are defined as ArrayField(models.CharField(max_length=50), null= True) . The problem is that the title and year can be sorted, but the other three cannot be sorted properly. I get larger values among the smaller ones. I suppose the Title and Year are strings, but the others are lists containing integers. Can some one have a lead on how to properly sort the three columns in the middle ?Table Headers Second column not sorted properly -
convert field to integer before using in admin, ordering by that field
At the moment, in my admin, i am ordering YelpCompanys by annual_revenue. Some of the annual revenues contain characters that are not numbers. I have a function on the model that converts annual_revenues to integers. How do I use this function in my ordering function in the admin? Any help is appreciated -- thanks in advance. Here is my code: models.py class YelpCompany(models.Model): title = models.CharField(max_length=255) url = models.URLField(max_length=255, unique=True) messaged = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=True) city = models.CharField(max_length=255, blank=True, null=True) company_type = models.CharField(max_length=255,blank=True,null=True) not_available = models.BooleanField(default=False) annual_revenue = models.CharField(max_length=255, blank=True,null=True) def __str__(self): return self.title def revenue_to_int(self): try: return int(self.annual_revenue) except Exception as e: if 'less than' in self.revenue: return self.revenue.split('less than ')[1].replace('$','').strip() elif 'million' in self.revenue: return self.revenue.split('to')[0].replace('$','').strip() else: return 0 admin.py @admin.register(YelpCompany) class YelpCompanyAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(messaged=False,not_available=False) list_display = ('title','url','messaged','city','annual_revenue','not_available') ordering = ('annual_revenue',) -
I want to disable the download button after 15 minutes of the updated time. I dont know how to do it
I recall the updated time time from database. I want to disable the button 15 minutes after the updated time and keep disable even after reload or refresh the page. ''' {% trans 'Updated time' %} {{ app.updated_time | default:_('Not provided.') }} {% trans "Download" %} ''' -
How to clear initial values on SelectMultiple widget
I am using a ModelMultipleChoiceField in a form within an UpdateView. I want to display the standard SelectMultiple widget but to clear all the initial selected attributes on the instance option values. By default SelectMultiple will select all the existing values; I want to clear this. I thought I could do this via the widget attrs but I am mistaken: form.fields['people'] = forms.ModelMultipleChoiceField( queryset=Person.objects.all(), to_field_name='email', widget=forms.SelectMultiple(attrs={'selected': None}) ) Is this possible?