Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript adding zero
How to add additional zero at the end of Number for example: if the user choose "0" in the Precision it will show like this (Lower Limit) if "1" if "2" I dont have javasccript code yet cause i dont know how to do it, please help. -
Django: allow creating only one instance of a model?
Is it possible to allow the admin to only create a maximum of one instance of a model, and no more? My model: class HomePageDetail(models.Model): main_image = models.ImageField(upload_to='index_images', default='..\..\static\images\random_pizza.jpg', blank=False) on_sale_pizza_1 = models.ImageField(upload_to='index_images', default='..\..\static\images\random_pizza.jpg', blank=False) on_sale_pizza_2 = models.ImageField(upload_to='index_images', default='..\..\static\images\random_pizza.jpg', blank=False) recommended_pizza_1 = models.ImageField(upload_to='index_images', default='..\..\static\images\random_pizza.jpg', blank=False) recommended_pizza_2 = models.ImageField(upload_to='index_images', default='..\..\static\images\random_pizza.jpg', blank=False) class Meta: pass def __str__(self): return str(self.pk) def get_absolute_url(self): return reverse("PizzaDeliverySystem_HomePageDetail_detail", args=(self.pk,)) def get_update_url(self): return reverse("PizzaDeliverySystem_HomePageDetail_update", args=(self.pk,)) -
Having problems getting mp4 file in my django app?
Views.py from django.views.generic import TemplateView class salespage(TemplateView): template_name = "salespage.html" page.html video width="420" height="340" autoplay source src="{% static 'img/story.mp4' %}" type="video/mp4" Your browser does not support the video tag. video -
How to troubleshoot ImageField not uploading?
I have a model which is not uploading Images/Videos for some reason and have tried everything I know how to troubleshoot it. This model that is not uploading files is: class TF_Question(Question): correct = models.BooleanField( blank=False, default=False) This one has the same sub-class but works for uploading files: class MCQuestion(Question): answer_order = models.CharField( max_length=30, null=True, blank=True) This is the parent class: class Question(models.Model): quiz = models.ManyToManyField( Quiz, verbose_name=_("Quiz"), blank=True) figure = models.ImageField( upload_to='testing/images/', blank=True, null=True, verbose_name=_("Optional Image")) video = models.FileField( upload_to='testing/videos/', blank=True, null=True, verbose_name=_("Optional Video")) This is the form: class TFQuestionForm(forms.ModelForm): class Meta: model = TF_Question fields = [ 'content', 'correct', 'explanation', 'figure', 'video', 'category', ] quiz = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super(TFQuestionForm, self).__init__(*args, **kwargs) self.fields['quiz'].queryset = Quiz.objects.all() And the view.. class TFQuestionCreateView(PermissionRequiredMixin, LoginRequiredMixin, CreateView): form_class = TFQuestionForm template_name = 'quiz/tf_create.html' success_url = reverse_lazy('quiz_index') permission_required = 'quiz.add_quiz' permission_denied_message = 'User does not have permissions to create questions.' The only thing that I know that has changed has been the way I used an inline formset factory on the MC_Question and then some stuff to get it to work with Bootstrap4: class MCQuestionForm(forms.ModelForm): class Meta: model = MCQuestion exclude = () quiz = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.CheckboxSelectMultiple) … -
Can't figure out why Django isn't adding table data from Views to Models
I am using an HTML page in Django's views as well as other functions in views to take data from form fields in the HTML page and send them to one of the Models databases through Django. This is all done off of localhost. I'm basing what I'm doing off of this solution. When I hardcode an entry and send it from views to models, there isn't an issue. When I try to take data from the HTML field and then send it, I get a code 200, but logging into the admin panel and trying to access the database causes the localhost server to crash. Below is my code: Views Functions for getting and sending table entry to Models def addCharacter(sUserID, sPlayerName, sRace, sPlayerClass, sStr, sCon, sDex, sInt, sWis, sCha): from pathfinder.models import characterTable c = characterTable(userID = sUserID, playerName = sPlayerName, race = sRace, playerClass = sPlayerClass, strength = sStr, constitution = sCon, dexterity = sDex, intelligence = sInt, wisdom = sWis, charisma = sCha) c.save() #this function courtesy of Mahshid Zeinaly on stackoverflow https://stackoverflow.com/a/19761466/12352379 def request_page(request): if(request.GET.get('mybtn')): userID = 'testUser' addCharacter(userID, string(request.GET.get('characterName')), string(request.GET.get('race')), string(request.GET.get('class')), string(request.GET.get('characterName')), string(request.GET.get('strength')), string(request.GET.get('dexterity')), string(request.GET.get('constitution')), string(request.GET.get('intelligence')), string(request.GET.get('wisdom')), string(request.GET.get('charisma'))) HTML in Views: def characterCreator(request): html … -
Django request.user when using django as an api
Originally I had a django application set up where the html was being served by django. The frontend would make a few fetch requests to the django app and update as needed. I would update the logged in user using request.user in the django views. However, I recently attempted to separate the frontend and backend entirely, using an express server with hmr to serve the frontend and only using django as an api. I'm not sure how to keep track of logged in users using this set up however, nor do I know how to keep csrf working correctly. Are there any standard ways of accomplishing this? -
How do you change the all uppercase Django Admin inline names to proper title case?
In the Django Admin portal if you collapse fieldsets the name and the show link are in proper/title case, but when you collapse inline they are in all uppercase. See screenshots below where the 'Date Information (Show)' is not in all uppercase, but the 'CHOICES (SHOW)' is. I would just like them to both look the same and not sure how to accomplish that. I already tried using a class of 'lowercase', but that didn't change the inline format. -
|as_crispy_field got passed an invalid or inexistent field
i've a error in my view django (|as_crispy_field got passed an invalid or inexistent field), becose tell me the error here. i don't understand. This is my code: views.py my_form = AlumnoForm() my_form2 = ApoderadoForm() if request.method == "POST": my_form = AlumnoForm(request.POST) and ApoderadoForm(request.POST) if my_form.is_valid() and my_form2.is_valid(): print(my_form.cleaned_data) print(my_form2.cleaned_data) Alumno.objects.create(**my_form.cleaned_data) Apoderado.objects.create(**my_form2.cleaned_data) return redirect('list_student') else: print(my_form.errors) print(my_form2.errors) extra_context = { 'form' : my_form, 'form2': my_form2 } return render(request, "create_student.html", extra_context) ``` -
Use a `ImageSpecField()` from the original file of a `ProcessedImageField()`
I'm creating a Django model for which I need to generate two resized images from one original source (e.g. that the user provides in the admin panel). I use django-imagekit for this, and I came with this class Event(models.Model): title = models.CharField(max_length=128) image = ProcessedImageField( upload_to='partners/', processors=[ResizeToFit(width=300, height=300)]) thumbnail = ImageSpecField( source='image', processors=[SmartResize(width=80, height=80)]) The problem here is that thumbnail uses the already-processed image file to create the new thumbnail version, resulting in a poor quality. Do you know a way to do this, without actually adding an ImageField() property -- that is, without saving the original full-format image? Thanks! -
django postgresql - CASE types interval and integer cannot be matched
In Django I'm creating a queryset with CASE and annotation. It looks like this: days_diff_calc = Case( When(Q(sent_date__isnull=True), then=None), When(Q(received_date__isnull=True), then=(timezone.now().date() - F('sent_date'))), default=(F('received_date') - F('sent_date')), output_field=DurationField() ) Item.objects.all().annotate( days_diff=days_diff_calc ) The important part of the query it creates looks something like this: CASE WHEN "item"."sent_date" IS NULL THEN NULL WHEN "item"."received_date" IS NULL THEN ('2019-11-26' - "item"."sent_date") ELSE (interval '1 day'* ("item"."received_date" - "item"."sent_date")) END AS "days_diff" When running it in Postgres I get this error: CASE types interval and integer cannot be matched LINE 3: ...item"."received_date" IS NULL THEN ('2019-11-2... ^ It seems like for some reason, Django ORM adds the interval 1 day * after the ELSE, but doesn't do it after the second WHEN and I think that's the reason for this error. I don't understand - why does it add it only to one place and not to the other, and if I would want to add it to the other place (second WHEN) - I would I do it? -
Call Object in model.py class
Im trying to get objects in two different class My admin.py from django.contrib import admin from clients.models import Compagnie, Personne, Trunk, Info from django.utils.html import mark_safe class PersonInline(admin.TabularInline): model = Personne @admin.register(Compagnie) class ClientsAdmin(admin.ModelAdmin): list_display = ('name', 'server_ip', 'management_link',) inlines_person = [PersonInline] and my model.py from django.db import models class Compagnie(models.Model): name = models.CharField("Nom de l'entreprise", max_length=200, blank=True, null=True) management_link = link class Meta: verbose_name_plural = 'Compagnies' class Personne(models.Model): compagnie = models.ForeignKey(Compagnie, on_delete=models.CASCADE) nom_complet = models.CharField("Nom complet",max_length=200, blank=True, null=True) class Meta: verbose_name_plural = 'Personnes-Ressources' class Info(models.Model): compagnie = models.ForeignKey(Compagnie, on_delete=models.CASCADE) management = models.URLField("Management link", max_length=128, db_index=True, unique=True, blank=True) class Meta: verbose_name_plural = 'Informations' So i would like to be able to get the 'management' in models.py object to appear in my admin.py where is 'management_link' And, I'ved tested MANY things to make ''management'' redirect to outside url. exemple: management = models.URLField("Management link", max_length=128, db_index=True, unique=True, blank=True) The user input : www.google.com so when im in the 'admin/' interface (admin.Model) where is management_link, we can click on it and it opens a new page going to the value that user gived im, so www.google.com Thanks to everyones that will try to help! -
Django: how should I implement changing an image of a html page in template from the admin panel as an admin?
So let's assume there is an image on the index page. How should I implement the possibility of changing this image to another image, from the Django admin panel, as an admin? -
pip install locustio ==0.8a2 is not installing?
I got an issue on 'core' module in not find in django project. To overcome from this problem, i got to know that i have to install 'locustio ==0.8a2' so i type in windowshell pip install locustio ==0.8a2 but it is not installing. And here is the initial problem(django): return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Papul\Desktop\sandeep\myproject\myproject\urls.py", line 6, in <module> from core.views import SignUpView ModuleNotFoundError: No module named 'core' here is the snapshot: https://i.stack.imgur.com/00tGl.png -
Is there a solution to this injection template tagging problem?
After learning about how Django operates what is known as Models-Templates-Views, my goal was to learn how to connect everything. So in order to practice the method of connecting everything I have started with generating a table. The table will display all the webpages and access records from the AccessRecord database which I created and populated it using the "Faker" library. In order to connect the model to the html page I have also used template tagging. The process was like this: In first_app directory, views.py file I imported the models: from first_app.models import Topic,Webpage,AccessRecord And then I used render to grab stuff from the model itself and use template tagging later to inject it into the html. Now in the templates/first_app directory index.html file I have added the {% load staticfiles %} tag and then added the link to the css file which href is an injection with template tagging <link rel="stylesheet" href="{% static "css/mystyle.css" %}"/> Now this is where the problem starts Since I am working in VS Code it highlights the /mystyle.css" in red and after %} it highlights also this part in red "/> After adding the div class in html,template tagging,table and table rows everything … -
Create an installable program from a django app and venv
Is it possible to create an installable windows program from a django app and python venv? If so could somebody point me the right direction of what to do? Thanks! -
'CustomerForm' object has no attribute 'get'
I have been trying to submit login information to a database in Django using a form bu keep getting an error that I have tried to fix. found similar answers here but didn't work for me. Can someone please help me urls.py from django.contrib import admin from django.urls import path #from customers.views import home_view #from customers.views import design_view from customers.views import CustomerForm urlpatterns = [ #path('',home_view,name='home'), path('for/',CustomerForm,name='form'), #path('design/',design_view,name='design'), path('admin/', admin.site.urls), ] template/design.html <h1>THIS IS ABOUT MY NAME</h1> <form>{% csrf_token %} {{ form.as_p }} <input type="submit" name="" value="save"> </form> forms.py from django import forms from .models import Login class CustomerForm(forms.ModelForm): class Meta: model = Login fields=['email','password'] views.py from django import forms from .models import Login class CustomerForm(forms.ModelForm): class Meta: model = Login fields=['email','password'] models.py from django.db import models # Create your models here. class Login(models.Model): email=models.EmailField(max_length=30) password=models.CharField(max_length=30) errorcode Internal Server Error: /for/ Traceback (most recent call last): File "C:\Users\Henry R\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Henry R\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "C:\Users\Henry R\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'CustomerForm' object has no attribute 'get' [27/Nov/2019 01:09:29] "GET /for/ HTTP/1.1" 500 58312 -
Django not supporting GET method JSON body?
this: curl "http://localhost:8000/v1/post" \ -H 'Content-Type: application/json' \ -H 'Accept-Encoding: gzip' \ -d $'{ "url": "/my-test-url" }' with this: class PostView(APIView): permission_classes = ([AllowAny]) throttle_scope = 'public_get' @method_decorator(cache_page(API_CACHE_TTL_PUBLIC_GET)) def get(self, request, format=None): print(request.data['url']) result = {} return Response(result) crashes on the print line... KeyError: 'url' However, changing the GET into a POST: curl -X "POST" "http://localhost:8000/v1/post" \ -H 'Content-Type: application/json' \ -H 'Accept-Encoding: gzip' \ -d $'{ "url": "/my-test-url" }' class PostView(APIView): permission_classes = ([AllowAny]) throttle_scope = 'public_get' @method_decorator(cache_page(API_CACHE_TTL_PUBLIC_GET)) def post(self, request, format=None): print(request.data['url']) result = {} return Response(result) will print it fine. This causes me to believe either Django can't handle GET request body payload and that I must use URL parameters instead with GET --- or that I'm missing something. What am I doing wrong here? -
FullCalendar Events do not refresh after Ajax adds a new event
I am using FullCalendar in Django app. A Django form is used to collect data and add create an event, using an Ajax call to the view. When I create a new event, I successfully add the event. The problem is when I add the event I have to reload the page manually to see the new event in the calendar - which is defeating the purpose of using Ajax! Below is the part of the script that handles the form success I use, can some please point me in the right direction? function handleFormSuccess(data, textStatus, jqXHR){ $myForm[0].reset(); // reset form data $('#addEventModal').modal('hide') var event_arr = $.parseJSON(data); $('#calendar').fullCalendar('removeEvents'); $('#calendar').fullCalendar('addEventSource', event_arr); $('#calendar').fullCalendar('rerenderEvents' ); } -
Django user permissions on variable data
Ran into a problem that has me scratching my head, documentation hasn't really pulled me any luck so I figured I'd see if anyone else has been in this situation. So let's say I have a model (among others): Organization That sort of acts like a psuedo-tenant. The thing is, users within my app may or may not have permissions to multiple organizations, some only 1, some this, some that. Point is, there's no clear structure on where permissions lay for each user. By default it should be none as it is now until manually granting, but instead of granting permissions to all organizations has anyone ran into a similar situation of being able to control permissions in a granular fashion? It is important to note that these 'organizations' are loaded dynamically via an API to an external product. I realize this can be done by crafting my own sort of permissions system outside of Django but my main question is can this be done with conventional Django permissions or is this out of scope? Thanks -
Django rest framework serializer ignores extra_kwargs or custom attribute
I am trying to make an api which is slightly different for the client and the main user. So I want to add the client later if the role is client. class StoreSerializer(serializers.ModelSerializer): class Meta: model = models.Store fields = ["id", "name", "location", "location_lat", "location_lng", "client"] def create(self, validated_data): user = self.context["request"].user if user.role == Roles.CLIENT.name: validated_data["client"] = user.client The dumbed down model lookst like this class Store(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) When I now call the serializer with the user that has the role client I get this response: {"client":["This field is required."]} Which is correct. But the weird thing happens we I add extra_kwargs to the StoreSerializer. If I change the serializer to: class StoreSerializer(serializers.ModelSerializer): class Meta: model = models.Store extra_kwargs = { "client": { "required": False } } ... Or change it to class StoreSerializer(serializers.ModelSerializer): client = serializers.UUIDField(required=False) .... I get the same response. How can this be? Client should not be required right? -
JS code not working on all data retrieved from Django Model
I'm retrieving an endDate field from Django model using forloop on HTML page. I want to check whether all the endDate coming are less that today's date or not. For that I'm using JS code. My code is able to perform checking only on first date retrieved but it's not working on other dates. Here's my HTML code for retrieving data: {% for p in object_list %} <h4>{{ p.jobName }}</h4> <p><b style="color: red">Expires On: </b><b>{{ p.endDate }}</b></p> <a href="{{ p.get_absolute_url }}" target="_blank">View info</a> <input type="hidden" id="endDate" name="variable" value="{{ p.endDate }}"> <span id="check"></span> {% endfor %} JavaScript code to check date: <script type="text/javascript"> var endDate = document.getElementById("endDate").value; var ToDate = new Date(); if(new Date(endDate).getTime()<=ToDate.getTime()){ document.getElementById("check").innerHTML = "Expired"; document.getElementById("check").className = "label danger"; } else{ document.getElementById("check").innerHTML = "Active"; document.getElementById("check").className = "label success"; } </script> I have 2 {{ p.jobName }} right now. First one should show Expired while second should show Active. My code is working only for first date i.e., for Computer Admin only. Here's what I'm getting the output: Can anybody tell me what's the issue? Thanks -
unable to unpack list of dictionary in django
I have as list of object as below : this_json_reponse = ['{"queskey": 1, "ques": "test question 1", "ans": "test ans 1"}', '{"queskey": 2, "ques": "test question 2", "ans": "test ans 2"}', '{"queskey": 5, "ques": "bfxgrdytreyt4etgest4", "ans": "3353tet4"}', '{"queskey": 6, "ques": "tet4w64t", "ans": "f464etrtd"}', '{"queskey": 7, "ques": "fdszf3r3647", "ans": "gry5757"}'] I will be receiving this from another api call. I need to simply list all the queskey and ques present : 1 : test question 1 2 : test question 2 ... I tried unpacking this with nested loop as below : <ul> {% for this_item in this_json_reponse %} <li>{{ this_item }}</li> {% for a,b in this_item.items %} <li>{{ a }}</li> {% endfor %} {% endfor %} </ul> sadly I'm unable to do so after long hit/trial. -
Form data not saving data to database - Django
I can't save form data to the database, everytime I try, I get a different error. Here's my form model class Meta: model = Asistente exclude = ('evento',) widgets = {'nombre': forms.TextInput(attrs={'class': 'form-control'}), 'telefono': forms.TextInput(attrs={'class': 'form-control'}), 'num_asistentes': forms.TextInput(attrs={'class': 'form-control'})} Here's the code to my view. def post(self, request, evento_id): evento = Evento.objects.filter(id=evento_id).first() form = RegistroAsistenteForm(request.POST) if form.is_valid(): registro_asistente = form.save(commit=False) registro_asistente.evento.pk = evento_id registro_asistente.save() else: form = RegistroAsistenteForm() return HttpResponseRedirect('/evento-reg/' + str(evento_id) + '/asistente/')``` There are times when I don't get any error, it just don't do anything. -
How to the name that matches the ID without refreshing/submitting the form in Django?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. My page currently loads, but there is never a call to the function/url that searches for the name to display it on the page (because there isn't one). I'm not sure where I might be missing the part that connects these two areas of the code or how to connect these, … -
How can I get images from RSS feed?
I'm trying to implement this code: https://github.com/ahernp/django-feedreader How would I retrieve also the images from the RSS feed?