Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating a field's attributes on ModelForm instance doesn't work in Django
I'm trying to add the id field "company-select" to the field of a ModelForm. However, when rendering the form, it doesn't apply the provided custom id. I applied the logic to my form according to the official docs. class CompanyForm(ModelForm): """ A form to render a select widget with companies associated to a user """ name = forms.ModelChoiceField(queryset=Company.objects.exclude(name='exclude-all'), required=True) class Meta: model = Company fields = ('name',) widgets = { 'name': Select(attrs={'id': 'company-select'}), } renders <select name="name" required="" id="id_name"> <option value="" selected="">---------</option> <option value="25">Test Company</option> ... </select> # forms.py def render_entities(request): """View to render the entities overview page""" # Get the logged in user instance user = User.objects.get(username=request.user.username) user_cashpool = Cashpool.objects.get(company__user=user) # Get the info for the site visited dashboard_site = 'entities' if request.method == 'GET': # Return the form and populate with user's company company = user.company # Query all entities associated to the cashpool companies = Company.objects.filter(cashpool=user_cashpool).order_by('name') # Pass the queryset to the Select Form CompanyForm.base_fields['name'] = forms.ModelChoiceField( queryset=companies) # Return the form form = CompanyForm() context = { 'company': company, 'companies': companies, 'dashboard_site': dashboard_site, 'form': form } return render(request, 'dashboard/dashboard_entities.html', context) -
Angular to Django, passing multiple parameters in a service call
I have some working code on Django, where i created a simple file uploader with a date picker that is passed through a view and then uploaded onto a database using a standalone python class that utilise sqlalchemy. However, I have been working on migrating the UI aspect onto an Angular Front End, but hit a road block and not sure where I am going wrong. The user needs to be able upload a excel binary file, input a date and hit upload. This should send a request to a view which then handles the request. The view it self works perfectly, when the file and dates are inputted from the Django HTML template. But I can't seem to make it work once the inputs come from Angular. At the moment I am getting a 'Unsupported Media Type" Error message. But my guess is i am not passing the file and date correctly to the service. Any help would be great Here is my code views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.FILES['data'], request.POST['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST) … -
how we can implement this coniditon in django template
How i can implement this condition in django template with multiple and or statement in if? {% if ((email_setting.twitter_link is not None and email_setting.twitter_link != '') or (email_setting.instagram_link is not None and email_setting.instagram_link != '') or (email_setting.fb_link is not None and email_setting.fb_link!= '') ) %} Here my body {% endif %} this give me an error TemplateSyntaxError at /settings/emailView Could not parse the remainder: '((email_setting.twitter_link' from '((email_setting.twitter_link' -
Django Rest Framework Prefetch_Related Order_By api result not ordered
I am trying to order the results of an api query by a prefetched field but it returns the results in the order of item_id Models class ItemDetails(models.Model): item_id = models.BigIntegerField(blank=True, null=False, primary_key=True) name = models.TextField(blank=True, null=True) class ItemRatings(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) item_id = models.ForeignKey('app.ItemDetails', on_delete=CASCADE, to_field='item_id ', related_name='ratings', db_column='item_id') rating= models.FloatField(blank=True, null=True) Views class ItemList(viewsets.ModelViewSet): def get_queryset(self): prefetch = Prefetch('ratings', queryset=ItemRatings.objects.order_by('rating')) return ItemDetails.objects.prefetch_related(prefetch) serializer_class = ItemListSerializer Serializers class ItemRatingsSerializer(serializers.ModelSerializer): class Meta: model = ItemRatings exclude = ('id', 'item_id') class ItemListSerializer(serializers.ModelSerializer): ratings = ItemRatingsSerializer(required=True, many=True) class Meta: model = ItemDetails fields = '__all__' Ive tried adding .all() after objects and at the end of the return statement in the get_queryset statement Any help is appreciated thank you -
Django Admin get_fieldsets kills User add form. Cannot add User
All hands, what I was trying to do is to filter UserChange fieldsets on the basis of user access. Just to remove some fields if user is not superuser And it worked. However later I discovered that I cannot create User as the start form with user name and two password fields is non existent anymore. So, Django keeps showing me red sign of mistakes as simply there are not required fields visible and I cannot fill them up. I removed all my code and found out that the simple fact of having this get_fieldsets function changes the add_form I tried to add specific user add form, I tried add_fieldsets - everything with no result until I have get_fieldsets() in my UserAdmin. Any ideas what I am doing wrong? -
How to get TLS/SSL information from request session in python?
I am working on updating django application services with TLS configuration to restrict the versions used as well as the ciphers in each version. For that purpose I am using HTTPAdapter and I mount the session with different ssl options. My question is that is there a way to get information of the mounted adapters in python? or anyway to check the tls/ssl settings in a created session? -
Django permission_required - how to detect if user has admin perm
I want to ask and know, how to detect with decorator befero view method if user is admin. Thanks. -
How to get username in models.py?
models.py def upload_to(instance, filename): nowDate = datetime.now().strftime("%Y/%m/%d") return '/'.join(['verify', instance.user.username, nowDate, filename]) class UserVerifyImg(models.Model): username = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE ) business_type = models.CharField(max_length=255) image = models.ImageField(upload_to=upload_to) upload_date = models.DateTimeField(auto_now = True) class Meta: managed = False db_table = 'account_user_verify' I searched about instance.user.username but It is showed errer. AttributeError: 'UserVerifyImg' object has no attribute 'user' This is my error. -
Instance of djaform not updating
I have the next form in Django: class Medical(forms.ModelForm): worker= forms.ModelChoiceField( queryset=Worker.objects.none(), empty_label=None, widget=forms.Select(attrs={'class': 'form-control'}) ) description=forms.CharField( widget=forms.Textarea(attrs={'class': 'form-control'}) ) upload=forms.FileField( widget=forms.FileInput(attrs={'class': 'form-control'}) ) class Meta: model = Medical_Issue fields = ( 'worker', 'description', 'upload', ) def __init__(self, *args, **kwargs): user_id = kwargs.pop('user_id') method=kwargs.pop('method') super().__init__(*args, **kwargs) self.fields['worker'].queryset = Worker.objects.filter(user_id=user_id) def save(self, commit=True): m = super(Medical, self).save(commit=False) m.worker=self.cleaned_data['worker'] m.description=self.cleaned_data['description'] m.upload=self.cleaned_data['upload'] if commit: m.save() return m And following views: def medical_list(request): worker=Worker.objects.filter(user_id=request.user.id).get() issues=Medical_Issue.objects.filter(worker=worker.id).order_by('-created_at') return render(request,'medical_list.html', {'medical_issues':issues}) def medical_add(request): print(request.user.id) if request.method == "POST": form = Medical(request.POST,request.FILES,user_id=request.user, method= 'ADD') if form.is_valid(): form.save() return redirect('medical_list') else: form = Medical(user_id=request.user, method= 'ADD') return render(request, 'medical_add.html', {'method':'ADD','form': form}) def medical_edit(request,id_issue): worker=Worker.objects.get(user_id=request.user) issues=Medical_Issue.objects.filter(worker=worker).order_by('-created_at') issue= Medical_Issue.objects.get(id=id_issue) if request.method == 'GET': form = Medical(user_id=worker.user_id,instance=parte, method= 'EDIT') else: form = Medical(request.POST, request.FILES, user_id=worker.user_id, method= 'EDIT') if form.is_valid(): form.save() return redirect('medical_list') return render(request,'medical_add.html', {'method':'EDIT','form': form}) Main probles is when adding, it saves record just fine, but when editing, it is creating a new instance of the issue. I´m trying to make it modifying save method on form, but maybe it´s not the right approach? With thata said, I have tried to add an id field to the form, but same results from this Thanks -
Django Fatal Error Connection failed at local host
Django Fatal Error Connection failed at local host enter image description here -
Django - Many to Many Relationship with Workouts & Exercises
I'm currently stuck on how to do the following: I want to track workouts and see the progress being made with the exercises. Each workout has a name, body weight, date, and exercises. I want to select the exercises when adding the workouts(exercises are already pre-created with a name and some tags), however, each workout is different, meaning the reps, sets, and weight for the exercise is different every time. I'm not sure how to make a model for this. I've added an image of a simple design I made to show what I'm after Hope someone can help me, I'm pretty sure it's a simple solution however, my brain is stuck atm. Image Of Design -
'WSGIRequest' object has no attribute 'get' Django 3.2.9
When i click button "send email" i got this problem 'WSGIRequest' object has no attribute 'get', i have no idea what going on. When i change method to GET the problem still issuse. views.py def sender(request): sent = False if request.method == 'POST': # Formularz został wysłany. form = EmailForm(request) if form.is_valid(): # Weryfikacja pól formularza zakończyła się powodzeniem… cd = form.cleaned_data title = request.POST.get('title','') message = request.POST.get('message','') email = request.POST.get('email','') send_mail(title, message, email, 'admin@admin.pl', fail_silently=False ) sent = True else: form = EmailForm() return render(request, 'contact.html', {'form': form,'sent': sent}) ulr.py urlpatterns = [ path('kontakt', views.sender, name='kontakt'), path('oferta', views.oferta, name="oferta"), path('', views.PostListView.as_view(), name='core'), path('<slug:slug>', views.post_detail, name='post_detail'), ] contact.html {% extends "base.html" %} {% block title %}Wyślij email{% endblock %} {% block content %} {% if sent %} <h1>Wiadomość e-mail została wysłana</h1> <p> "Wysłanie emaila zakończyło się sukcesem. </p> {% else %} <h1> Wyslij wiadomośc poprzez e-mail</h1> <form action="" method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Wyślij wiadomość e-mail"> </form> {% endif %} {% endblock %} Python ver 3.10.0 Django ver 3.2.9 -
Lit2.0 how to submit form data to backend
Am using Lit2.0, Material Web components, Django (backend). one reference: https://www.thinktecture.com/en/web-components/flaws/ I don't understand how to submit form data from Lit component to backend (Django) form.html contains Lit component (basic-form) <form id="id_demo" method="post" action=""> {% csrf_token %} <basic-form></basic-form> <button type="submit" class="mdc-button mdc-button--raised">Submit</button> </form> basic-form is a Lit component and it contains Material web components import {LitElement, html} from "lit"; // const template = document.createElement('template'); // template.innerHTML = ` // <slot></slot> // `; export class BasicForm extends LitElement { static properties = { form: '', }; constructor() { super(); // this.shadow = this.attachShadow({ mode: 'open' }); // this.shadow.appendChild(template.content.cloneNode(true)); } render() { return html` <mwc-textfield name="first_name"></mwc-textfield> `; } } customElements.define('basic-form', BasicForm); Could someone guide me to the right direction. -
How to pre format a string to show hyperlink in frontend using django
I have a model in which I accept string data in the char field. this is populated through Django admin field. Models.py class Test(models.Model): overview = models.CharField(max_length=10000, null=True, blank=False) views.py from .models import Test def testView(request): data = Test.objects.all() return render(request, 'abc.html', {'data': data}) my template which has html <p style="text-align: center; color: black">{{data.overview | linebreaks}}</p> this mock response of data: "with the great power comes the great responsibility. <a href="https://www.google.co.in/">connect</a>" from backend. how to show this as a link inside the paragraph in the front end. currently the whole anchor tag is displayed instead of link -
Running javascript code after Django backend Validation
this might be a stupid question but i cant seem to wrap my head around the problem here. I am trying to run a bit of code after a form has been submittet with no errors. The error handling is happening in a django backend. When the form is succesfully submittet, the user is redirected to another page. So i had an idea where i would listen to a page redirect then run the code that i want to but i am unsure if that is the best idea. There is really no code to show, does anyone have any idea. Also an idea where i would wrap my form as a promise and when the promise was fuffilled i would run the code but i am unsure of how to do that aswell. -
django: bootstrap modal not displaying
To test modal creations in python with django I created a test app named modalTestApp. Then I copied this html that I got off of the bootstrap website and pasted it into the main.html inside the app, without changing it. The webpage from the app loads fine but clicking the button to preview the modal does nothing. What am I doing wrong here? main/base.html: {% load static %} <!DOCTYPE html> <html> <head> <script src={% static "jquery/jquery-3.3.1.slim.min.js" %}></script> <script src={% static "jquery/jquery.min.js" %}></script> <script type="text/javascript" src={% static 'tablesorter-master/js/jquery.tablesorter.js' %}></script> <script src={% static "bootstrap-4.3.1-dist/js/popper.min.js" %}></script> <script src={% static "bootstrap-4.3.1-dist/js/bootstrap.min.js" %}></script> <style type="text/css"> .main { margin-top: 50px; padding: 10px 0px; } </style> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href={% static "bootstrap-4.3.1-dist/css/bootstrap.min.css" %}> <title>{% block title %} {% endblock title %}</title> </head> <body> <nav class="navbar navbar-dar bg-dark pb-0 pr-0"> <ul class="nav flex-row"> <p class="navbar-brand mb-0 pt-0" style="color: #eee">Weather Data</p> <a href="/", class="nav-link active">Home</a> {% if user.is_authenticated %} <a href="/stations", class="nav-link active">Stations</a> {% endif %} </ul> <ul class="nav justify-content-end"> {% if not user.is_authenticated %} <a href="/register", class="nav-link active">Register</a> <a href="/login", class="nav-link active">Login</a> {% else %} <a href="/logout", class="nav-link active">logout</a> <a href="/users/{{ user.username }}", class="nav-link active">Profile</a> {% endif %} </ul> </nav> {% block … -
How do you change the primary key sent to an update view in django?
I want to change the primary key being sent to the update view from the template. Let me explain. Here is my template: <a href="{% url 'new_url' model_instance.pk %}"> {{ model_instance.username }} </a> This model_instance is an instance in a for loop of the context variable model_instances in a list view. This primary key of the model_instance will then be sent to the following view: class UserUpdateView(generic.UpdateView): template_name = "leads/update.html" queryset = User.objects.all() context_object_name = "user" form_class = UserUpdateForm def get_success_url(self): return reverse("some-url") However, the problem is that the primary key I am sending to UserUpdateView is the primary key for the model_instance model, not the User model. Moreover, there is no link like one-to-one relationships between the the two models. However, there is a similarity. Both of the model_instance and user each have a username field that are the same. In other words, I need to first retrieve the model_instance.username, and then query the User model to find the user instance I want to update. At the moment, the UserUpdateView is simply receiving the primary key for a model_instance in the template, which is not what I want. I hope you guys can help me with this issue, and … -
django test framework token authentication — is there any way to log everyone out?
I understand that token authentication doesnt really have the concept of logging out— that a token merely identifies a user. Is there any way to invalidate all tokens? Maybe via the change of some variable from which all the tokens are generated— causing everyone to need to log in again? -
Query one more existing MSSQL DB from Linux
I have deployed django application running on Linux (Ubuntu) in VirtualBox. The settings file database section looks like this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } On the local network there is an MSSQL Server with database x and a few tables. I'd like to create a view with datagrid, which is able to work with the data from database x providing the basic CRUD functionality with possibility of filters. Could you refer me to the steps with corresponding documentation I need to fulfill? You don't need to go into much detail, only to refer me to what I need to edit and what I should be aware of to achieve a desired result. -
Django rest framework how to use path parameter in serializer
I am trying to create a API endpoint that outputs calculated data from the database. In this endpoint I have a path parameter which I would like to filter the data by. However I am not sure how to do it. urls.py path('v1/sets/<str:code>/breakdown', individual_set_breakdown.as_view(), name='individual_set_breakdown'), views.py class individual_set_breakdown(ListAPIView): serializer_class = SerializerSetsIndividualBreakdown def get_queryset(self): code = self.kwargs.get('code', None) qs = magic_sets.objects.filter(code=code.upper()) return qs serializers.py class SerializerSetsIndividualBreakdown(serializers.ModelSerializer): common = serializers.SerializerMethodField() class Meta: model = magic_sets fields = ['common'] def get_common(self): def average(lst): if not len(lst): return 0 else: return sum(lst) / len(lst) common = { 'unique': magic_sets_cards.objects.exclude(side='b').filter(set_id__code='LEA').filter(rarity='common').count(), } return common As you can see I try to filter the data in the view but that does not seem to filter the data the is returned from the endpoint. I would like filter(set_id__code='LEA') to be dynamic depending on what is passed into the endpoint. If I remove this part it gets the data for all sets. -
Django Re-Run Migrations on older DB
I've made some changes to my local Django project which has altered my DB structure. I ran my migrations on my local database and everything works fine locally. However my production SQL file does not have these changes made to it. How do I bring my production SQL file up-to-date with the new migrations? -
Straight forward modelform doesn't validate on submit of form
I have a fairly simple ModelForm which doesn't validate on submit. Not sure how to debug this. I tried different print statements in my view and everything seems to be proper. This is what I have: # views.py def render_entities(request): """View to render the entities overview page""" # Get the logged in user instance user = User.objects.get(username=request.user.username) user_cashpool = Cashpool.objects.get(company__user=user) # Get the info for the site visited dashboard_site = 'entities' if request.method == 'GET': # Return the form and populate with user's company company = user.company # Query all entities associated to the cashpool companies = Company.objects.filter(cashpool=user_cashpool).order_by('name') # Pass the queryset to the Select Form CompanyForm.base_fields['company'] = forms.ModelChoiceField( queryset=companies) # Return the form form = CompanyForm() context = { 'company': company, 'companies': companies, 'dashboard_site': dashboard_site, 'form': form } return render(request, 'dashboard/dashboard_entities.html', context) else: form = CompanyForm(request.POST) if form.is_valid(): # fails # Get the cleaned inputs company = form.cleaned_data['company'] ... # forms.py class CompanyForm(forms.ModelForm): """ A form to render a select widget with companies associated to a user """ company = forms.ModelChoiceField(queryset=Company.objects.exclude(name='exclude-all'), required=True) class Meta: model = Company fields = ['name'] # template <!-- Select Company --> <form action="entities" method="post"> {% csrf_token %} <label for="company">Select a Company</label> {{ form.company }} … -
django make multiple objects for each da with a user imput: start and end date
I'd like to know how i can make multiple object for each day in a Timespan. The users input is a start and end date. My curent moddel looks like this: from datetime import datetime from django.db import models from django.contrib.auth.models import User class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) desk = models.ForeignKey(to='Desk', on_delete=models.CASCADE) startingdate = models.DateField(default=datetime.now) endingdate = models.DateField(default=datetime.now) ... I probably have to change it to this: ... class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) desk = models.ForeignKey(to='Desk', on_delete=models.CASCADE) date = models.DateField(default=datetime.now) ... The user selects a start and end date on the website: <form"> <label for="starting_date">Start Date:</label> <input type="date" id="starting_date" name="starting_date"> <label for="ending_date">End Date:</label> <input type="date" id="ending_date" name="ending_date"> <input type="submit" value="Submit"> </form> As I said a user should have the posibility to canche a Booking for a day. but the problem here is if the user e.g. created a Booking from 21-12-2021 until 25-12-2021 and just want to canche/delete the booking on 23-12-2021 it get's a bit complecated. -
What is the recommended way of naming REST API urls? [closed]
I have a Django REST API. In my app there are users and the users have plans. For plans, I have GET, POST and PUT routes. Every plan has an id and a user_id linking it to a User. Should I use url parameters in my endpoints or should I just receive the params in the request body? For example, should I do: POST api/user/<uuid:user_id>/plan or POST api/plan and take the user_id from the request body? And if the number 1 is the better way, should I still require the user_id to be passed also into the request body? And with the update request, should I do: PUT api/user/<uuid:user_id>/plan/<uuid:plan_id> or PUT api/plan/<uuid:plan_id> and take the user_id from the request body, or PUT api/plan/ and take both id's from the body? And again, if I require the id's in the url, should I do it also in the body? -
Django_filters apply all chosen filter fields
Hej! :) I want to filter my data before I do some calculations with it with an AND operator. The chosen filter fields should ALL be applied. I added some fields of the mode to the filter function and I can filter (e.g.) for the name and the year seperate. But not combined. If I try to filter for both name AND year at the same time I would just get the results from year. In my model I got an M2M to another model in which the year is set: # models.py class Plant(models.Model): name = models.CharField( max_length=200 ) used_xducts = models.ManyToManyField( Xduct, through="UsedXduct", blank=True, related_name="used_in_plant" ) class UsedXduct(models.Model): plant = models.ForeignKey( Plant, on_delete=models.PROTECT, related_name="used_in_plant" ) xduct = models.ForeignKey( Xduct, on_delete=models.PROTECT, related_name="xduct" ) year = models.SmallIntegerField( validators=[validate_year], blank=True, null=True ) class Xduct(models.Model): code = models.CharField( max_length = 20, blank = True, null = True, unique = True ) name_english = models.CharField( max_length = 200, blank = True, null = True, unique = True ) description_english = models.TextField( max_length = 500, blank = True ) explanation_english = models.TextField( max_length = 4000, blank = True ) # filters.py class PlantsNameFilter(django_filters.FilterSet): name = ModelChoiceFilter(queryset=Plant.objects.all()) year = django_filters.NumberFilter(method='year_filter', label='Year') class Meta: model = …