Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Django render JS on server side?
I know that Django has default config of SSR (server-side rendering) but all the articles I have gone through mention that the Django-forms are rendered on server side and then sent to the browser. No specific information on the use case when javascript is mixed in the template. I want to know if I use jquery tables in my Django template. Does that still render on server side? If yes then how does it render Javascript/jquery on the server-side? I'd be glad if someone corrects me if my question itself has invalid argument. -
Django how to filter table with dropdown menu?
I have created an app that collect all daily income. The model is the following: class Income(models.Model): date=models.DateField('', default="GG/MM/YYYY") income=models.DecimalField() I have created a simple template that contains the form and the data table with all data collected. <form method="post"> <div class="row"> h5>Income data collection</h5> <div class="row"> <div class="form-group col-2 0 mb-0" > {{form.income|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.date|as_crispy_field}} </div> </div> <table class="table" > <thead> <tr> <th>Income</th> <th>Date</th> </tr> </thead> <tbody> {% for inc in income%} <tr> <td>{{inc.income}}</td> <td>{{inc.date}}</td> </tr> {% endfor %} </tbody> </table> In the views I have added the following filter: income=Income.objects.filters(data__year='2020') At this point, I have created another model that set the reference year as the following: I have the following model class Timing(models.Model): reference_year=models.DecimalField(max_digits=4, decimal_places=0, default="2020") This model have a view with form that give to the client the possibility to register all reference year (2020, 2021 and so on). Now I want to link reference_year with income views.py. How? with a dropdown menu that cointains all reference_year filled. So for example if clients save in timing models a reference_year equal to 2020, in the dropdown the client could select it and the views dynamically update the filter. -
How do I create tag when creating post instance
I have Tag and Post models in many to many relationship. How do I create a tag instance or choose a tag already exist before when creating a post entity. Below is the class in my serializer file class PostSerializer(serializers.HyperlinkedModelSerializer): # display the category name category = serializers.SlugRelatedField(queryset=Category.objects.all(), slug_field='name') author = serializers.SlugRelatedField(queryset=Author.objects.all(), slug_field='username') tags = TagSerializer(many=True, read_only=True) class TagSerializer(serializers.HyperlinkedModelSerializer): posts = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name= 'post-detail' ) -
How to create a Trigram index in Django 3 with multiple columns
I've implemented Trigram Similarity search with annotate which gives me exactly what I want in terms of results; but I have 220,000 records in my database and the search takes 5+ seconds per query which is too long. The search is with 3 columns and one of those invokes a join. How do I add an index or the equivalent SearchVectorField but for Trigram to speed up my query? See current code below: trig_vector = (TrigramSimilarity('make__name', text) + TrigramSimilarity('model', text) + TrigramSimilarity('specification', text)) query_set = cls.objects.annotate(similarity=trig_vector).filter(similarity__gt=0.5).order_by('-similarity') I have tried making my own index from varous posts but I'm not too familiar with index's and each one I've implimente hasn't has an effect on the query time. -
Is there a way to upload large files to github
Please i am trying to upload my django aplplication to github so that i can deploy to heroku, but the files are very large so i am finding it difficult to upload. I used lfs but still after it start compressing the files objects, it get stucked at 99% and later on shows a fetal error. can someone help me out. i am really getting frustrated. I am using postgres as my database and in the files i have some video files that are about 400mb each in size. my static files to are about 300mb. this add to the above question, i also most often face this problem blog/templates/blog commit not checkout when trying to add the files. What might be the cause. -
when ever i am trying to start a project after i have installed django, execution displays No Module Found Error :django module or django.core
(.env) C:\Users\shara\Desktop\testfolder\_djhole>pip install Django (executed) (.env) C:\Users\shara\Desktop\testfolder\_djhole>django-admin start project my site (No Module Found Error). I have repeated this process for a long time. Cannot start working on Django so far due to this ModuleNotFoundError: No module named 'django.core'; 'Django' is not a package I have uninstalled it and reinstalled it several times. when I use pip freeze then asgiref==3.2.7 Django==3.0.7 pytz==2020.1 sqlparse==0.3.1 but still cannot start working on Django because the module is not found an error. By the way, there is only one python version 3.8.3 and added to the path. I hope that there would be some genius out there who could give me some answer because I have searched all over the internet for resolving this diabolical problem and got no company. -
How to work with multidimensional list in python
A multidimensional array is an array containing one or more arrays.This is a definition of multidimensional array in php and below is an example of multidimensional array [employee_experiences] => Array ( [0] => Array ( [company_name] => xyz [designation] => worker [job_description] => abc [started] => 2020-06-09T19:00:00.000Z [ended] => 2020-06-09T19:00:00.000Z ) [1] => Array ( [company_name] => zyz [designation] => worker [job_description] => def [started] => 2020-06-09T19:00:00.000Z [ended] => 2020-06-08T19:00:00.000Z ) ) My question is that how can I get this format in python and save it to the the database I know python can't handle array instead python use lists -
Is there a way to block self-following in Follow model?
My model structure looks like this: from django.db import models class Follow(models.Model): follower = models.ForeignKey('accounts.User', related_name='following', on_delete=models.CASCADE) user = models.ForeignKey('accounts.User', related_name='followers', on_delete=models.CASCADE) class Meta: unique_together = (('user', 'follower',),) def __str__(self): return f'{self.follower.username} follows {self.user.username}' I'm looking for something similar to "unique_together" but for the same user. I know there're possibilities to block it in API but I want it to do it from model level. -
Page not found in django on post request when upload a file
my django project is not working. when i save images getting page not found error and when i remove imageField it saves data successfully when i submit the form with image get this error when i submit the form with out image submitted succesfully -
Django dynamic views based on dropdwon option
I have a question for you. I have the following model class Timing(models.Model): reference_year=models.DecimalField(max_digits=4, decimal_places=0, default="2020") In my views.py I have created a filter as the following: income=Income.objects.filters(year='2020') Now I want to link reference_year with income views.py. How? with a dropdown menu that cointains all reference_year filled. So for example if clients save in timing models a reference_year equal to 2020, in the dropdown the client could select it and the views dynamically update the filter. is it possible to get it using django/jQuery? -
how to manage huge task for a huge number of users in django
I have a system developed in django where a lot of calculations have to be done for each user. The process takes almost 5 to 6 seconds for each user to complete the calculations. Currently I am using celery and rabbitmq to run the job as the number of user is limited now. The upcoming scenario is: 1. The number of users almost 100000 2. Have run the process at a certain time in each week for all users 3. Have to complete the total tasks for all the users in a few seconds I am using amazone aws server. can you please suggest me the archetectural scenario on this. -
How to get the URL of Django page to reload?
I know there are ways to get it in aspx and php, but cant find it for Django. I have an application (App1) and I load a page with a parameter (par1) with submit button from the database: this is the url of the method: ... path('load/', views.load, name='load'), ... html part: <form method="post" id="idForm" name="frm1" action = "/App1/save/#about" enctype="multipart/form-data"> .... <input type="submit" name="load" id="load" value="Load"/> I need something like: http://127.0.0.1:8000/App1/load/?par1=name1 to repeat the loading later, to send this link for other users. However it doesn't work, it loads some plain text/values. Can someone help me to do that? -
Django Update Field In Realtime & Validate
I'm presently creating a Django app where the user needs to input three required pieces of information: client, stage and purpose. These then combine to create a valid project name. What I need is a field that updates as the user types to give a preview of what the project name will be. Is this possible? I presently have: class ProjectForm(forms.Form): client = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Client Name (lowercase only)'}),validators=[RegexValidator(r'^[a-z]+$', 'Enter a valid client name (only lowercase letters)')]) stage = forms.ChoiceField(choices=TYPES) purpose = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Project Purpose (lowercase only)'}),validators=[RegexValidator(r'[a-z]+$', 'Enter a valid purpose (only lowercase letters)')]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Button('back', 'Back', css_class='button button--wide button--black', onclick="window.location.href = '{}';".format(reverse('home')))) self.helper.add_input(Submit('next', 'Next', css_class='button button--wide button--white')) self.helper.layout = Layout( Fieldset( 'Project Name', Row( Column('client', css_class='form-group col-md-4 mb-0'), Column('stage', css_class='form-group col-md-4 mb-0'), Column('purpose', css_class='form-group col-md-4 mb-0'), ) ) ) -
Django rest framework: Reject upload before parser
I have an upload API for my Django app specified with Django REST framework. from rest_framework import views class MyUploadView(views.APIView): permission_classes = ( CanUploadFilePermission, ) parser_classes = (parsers.FileUploadParser,) I noticed that the permissions are only checked after the file has already been uploaded/processed by the FileUploadParser. Unfortunately, I could not find any information in the Django REST framework of the execution stack for API calls. So I don't even know which parts (parser, permission, authentication etc) are executed in which order. Is it possible to reject a file upload before FileUploadParser even read the entire file into buffer? My goal is also to limit the file upload size depending on the user permissions and rejecting the request if the HTTP Content-Length header is larger than what is allowed for a certain user before the server even starts to write it into its buffer. -
Count the number of email campaigns clicked by a user within one query
What I intend to do is something like this: Clicks.objects.filter(campaign_id__in=[1,2,3]).distinct('campaign', 'subscriber').annotate(campaigns_clicked=Count('subscriber')) But django returns with the error: NotImplementedError: annotate() + distinct(fields) is not implemented. A subscriber can have multiple clicks for one campaign and one campaign can have clicks for multiple subscribers. Amongst the clicking subscribers, I want to know how many campaigns each subscriber clicked. Is there a workaround to get this result within one query? -
Django select_related() on a reverse OneToOneField results fails with ___
I have what I think is a fairly standard related model and queryset, that strangely is failing with: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: related_thing class MainThing(models.Model): pass class RelatedThing(models.Model): main = models.OneToOneField(MainThing, related_name="related_thing") MainThing.objects.select_related("related_thing") The error is coming from here: https://github.com/django/django/blob/master/django/db/models/sql/compiler.py#L803 Reading through the code, I'm not understanding how the reverse OneToOne field is supposed to be found. The lookup appears to use: opts = self.query.model._meta for f in opts.fields: field_model = f.model._meta.concrete_model fields_found.add(f.name) However the model's ._meta.fields will not include reverse one to one relationships: MainThing.related_thing # the relation exists <django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor at 0x10726aa90> MainThing._meta.fields # but doesn't appear in .fields (<django.db.models.fields.AutoField: id>) -
How To Tell Django Ive Overridden A Third Party App
Im wanting to add functionality to a Django-Notifications view. I guess the best way to do this is to override the class, add my custom logic, then pass the class to super: from notifications import AllNotificationsList class CustomAllNotificationsList(AllNotificationsList): def get_queryset(self): # my custom logic return super(CustomAllNotificationsList, self).get_queryset(self) I know of this guide for overriding Django Admin, but I cant find how to do this for other third party packages. My questions are: I dont know where to put this overridden class (in my project tree). I dont know how to tell Django that it has been overridden (settings.py?). Thank you. -
use instance in foreignkey
I have model products products class Product(models.Model): shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=True) Brand = models.CharField(max_length=200, blank=True) description = models.TextField(null=True, blank=True) when users insert a new product then the shop(user) is instance who has a login? and it is not editable -
Django Oscar customization, many product types after add AttributionGroup
I want to create custom product with set of custom attributes. In my attempts I used Oscar's documentation with some part of success. I created class BarrelProduct derived from Oscar's Product. from oscar.apps.catalogue.models import Product as CoreProduct class BarrelProduct(CoreProduct): barrel_type = AttributeOptionGroup.objects.create(name='BarrelType') AttributeOption.objects.create(group=barrel_type, option='M') AttributeOption.objects.create(group=barrel_type, option='P') klass = ProductClass.objects.create(name='foo', slug=uuid1) ProductAttribute.objects.create( product_class=klass, name='Type b', code='barrel_type', type='option', option_group=barrel_type) After that I run migrations and all seems worked but now in Oscar's admin Panel I have to choose one of several useless product types. List of product types looks like that: - barrel - foo - foo - foo - foo - foo - foo If I select the barrel product there is barrel's type union as was expected. -
How I can upload file in django?
I'm trying to upload file in a specific folder and store its path in DB through forms(CBV), but it doesn't work!! this is my code. I'm selecting the file through forms then I submit the form, but it doesn't submit. #views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post # fields = ['title', 'content'] success_url = reverse_lazy('blog/new_post.html') template_name = 'blog/new_post.html' form_class = PostCreateForm def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(self.success_url) else: return render(request, self.template_name, {'form': form}) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) #model.py class Post(models.Model): title = models.CharField(max_length=1000) content = models.TextField() xml_file = models.FileField(null=True, upload_to='xml_files') rate = models.FloatField(null=True, blank=True, default=None) post_date = models.DateTimeField(default=timezone.now) post_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): # return '/detail/{}'.format(self.pk) return reverse('detail', args=[self.pk]) class Meta: ordering = ('-post_date', ) #forms.py class PostCreateForm(forms.ModelForm): title = forms.CharField( max_length=1000) content = forms.CharField(widget=forms.Textarea( attrs={'rows': 15, 'placeholder': 'write here'} ), max_length=50000) xml_file = forms.FileField(label='upload file') class Meta: model = Post fields = ['title', 'content', 'xml_file', ] -
removing relative links from rss feed in python django
When creating the news, relative links were added to the text of the news itself by [link_name] (downloads/generic/2020.04.1/) When I load this text through the standard rss feed handler class BaseLatestNewsFeed(Feed): link = "/news/" def item_title(self, item): return item.title def item_description(self, item): return markdown_text(item.preview) and get item><title> ... </title><link>https://example.com/26/</link><description>&lt;p&gt;this is a link for download: &lt;a href="/downloads/generic/2020.04.1/"&gt; 2.6.0.13508&lt;/a&gt;&lt;/p&gt;</description> I know that in order to solve this problem, I can add an attribute xml:base="http://example.com/" to the description tag, but I don’t know how to do it in django. Or maybe there are other ways to solve the problem -
ModuleNotFoundError: No module named 'asyncio.streams'
i am working on a long project in Django and suddenly i faced this error: import asyncio File "C:\Users\AppData\Local\Programs\Python\Python38\lib\asyncio__init__.py", line 17, in from .streams import * ModuleNotFoundError: No module named 'asyncio.streams' please Tell me how can i fix it . I am Using Python 3.8.1 -
Creating User For Postgresql
When I enter su postgres it is asking for a password and I did not set any prior password. I am using a Django book and have installed PostgreSQL with sudo apt-get install PostgreSQL PostgreSQL-contrib I installed it within a virtual environment the instructions are vague on where to install so I just install it in there. Also installed the install the psycopg2 PostgreSQL adapter for Python with pip install psycopg2-binary==2.8.4. I am now in the next step to create a user for the PostgreSQL but can't pass that step the instructions provided are to enter su postgres and immediately after createuser -dp user-name and it is asking for a password. I have entered my superuser password but showing authentication failure. Thanks -
Filter by list django-graphene
i want to filter with a list. Right now when i run my query i get an empty list. I think that i'm filtering the list the wrong way in my resolver as i don't get any type errors. { articles(city: ["city1", "city2"]) { title } } Query class Query(graphene.ObjectType): articles = graphene.List(ArticleNode, args={'city': graphene.List(graphene.String)}) Resolver def resolve_articles(self, info, limit=None, offset=None, city=None): if city: filter = ( Q(title__icontains=city) | Q(owner__groups__name__icontains=city) ) return BlogPage.objects.filter(filter).order_by('-first_published_at')[offset:limit] Thank you -
django wizard form problem in showing multiforms
My Views Page: from django.shortcuts import render from django.http import HttpResponse from formtools.wizard.views import SessionWizardView from .forms import ContactForm1,ContactForm2,ContactForm3 class ContactWizard(SessionWizardView): template_name = 'contact.html' form_list = [ContactForm1,ContactForm2] def done(self, form_list, **kwargs): form_data = process_form_data(form_list) return render_to_response('done.html', {'form_data': form_data}) def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] return form_data My form page: from django import forms class ContactForm1(forms.Form):enter code here subject = forms.CharField(max_length=100) class ContactForm2(forms.Form): sender = forms.EmailField() class ContactForm3(forms.Form): message = forms.CharField(widget=forms.Textarea) I am new to Django I am working with the wizard forms but this wizard form not showing the if statement of the wizard multiform. Please help me to solve the wizard form. Html Page {% load i18n %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> {% for field in form %} {{field.error}} {% endfor %} <form action="/contact/" method="post"> {% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input type="submit" value="{% trans …