Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
I am trying to filter ascending, descending, old price promotional-price to be shown in the public page
if request.GET.get("sort", False): category_products = category_products.filter(old_price=request.GET.get("sort")) -
Django REST how to get output of multiple nested object serializer
Im trying to create an api for a quiz app. I`m working with the Django rest framework to create this API. However, Im stuck with creating a good view for the API. Im not really getting the response I want I tried multiple things but I can't figure it out. The app has videos with questions. The questions have multiple answers, and videos have multiple questions. VideoQuestions model is created for adding the id of the video for the questions. Questions model is created for making questions Question_answers is created for making answers to the questions. The admin side looks like this: The problem: I want to achieve a JSON response that looks like the admin (see image above && what json response I want below). Im not that good with creating an API and working with django rest framework. The response I get now is also shown below. Models.py class VideoQuestions(models.Model): """ Categorize questions per video """ video = models.ForeignKey(Video, on_delete=models.CASCADE) created = models.DateTimeField() class Meta: verbose_name_plural = "E-learner questions" class Questions(models.Model): """ Questions class for the e-learner overlay """ video = models.ForeignKey(VideoQuestions, on_delete=models.CASCADE) question_text= models.CharField(max_length=65) class Meta: verbose_name_plural = "Questions" class Question_answers(models.Model): """ Answers for respected questions """ … -
502 Bad Gateway with nginx
We are using nginx for django application. by this application we can select set of devices to execute some actions like service restart. when we start using this application in more than 4 tabs(execute in 4 list of devices in same time), we are getting "502 Bad Gateway with nginx" randomly. Looking to find a way to increase the capacity of requests in order to allow multiple access in same time. -
how to extract this stores data and store into the js file
i'm getting this error while working with django channels tutorial project F:\djangoprojects\chatproject\mychat>docker run -p 6379:6379 -d redis:5 docker: Error response from daemon: failed to start service utility VM (createreadwrite): hcsshim::CreateComputeSystem 9eb1deb8fc69ee2656d9e049530b329c0fa8ca44a1f6523e9d5a27768fbedb62_svm: The virtual machine could not be started because a required feature is not installed. (extra info: {"SystemType":"container","Name":"9eb1deb8fc69ee2656d9e049530b329c0fa8ca44a1f6523e9d5a27768fbedb62_svm","Layers":null,"HvPartition":true,"HvRuntime":{"ImagePath":"C:\Program Files\Linux Containers","LinuxInitrdFile":"initrd.img","LinuxKernelFile":"kernel"},"ContainerType":"linux","TerminateOnLastHandleClosed":true}). -
Message Persistency with Django-channels and Rabbitmq?
I want to build chat server using django-channels with rabbitmq as channel-layer. And I want persist all messages for each group for archive purposes. Direct solution would be to save the message inside the Consumer of django-channels, but this might be slowing the overall performance because you are calling django ORM synchronously. A better solution I think is to create separate service that is responsible for the persistency. This service should subscribe and store all events pushed into rabbitmq. But to do so I have to know how django-channels integrate with rabbitmq? In other words: does django-channels create fanout exchange for each group? or it use topic exchange? or something else? -
How to add mobile collapsing navarro to django using materialize css?
I have some problems adding a navbar that collapses into a ‘hamburger bar’ at mobile devices and when a device is in split view. This is what I have done so far, the hamburger bar shows but when I click on it nothing happens, my code: <head> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> {% load static %} <link rel="shortcut icon" type="image/JPG" href="{% static 'images/favicon.ico' %}"/> <link href="{% static "tinymce/css/prism.css" %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> </head> <body> <div class="navbar-fixed"> <nav> <div class="nav-wrapper teal lighten-1"> <a href="#!" class="brand-logo"><i class="material-icons">assignment </i>Logo</a> <a href="#" data-target="mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a> <ul class="right hide-on-med-and-down"> <li><a href="/">Home</a></li> <li><a href="/newsroom">Newsroom</a></li> </ul> </div> </nav> </div> <ul class="sidenav" id="mobile"> <li><a href="/">Home</a></li> <li><a href="/newsroom">Newsroom</a></li> </ul> <script language="javascript"> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.sidenav'); var instances = M.Sidenav.init(elems, options); }); </script> <div> {% block content %} {% endblock %} </div> </body> <script src="{% static "tinymce/js/prism.js" %}"></script> I think the problem is about the javascript part, but I can’t solve it. Thanks from now! -
Django: Filter on a pk with ManyToManyField gives as many element as in m2m relation
I'm really confused with my Django Model. Models.py class Category(models.Model): id = models.CharField(max_length=100, primary_key=True) name = models.CharField(verbose_name="Category name", max_length=400, unique=False) slug = models.SlugField(max_length=151, unique=True, editable=False, null=True) def __str__(self): return self.id def save(self, *args, **kwargs): self.slug = slugify(self.name)[:50] + '-' + str(self.id) super(Category, self).save(*args, **kwargs) class Product(models.Model): objects = ProductManager() code = models.BigIntegerField( primary_key=True, unique=True) # TROUBLE SEEMS TO BE HERE... name = models.CharField(max_length=100, null=True, verbose_name="Nom") slug = models.SlugField(max_length=100, unique=True, blank=True, null=True) nutritionGrade = models.CharField( max_length=1, null=True, verbose_name="Nutriscore") image = models.URLField(null=True) category = models.ManyToManyField( # ...AND HERE Category, related_name="category", verbose_name="Catégorie") compared_to_category = models.ForeignKey( Category, on_delete=models.PROTECT, null=True ) Test_commands class TestDuplicates(TestCase): @patch('products.management.commands.init_db.requests.get') def test_init_nutella(self, mock_request): # replace json by a small mock openff request with only 3 product mock_request.return_value.json.return_value = NUTELLA call_command('init_db') self.assertEquals(len(list(Product.objects.filter(code=3017620422003))), 1) This test call the custom command init_db to populate my DB. In the mock NUTELLA product with code 3017620422003 has 7 categories in the ManyToManyField category. I get a AssertionError: 7 != 1 and I can't understand why since a filter on a primary_key should return a unique element. What am I doing wrong ? Other example in my real database here with 4 categories (event using distinct) : >>> Product.objects.get(code=8000500310427) <Product: Nutella biscuits> >>> Product.objects.filter(name__contains="Nutella biscuits") <QuerySet … -
Django: Retrieve pk for every object in ListView
I have a Dictionary view that shows the list of words created by a specific (special) user: class Dictionary(FilterView): model = Word template_name = 'vocab/dictionary.html' context_object_name = 'dict_list' paginate_by = 15 filterset_class = WordFilter strict = False def get_queryset(self): qs = self.model.objects.filter(user__username__iexact='special_user') return qs def get_object(self): queryset = qs pk = self.kwargs.get('pk') if pk is None: raise AttributeError('pk expected in url') return get_object_or_404(queryset, pk=pk) Now I want any user to be able to come to this page and add any word that they want to, like this: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 new_word, created = Word.objects.get_or_create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) Everything works as expected. But in the template I want the button to look different depending on whether the logged in user already has this word in their own list (which should be judged by if target_word is the same). My template looks like this: <tr> {% for word in dict_list %} <td>{{word.target_word}}</td> <td>{{word.source_word}}</td> <td> {% if user_word %} <a href="" class="btn btn-success btn-sm" >Added</a> … -
How to pass field value from one model object to another?
Oh my... It is kind of a basic question, but I tried many solutions, but nothing works for me and I cannot find the similar question to mine... I have two models: class ForQuery(models.Model): id=models.BigAutoField(primary_key=True) dep_sch = models.ForeignKey('DepDict', models.DO_NOTHING, db_column='dep_sch', blank=True, null=True) code_dep_sch = models.CharField(max_length=5, blank=True, null=True) class DepDict(models.Model): department = models.CharField(primary_key=True, max_length=35) code = models.CharField(max_length=5) I have all minimal meta for these Models incuding get_absolute_url and str . I have defined url for the function in view which I am using in the template. I am matching both models by department in DepDict and dep_sch in ForQuery and in the template, based on this match I can print easily the code for the dartment, like so: {% for d in c%} {% if forquery.dep_station == d %} {{ d.code }} {% endif %} {% endfor %} Now, based on this match, I cannot save referenced field code from DepDict to field code_dep_sch from ForQuery. How would I approach this task? My view function looks like this so far: class MetalDetailView(generic.DetailView): model=ForQuery def get_context_data(self, **qwargs): content = super(MetalDetailView, self).get_context_data(**qwargs) content['c'] = DepDict.objects.all() self.code_dep_sch = c.code #this didn't work self.save() return conObject Trying to using object.field_name doesn't work... Thank you for …