Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango ORM double join with Sum
I searched for a similar case on SO and Google with no luck. SHORT EXPLANATION I have transactions that belong to an account, and an account belongs to an account aggrupation. I want to get a list of accounts aggrupations, with their accounts, and I want to know the total balance of each account (an account balance is calculated by adding all its transactions amount). LONG EXPLANATION I have the following models (I include mixins for the sake of completeness): class UniqueNameMixin(models.Model): class Meta: abstract = True name = models.CharField(verbose_name=_('name'), max_length=100, unique=True) def __str__(self): return self.name class PercentageMixin(UniqueNameMixin): class Meta: abstract = True _validators = [MinValueValidator(0), MaxValueValidator(100)] current_percentage = models.DecimalField(max_digits=5, decimal_places=2, validators=_validators, null=True, blank=True) ideal_percentage = models.DecimalField(max_digits=5, decimal_places=2, validators=_validators, null=True, blank=True) class AccountsAggrupation(PercentageMixin): pass class Account(PercentageMixin): aggrupation = models.ForeignKey(AccountsAggrupation, models.PROTECT) class Transaction(models.Model): date = models.DateField() concept = models.ForeignKey(Concept, models.PROTECT, blank=True, null=True) amount = models.DecimalField(max_digits=10, decimal_places=2) account = models.ForeignKey(Account, models.PROTECT) detail = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return '{} - {} - {} - {}'.format(self.date, self.concept, self.amount, self.account) I want to be able to do this in Django ORM: select ca.*, ca2.*, sum(ct.amount) from core_accountsaggrupation ca join core_account ca2 on ca2.aggrupation_id = ca.id join core_transaction ct on ct.account_id = ca2.id group … -
Django Model Custom Field Problems
I've been trying to get this done for days but still can't see where the error is. At the moment I'm using the generic CreateView in views.py for form processing. The particular text field in question is supposed to take a string in the format of "HH:mm" or ":mm" (or 0), convert it to minutes and store in the DB as an integer. For some reason the form.errors still says this must be an integer. Obviously initially it is a string, but should be an integer by the time it gets to saving. Custom Model Field in models.py class FlightTimeFieldInt(models.IntegerField): description = "a field to input flying time" def get_db_prep_value(self, value, *args, **kwargs): if value is None: return None return value def to_python(self, value): if value is None or isinstance(value, int): return value if str(value.split(":")[0]) == '': split = value.split(":")[1] value = int(split) print(value) return int(value) else: h, m = value.split(":") value = (int(h) * 60) + int(m) return value def from_db_value(self, value, expression, connection, context): return self.to_python(value) def formfield(self, **kwargs): defaults = {'form_class': None} defaults.update(kwargs) return super(FlightTimeFieldInt, self).formfield(**defaults) There could be a better way but not sure how to go about it. Thanks for your help! -
Is there a way to dynamically create django models(classes)?
I have been assigned a challenging task recently, we are designing a website for our customers, and my boss wanted me to create flexible model-creation functions: which means he doesn't want us to "hard code" the models, he told us not to manually define django models but to create them at system runtime. For example, we have no models related to our business process at first, admin users can define a form's format on our front pages which will be processed by general users later. Then our backend receives the request from front-end and create the form model with fields provided. I found I can create a class by type() function like type(class_name, (models.Model,), attrs), and I did get new class via this function. But I was wondering how to persist this class in our system? Like saving this new class into my models.py and making migration so that our DB has it as well -
NOT NULL constraint failed Django
I want to save Department model forms with Model Direccion values, using foreign key in Department, but I have this error. Models.py class Direccion(models.Model): calle = models.CharField(max_length=50) numero = models.CharField(max_length=6) #comuna = models.ForeignKey(Comuna, on_delete=models.CASCADE) class Departamento(models.Model): n_habitaciones = models.IntegerField(max_length=1) n_banios = models.IntegerField(max_length=1) n_depto = models.CharField(max_length=5) descripcion = models.CharField(max_length=500) precio = models.IntegerField(max_length=10) img1 = models.ImageField(upload_to='Departamentos/') img2 = models.ImageField(upload_to='Departamentos/') img3 = models.ImageField(upload_to='Departamentos/') img4 = models.ImageField(upload_to='Departamentos/') img5 = models.ImageField(upload_to='Departamentos/') direccion = models.ForeignKey(Direccion, on_delete=models.CASCADE) Forms.py class DeptosForms(forms.ModelForm): descripcion = forms.CharField(max_length=1000, widget=forms.Textarea) img1 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) img2 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) img3 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) img4 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) img5 = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'type':'file'})) calle = forms.CharField(max_length=50) numero = forms.CharField(max_length=6) class Meta: model = Departamento fields = ('n_habitaciones', 'n_banios', 'n_depto', 'precio', 'descripcion', 'img1', 'img2', 'img3', 'img4', 'img5', 'calle', 'numero', ) Views.py def AddDepto(request): if request.method == 'POST': form = DeptosForms(request.POST, request.FILES) if form.is_valid(): depto = form.save() depto.save() messages.success(request, 'Departamnto registrado correctamente') return redirect('show_deptos') else: form = DeptosForms() return render(request, 'core/add_dptos.html', {'form': form}) Error: enter image description here -
Django 3 - Passed variable in views.py not accessible in web form like other vars
Newbie to Django here - I have a list of DB entries that I want to be able to cycle through one at a time and currently I am working on loading the first object by its ID. The form renders fine, but other vars aren't accessible as expected - am I missing something in the code? views.py def ticket_edit(request): updateform = TicketForm(request.POST) if request.method == 'POST': if updateform.is_valid(): ticket = Ticket.objects.update( ticketID=updateform.cleaned_data['ticketID'] ) ticket.save() return HttpResponseRedirect(".") else: print("FORM NOT YET VALID: Awaiting form.is_valid()") updateform = TicketForm() #--Get list of ticketIDs--------------- def ticketID_listGet(): tickets = Ticket.objects.all() ticketIDList = [] for ticket in tickets: aTicketID = ticket.appTicketID ticketIDList.append(aTicketID) return ticketIDList tList = ticketID_listGet() tFirst = str(tList[0]) print('TicketIDs: ', tList, tFirst) return render(request,'authentication/ticket-edit.html',{ "has_error": False, "updateform": updateform, "tFirst": tFirst }) ticket-edit.html <div class="container" style="border-style:none"> <form action="." method="POST" id="ticket-update-form" style="border-style:none"> {% csrf_token %} <div class="row"> <div class="col-md-12"> <div class="form-control" style="border-style:none"> {{ updateform.ticketID.label_tag }} {{ updateform.ticketID }} {{ tFirst }} </div> </div> </div> I am not getting errors when using {{ tFirst }}, it's just being ignored as if unrecognized. Ultimately I am trying to determine how to retrieve the existing ticketIDs and the first ticketID as vars and then cycle through them with … -
Create bulk permission retrieval for django user.has_perms to improve speed of the code
I have such a function that runs for multiple projects and users: def has_project_permissions(project, user, can_edit=False, is_owner=False): permission_level = CAN_VIEW if can_edit: permission_level = CAN_EDIT if is_owner: permission_level = IS_OWNER return user.has_perm(permission_level, project) or (user.is_staff and not project.disable_staff_access) Currently I am using for loop to iterate over each user and each project and get permissions. Is there a way to rewrite it and get all the permissions for all of the users and projects in Django? I need it to improve speed since when there are too many users and projects, obviously speed is going to be very bad. I would expect its possible in Django somehow. Here is the function in which I am iterating over projects. Iteration over users happens one level above (not included): def _get_json_for_user(projects, user): """Returns JSON representation of the given User object Args: user (object): Django user model Returns: dict: json object """ if hasattr(user, '_wrapped'): user = user._wrapped # Django request.user actually stores the Django User objects in a ._wrapped attribute user_json = {_to_camel_case(field): getattr(user, field) for field in ['username', 'email', 'first_name', 'last_name', 'last_login', 'is_staff', 'date_joined', 'id']} user_json['displayName'] = user.get_full_name() csi_user = True if user: if len(projects) == 0: csi_user = False else: … -
How to get id of clicked item Django
Hello i have a list of items in the cart but i would like to decrease, increase and delete items from the cart but I have no idea how to get "pk" of these items. Should i use update view if I do not want to use JS? views.py class CartView(TemplateView): template_name = "shop/cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = Cart.objects.annotate( price=Sum(F('orderitem__item__price') * F('orderitem__quantity')) ).get(order_user= self.request.user) cart = context['cart'] cart.total = cart.price cart.save() context['order_items'] = OrderItem.objects.filter(cart=cart) return context def post(self, request, pk): if 'minus' in request.POST: cart = Cart.objects.get(order_user=self.request.user) OrderItem.objects.filter(id=pk, cart=cart).update( quantity=F('quantity')-1) return HttpResponse("cart uptaded") -
Does it Make Sense to Dynamically Add EC2 Instance Private IPs to Django's CACHE LOCACTION Setting in an Elastic Beanstalk Environment with NGINX?
I'm using Elastic Beanstalk with load balancing and I've set a minimum number of instances to 2. So I have two instances with two different private IPs. What I'm trying to achieve is to add Memcached caching locations dynamically to Django's CACHES setting based on the EC2 instances that exist in an environment. My Primary Question Since Elastic Beanstalk uses NGINX (in my case), do I need to dynamically add the instance IPs to Django's CACHES location? Or would setting 'LOCATION': '127.0.0.1:11211', be sufficient for all running EC2 instances? Secondary Question Does NGINX centralize the cache for all running instances? My NGINX primary config: (staging) [ec2-user@ip-172-31-9-242 conf.d]$ cat elasticbeanstalk/00_application.conf location / { proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Connection $connection_upgrade; proxy_set_header Upgrade $http_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } The Django documentation says the same cache can be shared across multiple servers - Memcached caching: One excellent feature of Memcached is its ability to share a cache over multiple servers. This means you can run Memcached daemons on multiple machines, and the program will treat the group of machines as a single cache, without the need to duplicate cache values on each machine. To take advantage of … -
What is the purpose of deleting kwargs in a field's deconstruct method?
With the documentation detailing how to write a custom model field: Writing custom model fields, I'm failing to understand the implementation of Field Deconstruction and the deconstruct(). In the example they provided: For example, in our HandField class we’re always forcibly setting max_length in init(). The deconstruct() method on the base Field class will see this and try to return it in the keyword arguments; thus, we can drop it from the keyword arguments for readability: from django.db import models class HandField(models.Field): def __init__(self, *args, **kwargs): kwargs['max_length'] = 104 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs Reading further down in the documentation it says the following: for any configuration of your Field instance, deconstruct() must return arguments that you can pass to init to reconstruct that state. Why is the keyword argument max_length being deleted if its required to instantiate the field? -
django update using logged in username as pk
So I made table and post method menus with logged user information. I want to update information using username. If there's no username exit on table as logged in user, it posts data but if username already exits, I want it to overwrite data. So far, it doesn't overwrite but just post. What can I do to fix this? model.py class OrderItem(models.Model): username = models.CharField('Username', max_length=20, null=True, blank=True) first_name = models.CharField('First Name', max_length=30, null=True, blank=True) last_name = models.CharField('Last Name', max_length=30, null=True, blank=True) vendor_name = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) menu_name = models.ForeignKey(Menu, on_delete=models.SET_NULL, null=True) note = models.CharField('note', max_length=255, null=True, blank=True) view.py def UpdateOrderView(request, pk): username = user.is_authenticated order = OrderItem.objects.get(username=username) form1 = OrderForm() context = {'form1': form1 } if request.method == 'POST': form1 = OrderForm(request.POST, instance=order) print(request.POST) if form1.is_valid(): form1.save() return redirect('order-update', pk=pk) return render(request, '/order_info.html', context) urls.py urlpatterns = [ path("order_info", views.OrderView, name="order-page"), path("<int:pk>", views.UpdateOrderView, name="order-update"), ] -
Deploy Django app on Apache server on CentOS 7
I am following this article to deploy a Django app on Apache in CentOS 7. I have some differences compared to that article: 1 - I used port 443 for https (my machine already has port 443 open with my_app_dns) 2 - My virtual host config file /etc/httpd/conf.d/django.conf is as following: <VirtualHost *:80> ServerAdmin xxx@xxx.com ServerName my_app_dns DocumentRoot /home/centos/path_to_my_app Alias /static /home/centos/path_to_my_app/static <Directory /home/centos/path_to_my_app/static> Require all granted </Directory> #ErrorLog /logs/apis_error.log #CustomLog /logs/apis_access.log combined WSGIPassAuthorization On WSGIDaemonProcess my_app python-path=/home/centos/path_to_my_app:/home/centos/.local/share/virtualenvs/my_app-8BiokhAz/lib/python3.9/site-packages WSGIProcessGroup my_app WSGIScriptAlias / /home/centos/path_to_my_app/wsgi.py <Directory /home/centos/path_to_my_app> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> 3 - My app uses Postgres database instead of SQlite3. The DocumentRoot is set to /var/www in /etc/httpd/conf/httpd.conf. I have also set up self-signed SSL certificate with the file etc/httpd/conf.d/ssl.conf). Below is some of the content of the ssl.conf file: Listen 443 https ... <VirtualHost _default_:443> DocumentRoot "/var/www" ServerName my_app_dns:443 ... SSLEngine on SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt ... </VirtualHost> With the above setup, when I go to https://my_app_dns", I see the sample Apache Test page. If I change <VirtualHost *:80> to <VirtualHost *:443> in the file /etc/httpd/conf.d/django.conf, going to https://my_app_dns yields this error: my_app_dns sends an invalid response ERR_SSL_PROTOCOL_ERROR What am I missing in this setup sequence in order … -
Forward Telegram Channel Messages to Twitter via Bot (with delay)
Hope you are having a good time. I am looking to develop a basic telegram bot that will redirect all the messages from a private telegram channel to a twitter account with a delay of 3 hours, that is, if a message is posted in a telegram channel at 09:00 AM it should be forwarded to twitter at 12:00 AM. Can it be possible, if yes, how? -
AWS SES sending emails with disabled links
I configured the SES service with SMTP in a Django project. It sends emails, but sometimes (Not always), the emails arrives with all the links disabled. I verified the domain and the DKIM -
Django 3 by example bookmarklet_launcher.js
Following is a piece of code in the Django 3 by example book we can use it to in bookmark in a browser and upon clicking the bookmark, the code in it will be executed. Can anyone please help me understand this code? (function(){ if (window.myBookmarklet !== undefined){ myBookmarklet(); } else { document.body.appendChild(document.createElement('script')).src='https://127.0.0.1:8000/static/js/bookmarklet.js?r='+Math.floor(Math.random()*99999999999999999999); } })(); Why we need to put function inside parenthesis? (function.....)() How browser executes the code. We put javascript tag in start of code. JavaScript:(function.....)() what is this function myBookmarklet() and when if statement will be actually executed? How will window object will have myBookmarklet property? Any relevant resources will be appreaciated. Thanks a lot -
ValueError at /accounts/register. The User could not be created because the data didn't validate. (django model form)
I don't understand why this error would occur. So, here's my very simple user model: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): pass My Model Form: class RegistrationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Cofirm Password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'email') def clean_password(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: return False return True def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user And my view where i am calling the form.save() method: class Register(View): template = 'application/register.html' success_url = 'application:index' def get(self, request): ctx = { 'form': RegistrationForm(), } return render(request, self.template, ctx) def post(self, request): form = RegistrationForm(request.POST) instance = form.save(commit=False) if not form.is_valid(): ctx = { 'form': RegistrationForm(), } return render(request, self.template, ctx) instance.save() login(request, instance) return redirect(self.success_url) Can someone please help me understand what i have done wrong here?? Thank you -
Django-3.2 empty path anchoring in template
I have two urls.py file. The first one on root I have included the second. #urls.py (project urls file) path('', include('home.urls')), #urls.py (home app urls file) path('', views.Home.as_view(), name='index'), In my browser address bar '127.0.0.1:8000' works just fine. I am getting stuck when I want to anchor the url in template. <a href="{% url 'index' %}"></a> -
How to render errors provided from django API for each field individually in React JS
I have a register form and I want to display for each field the validation error that comes from api like in the next photo. I know how to create this on front end but I don't know how to find for each field from my form is the error message in api. I want to know how I cand show that red message coresponding to each field, based on the answer from api. {email} <label className="label-register">First Name</label> <input value={firstName} onChange={updateFirstName} id="first-name" required="true" className="form-input" type="text" /> <label className="label-register">Create a password</label> <input value={password} onChange={updatePassword} className="form-input" required="true" type="password"/> <label className="label-register">Repeat your password</label> <input value={password2} onChange={updatePassword2} className="form-input" required="true" type="password" /> <div className="term-and-cond"> <p><input type="checkbox" required="true"/>I have read and agree to the Terms and Conditions, the Privacy Policy.</p> </div> <button type="submit" className="check-email-btn register-btn">Create account!</button> </form> The response from the API is next: { "email": [ "E-mail already exist" ], "password": [ "Password must contain one number." ], "password2": [ "Password didn't match" ] } -
Use Custom Renderer Response In Django Test Client
I use a custom renderer to render responses from my views, and they work well when I send requests using Postman. When I try to write tests, the responses I get from the Test Client is different. Printing both responses gives these results: Postman Response: b'{"success":true,"message":"User retrieved successfully.","data":{"id":5,"email":"user0@email.com","username":"user0"}}' Test Client Response: {'id': 5, 'email': 'user0@email.com', 'username': 'user0'} How do I make the Test Client response the same as the response I get from Postman? -
Python: Reverse every 2 items on a list
I am working on a Django platform where i am supposed to submit a list of polygon coordinates from google maps to search through a dataset. So far, i have managed to collect the coordinates from the frontend but they are mixed up i.e the longitudes start then latitude follows and ideally ,the longitudes are supposed to start then the latitudes to follow Here is a working sample of the list i have: coordinates = [65.56147597726766, -104.83033675930798, 64.44751706485646, -93.93189925930798, 58.232434372977615, -98.85377425930798] The desired format should be: coordinates = [-104.83033675930798,65.56147597726766, -93.93189925930798,64.44751706485646, -98.85377425930798,58.232434372977615] Any help will be highly appreciated. -
Django unittest self.assertTemplateUsed, how to check the occurrence of multiple templates
self.assertTemplateUsed(response,('goods/item_list.html', 'base.html', 'inc/_nav.html') ,) error AssertionError: False is not true : Template '('goods/item_list.html', 'base.html', 'inc/_nav.html')' was not a template used to render the response. Actual template(s) used: goods/items_list.html, base.html, inc/_nav.html how to check for multiple templates in response -
Django: How to open a small window on button click without changing url
I am using Django and I want to open a small forms window when I click on button 'Nouvelle Chirurgie' in template without changing the url and I don't know if I have to do it with js or no and how to do it, and after that how to save it in views. Actually, I'm this button take me to another page: <a href="{% url 'register_visit' patients.id %}" class="btn btn-primary">Nouvelle Chirurgie</a> So, what should I do? -
Django v3 path variable in url issue
I've been scratching my head on this one a lot. I feel like the answer is right in front of me but I can't see it. I'm using django 3 and I have an url that is returning an error. My Urls is... url(r'^(?P<path>.*)$', views.GraphanaProxyView.as_view(), name='grafanadash'), My View is... class GraphanaProxyView(ProxyView): upstream = '{{ip.port}}' def get_proxy_request_headers(self, request): headers = super(GraphanaProxyView, self).get_proxy_request_headers(request) headers['X-WEBAUTH-USER'] = request.user.username return headers I am calling the url from an iframe.... <iframe src ="{% url 'grafanadash' %}" width="100%" height="1200px" frameborder="0"></iframe> But I get the following error... NoReverseMatch at /testsite/mt/mtgrafana/ Reverse for 'grafanadash' with no arguments not found. 1 pattern(s) tried: ['testsite\\/mt\\/(?P<path>.*)$'] I know that technically the "path" part doesn't point to anything, but the view is expecting a "path" variable for it to use. If I just type the address into the bar "/testsite/mt/grafanadash" it routes through the view and works. If I attempt to have it render inside a frame, or just call it through a link is when I get the error. Any help would be appreciated. -
How to make custom form readonly when accessed by user with no change perms on Django Admin
I have an issue. I have custom forms for most of my models - as I do most of my validation and data manipulation through Forms instead of Views so that the experience or behaviour when a user does their operation through my site or Django's Admin panel are the same. For models registered to the Admin site without custom forms (register model only) - they behave flawlessly according to user perms. If they have change_modelname perms, they can click the link on an object and be taken to a DetailView form where they can make changes. If they only have view_modelname perms, they'll be taken to the DetailView that are now all readonly. For models registered to the Admin site with my custom forms though - for users that only has View permissions (no Change permissions), are met with a KeyError when clicking on an object, instead of being able to see the DetailView in readonly mode. I've looked around on how to solve this, including trying to find out from the source code on how Django does this with the forms they generate from our models by default, but can't seem to find anything useful to me. What … -
Automatically link form and user using OneToOneField
I have create a model form using also OneToOneField field to link it to my user, my problem is that I have to go to the admin section to manually select the user to make it works. Is it possible to have the user linked to the form submitted automatically? Also this may be stupid but when I use user.userinformation.gender to get the info about gender I get back "m", is there a way to access the label "Male" instead? TThank for yours help! My code: models.py class UserInformation(models.Model): gender_choice = [('m', 'Male'),('f', 'Female')] user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) gender = models.CharField(max_length=120, choices=gender_choice) phone = models.CharField(max_length=10) email = models.EmailField() forms.py class UserInformationForm(forms.ModelForm): class Meta: model = UserInformation fields = ('first_name', 'last_name', 'gender', 'phone', 'email',) views.py def add_information(request): if request.method == "POST": form = UserInformationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Form submitted') else: form = UserInformationForm() return render(request, 'accounts/profile/add_information.html', {'form': form}) def show_profile(request): profile_info = UserInformation.objects.all() return render(request, 'accounts/profile/user_profile.html', {'profile_info': profile_info}) -
Handle multiple booleans in postgres?
I have a table which has more than 12 columns which just have boolean items ! How to manage this with a single column or having multiples are the effective ? And as part of requirement, this needs to be dynamic ( in the sense, the column may increase in future ) so it should act without altering the table ! Whats the best way to achive this ? Table users: education: False profession: False location: True certificates: False exams: True Like the above i have more than 12 columns, and in near future this may increase - so is there any way to handle this - for example using Json or array or bitwse etc