Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
como agrupar datos repetidos?
tengo esta consulta de django: detalleventa = DetalleVenta.objects.filter(venta_id__in=idventas).values('cantidad','producto__nombreProducto') print(list(detalleventa)) el cual me imprime esto: [{'cantidad': 6, 'producto__nombreProducto': 'Jose Cuervo'}, {'cantidad': 2, 'producto__nombreProducto': 'Absolut'}, {'cantidad': 7, 'producto__nombreProducto': 'Litro Tapa Roja'}, {'cantidad': 1, 'producto__nombreProducto': 'Litro Tapa Roja'}, {'cantidad': 2, 'producto__nombreProducto': 'Ron Medellín Garrafa'}, {'cantidad': 4, 'producto__nombreProducto': 'Aguila ligth'}, {'cantidad': 1, 'producto__nombreProducto': 'Aguila ligth'}] quiero que aguila light no salgan 2 con distinta cantidad, sino algo como esto: ..... {'cantidad': 2, 'producto__nombreProducto': 'Ron Medellín Garrafa'}, {'cantidad': 5, 'producto__nombreProducto': 'Aguila ligth'}, como puedo lograrlo? -
How does Django detect locale to make translation work
I don't quite understand how Django detect the local machine's locale. I have made the translation works if I explicitly set the language code. But how does it make translation base on locale and how to test it. -
Error while passing value with url to django view
Error while passing value to view from template using url Error : Error during template rendering In template D:\TONO\DJANGO_TASK\user_auth\templates\auth_app\other-user-listing.html, error at line 114 Reverse for 'add_to_group' with arguments '(name: Administrator,)' not found. 1 pattern(s) tried: ['auth_app\\/<str:username>/'] This my urls.py url(r'^<str:username>/', views.add_to_group, name="add_to_group"), This is the call from template <a href="{% url 'add_to_group' username %}"><i class="icon-plus">Add</i> </a> -
How to post the every step data of a wizard in the database using django?
I am having the 4 html pages in templates and those html pages will be having the next and previous steps now what I am trying to do is after clicking the every next the data is to be stored and after final submit the overall data should be dumped into the database.How can we achieve this in django? please illustrate with an example if possible? Thanks in advance The steps will be as in the link given here https://www.modsy.com/project/room -
how to access request object inside Django Form
I need to access the request object inside Django Form, to name the form fields dynamically as it looks like into the code below. The request object is currently returning None. How can i have request object inside form? class PartitionAdminForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) request = kwargs.get('user', None) term_partition = core_utils.get_system_terms(request).get("partition") if self.fields.get('username'): self.fields['username'].label = _(f"{term_partition} Super Admin Username") self.fields['username'].help_text = "" -
Is there any resource for learning django?
I am new to django. I want to build an online pharmacy stock management system with e-commerce. but I'm new to django. it's getting hard for me. is there any ways to learn django. or any help. I have no idea about this guys. -
AWS Cognito Boto3 Error on Confirm Device: Invalid device key given
I have been creating a AWS Cognito flow with Python, Django and Boto3 with MFA enables. My authentication flow is the following: initiate_auth: called on an django rest endpoint response = client.initiate_auth( ClientId=settings.AWS_COGNITO_CLIENT_ID, AuthFlow='USER_PASSWORD_AUTH', AuthParameters={ 'USERNAME': email, 'SECRET_HASH': get_secret_hash(email), 'PASSWORD': password, } ) if "ChallengeName" in response: data["mfa"] = True data["session"] = response["Session"] respond_to_auth_challenge: called on a seperate django rest endpoint response = client.respond_to_auth_challenge( ClientId=settings.AWS_COGNITO_CLIENT_ID, ChallengeName='SMS_MFA', Session=session, ChallengeResponses={ 'USERNAME': email, 'SMS_MFA_CODE': code, 'SECRET_HASH': get_secret_hash(email), } ) based on this post I wanted to implement the confirm device so MFA is skipped upon next login. So after the respond to auth challenge I have this code: device_key = response['AuthenticationResult']['NewDeviceMetadata']['DeviceKey'] device_group_key = response['AuthenticationResult']['NewDeviceMetadata']['DeviceGroupKey'] device_password, device_secret_verifier_config = generate_hash_device(device_group_key, device_key) device = client.confirm_device( AccessToken=response["AuthenticationResult"]["AccessToken"], DeviceKey=device_key, DeviceSecretVerifierConfig=device_secret_verifier_config, DeviceName=email ) But I always get the Unknown error An error occurred (InvalidParameterException) when calling the ConfirmDevice operation: Invalid device key given. Can anyone help on why this happens? -
Django views function skip urls keywords
#1. path('<str:lang>/request/', views.request.get_request), #2. LangMiddleware #3. views.py ---> def get_request(request): <--- I don't want to put 'lang' param I have a lang keyword in urls, this keyword only use inside of LangMiddleware It don't need it inside of views, therefor I don't want to put keyword in every function. anyone know how to solve this? -
Advice on how to handle PostgreSQL database in Django app?
For some background, I worked on a Django app that had a SQLite3 database. I just created models in Django using the python manage.py startapp model_name, and just directly manipulated the database by creating API endpoints in python. I would then make API requests and change my database like that. But this time, I've created a Django app that has a PostgreSQL database. I managed to connect my database to Django after figuring out how to install psycopg2. Then, I created a Users table in PostgreSQL through the command line. I want to get this table to show on my Django admin site, and hopefully repeat the same method for the other app. But the Django admin site can render only Django models that have been registered to the admin. So now, I'm wondering if there is a better method for working with PostgreSQL in Django. I saw SO posts suggesting inspectdb, but this creates a large models.py file generating other classes for my app. I also couldn't successfully register the Users model to the Django admin site. I am now curious if I am working in the opposite direction. Should I be generating User models in Django and then … -
session management (Angular and Django)
I am using django rest framework and angular, practicing with this I was logging in, but I had doubts about how active sessions are handled, I have no idea how to do it but the concept, I have seen that several use a token (djangorestframework-jwt) but I do not quite understand it, what I want to do is that when you log in the records are created they carry the user's id -
what framework/language should I use to build a contact us website
a relative of mine wants me to build a contact us website for his business. I just finished systems engineering first year and have no experience with web development. I understand that this is an easy task as there is no database managment or things like that. I have played around with django and javascript but I'm not sure what kind of technologies are the best for this cases. Is django a good choice? or is the task too simple to use django? What should I use? The website should have an admin mode in which my relative can easily add and change information whenever he wants. Thanks, any suggestion as to what frameworks or languages to use for backend and frontend will be appreciatted. -
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 …