Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Scrollable vertical menu jumps to top after clicking on a link
Good evening community, I have a problem related to a vertical menu that is scrollable when there are more items in the menu than the page can take vertically. If I scroll down to an item that is not displayed on the screen when I'm at the top of the menu and I click this item to get to the respective page, the page will get loaded but the menu jumps back to the top, so that the item i just clicked is not displayed on the screen again. But I want that the part of the menu with the item is shown when the new page is loaded and not the top of the menu. I'm developing my site with python and django and using bootstrap for frontend, if that helps with my problem. I will add some pictures to visualize my problem. Sadly i can't post pictures directly yet. Starting Position 1 <- This is the top of the menu with the page 'Einführung' loaded Scrolled Position 2 <- This is the scrolled position and I want to click the 'Print-Funktion'-link Top Position 3 <- This is the menu after I clicked on the link (top position) Scrolled … -
How to use Basic HTTP Django Authorization middleware?
I don't understand the django middleware snippet here: https://djangosnippets.org/snippets/1304/ I have incorporated the middleware correctly, and upon visiting my site, I can manually enter in the username and password and authenticate with the decorator. My problem is that I don't know how to send a request from Postman/curl to authenticate. I have included an "Authorization" header in my Postman request, but I don't know how to format the values. For example: "Authorization: user password" def __call__(self, request): if 'HTTP_AUTHORIZATION' not in request.META: return self._unauthed() else: authentication = request.META['HTTP_AUTHORIZATION'] (auth_method, auth) = authentication.split(' ', 1) if 'basic' != auth_method.lower(): return self._unauthed() auth = base64.b64decode(auth.strip()).decode('utf-8') username, password = auth.split(':', 1) if ( username == settings.BASICAUTH_USERNAME and password == settings.BASICAUTH_PASSWORD ): return self.get_response(request) return self._unauthed() -
Signal django to run a task
I made a management command that populates one of my models from a csv file. I need to do this update quite frequently and the csv files have tens of thousands of lines. Sometimes it can take over 10 minutes to finish populating. I want to add a feature that lets me upload the csv file through the website directly and after the file is uploaded, django should run that command, or at least the logic from it, and populate the db. How would I go about this? I want to be able to leave the page after I upload the file and receive an e-mail when the task is finished. -
How do I include intermediary Models in my Django Rest Framework API
I am in the process of learning about the Django Rest Framework at the moment and I stumbled unto a tricky part that I can't seem to get working in our project. Our project is a fictional webshop where you can put dog babies in your cart and order them. Our Frontend is communicating with the backend via Django Rest Framework. The three main models that we have are Users, Orders and Puppies. Because every order has a list of puppies and every puppy has its own amount we needed an intermediary model for the two as a simple ManyToManyField apparently can't handle extra columns. This makes things much more complicated (at least for someone who is new to Django). How can I reflect the relationship in the serializers and the views and how do I have to form the JSON Object that is sent from the frontend? also: Where would I calculate the total price of an order? Do I need the OrderDetail view even if I don't want to edit or get one specific order or is the DetailList view enough? There is a question on here which is solving a similar problem: Include intermediary (through model) in … -
Editing a .JSON file from the Django Admin Panel using Models
I'm setting up the admin panel for Django to allow easy editing of a .json file with names and information. The problem is that the file isn't static and it's not modified by just me but also by code running in the background that modifies and adds new values. Sometimes these values can be incorrect so I'm trying to get it so i can manually edit them using the admin panel from Django. Example JSON file: { "101": { "First_Name": "Ida", "Last_Name": "Wilkins", "Age": "42", }, "102": { "First_Name": "Tony", "Last_Name": "Davis", "Age": "34", } } I've already tried using serialize but I only really managed to get it loaded into the admin panel and not out of it it also didn't really look this was a good way to do it. I also can't really find any information on how to do this and if it's even possible. -
Group models by field similarity in Django/PostgreSQL
Let's say I have a Person model: from django.db import models class Person(models.Model): name = models.CharField(max_length=256) Instances of this model have been populated from an existing data source, and I would now like to merge similar People together by name. It is trivial to find the names similar to a given name ("Bob", here): Person.objects.all() # Annotate each item with its unaccented similarity ranking with the given name .annotate(similarity=TrigramSimilarity("name__unaccent", "Bob")) # And filter out anything below the given threshold .filter(similarity__gt=0.9) This will generate (something close to) the following: SELECT "person"."id", "person"."name", SIMILARITY("cases_person"."name", 'Bob') AS "similarity" FROM "cases_person" WHERE SIMILARITY("cases_person"."name", 'Bob') > 0.9 But, what I want are groupings of similar people. This can be done in Python with some modifications to the above: from django.contrib.postgres.search import TrigramSimilarity from .models import Person people = Person.objects.all() threshold = 0.9 people_ids_to_merge = [] processed = set() for name in people.values_list("name", flat=True): similar_people = ( # We must exclude any people that have already been processed, because # this means they are already in people_ids_to_merge. If we didn't # exclude them here, we would get duplicates in people_ids_to_merge people.exclude(id__in=processed) # Annotate each item with its unaccented similarity ranking with the current name .annotate(similarity=TrigramSimilarity("name__unaccent", name)) … -
Django won't accept a decimal as a decimalfield
I have a an api endpoint that receives some data (a decimal in string form). It then needs to multiply it by something from the db, which is a DecimalField, and save the result into another DecimalField (via a model serialiser). I've tried the following (request.data["hours"] is a string, hourly_rate is a decimal from a DecimalField) total = request.data["hours"] * hourly_rate - fails, multiplying string by Decimal total = Decimal(request.data["hours"]) * hourly_rate - fails total = (Decimal(request.data["hours"]) * hourly_rate - fails).to_eng_string() - fails In all but the first, 'fails' means the following error: {'total': [ErrorDetail(string='A valid number is required.', code='invalid')]} I would have expected it to accept a Decimal, and I've read that it should accept a string, but apparently not... -
when i want to extract information from query results in django it return none
I want to get the column of result, it prints fine in views, but return nothing in ajax, i don't know why?, there are a same type of function that works fine, but it didn't. def requiredfield(request): total_ms=['pratap'] # #print(T) name = ['jay'] print(name) print(total_ms) if request.method == "POST": datafiles = request.POST.get('datafiles') print(datafiles) query = 'select id, Must_Have from analytics_fileuploadrequiredata where DataFiles_Name = ' + '"' + datafiles + '"' #query = 'select id, Functions from analytics_analyticsreport' print(query) result = FileUploadRequireData.objects.raw(query) for i in range(len(result)): ms = result[i].Must_Have if ms not in total_ms: total_ms.append(ms) print(total_ms) return JsonResponse(total_ms, safe=False) -
Server-to-server communication with RasPi and Python
I am aware of frameworks like Django and Flask that manage all the GET requests etc but how do I communicate between two servers without a framework full of nonsense I don't need. I'm trying to set up a drone with motors, photos that need sending and remote control via the server at home which is accessed over the internet via a proxy for security. I'm focusing on the RasPi though. -
Server communication with Python on RasPi
I am aware of frameworks like Flask and Django that manage all the GET requests etc but how do I communicate between two servers without a framework full of nonsense I don't need. I'm looking to finish my server-controlled drone which sends pictures and is controlled via the server but all in Python. -
NoSQL or SQL for eCommerce sites' product price comparison ( with Django)?
I'm trying to build a project for comparing product prices among different e-commerce sites of our local area. I'm using Scrapy for crawling data from different e-commerce sites and now needs to store those data into a database. I'm not sure which type of database I need to store information like below: product_title product_link product_image product_price Any kind of suggestion would be much appreciated. Note: I am using Django for back-end and Scrapy for data scraping. -
Django form, use data in field from other model
How to fill field in form based on model id? I have to models. Match and Match Register. Logged user can register for match, the data is written in Match Register model. I am now creating form for editing Match object and want to populate fields referee_a and referee_b with values from Match Register table (for edited match of course). I don't know how to to do this exaclty. Could you please help me with it? class MatchForm(forms.Form): class Meta: model = Match fields = ('match_number', 'home_team', 'away_team', 'match_category', 'date_time', 'notes', 'referee_a', 'referee_b') widgets = { 'match_number': forms.TextInput(attrs={'class': 'form-control'}), 'home_team': forms.Select(attrs={'class': 'form-control'}), 'away_team': forms.Select(attrs={'class': 'form-control'}), 'match_category': forms.Select(attrs={'class': 'form-control'}), 'date_time': forms.DateTimeField(attrs={'class': 'form-control'}), 'referee_a': forms.Select(attrs={'class': 'form-control'}) 'referee_b': forms.Select(attrs={'class': 'form-control'}) 'notes': forms.Textarea(attrs={'class': 'form-control'}) } class MatchRegister(models.Model): match = models.ForeignKey( Match, on_delete=models.SET_NULL, null=True ) ref_reg = models.ForeignKey( User, on_delete=models.SET_NULL, null=True ) -
Django channels sends 403 instead of 404
I'm just starting with django channels and I would like in case of error that django channels sends a 404 instead of a 403 when closing without accepting connection. class MyConsumer(AsyncWebsocketConsumer): async def connect(self): if False: await self.accept() await self.close() Client side, when I connect to this socket, I get 403 and I want to receive 404: b'HTTP/1.1 403 Access denied\r\n' There is probably something basic I don't get. -
No .sock file is being created by my gunicorn service
I have the following problem while hosting my website. I configured all the things .conf files here: gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=user Group=nginx WorkingDirectory=/root/myproject ExecStart=/root/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:/root/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target and my nginx.conf server { listen 80; server_name agros.uz www.agros.uz; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/myproject/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/root/myproject/myproject.sock; } } However I am having the following error unix:/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 37.9.113.208, server: agros.uz, request: "GET /uz/insurance?type=physical&page=2&page=7&page=6&page=8&page=4 HTTP/1.1", upstream: "http://unix:/root/myproject/myproject.sock:/uz/insurance?type=physical&page=2&page=7&page=6&page=8&page=4", host: "agros.uz" When I access the domain this error happens 502 Bad Gateway error and the .sock file is not being created in /root/myproject/myproject.sock as it mentioned in my gunicorn.service file. -
Django built-in authentication for reset password link chopping off token in url
I am using built-in Django authentication to send an email to reset a password. Sending the email works, but when I try and follow the link to the page to reset my password, Django changes the URL (kind of like a redirect I guess) and then is trying to resolve the URL to 'http://127.0.0.1:8000/registration/USER_ID/set-password', instead of 'http://127.0.0.1:8000/registration/USER_ID/TOKEN'. Django then throws an error: 'NoReverseMatch at /registration/reset/USER_ID/set-password/' I don't have a file called "set-password" and nowhere in my code (templates, URLconf) do I have "set-password". urlpatterns = [ ... ... path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] I am using the code found in the docs (https://docs.djangoproject.com/en/2.1/topics/auth/default/#using-the-views) for my URL matching, so I am not creating anything new. It seems like Django is removing the token from the URL? -
Send custom signal on updating record in DRF view
I'm using Django 2.x and DRF. I have created a signal and want to send it when the record is updated and created. Below is my ViewSet with two methods update and perform_create. class AmountGivenViewSet(LoggingMixin, viewsets.ModelViewSet): serializer_class = AmountGivenSerializer def update(self, request, *args, **kwargs): obj = self.get_object() request.POST._mutable = True if 'mode_of_payment' not in request.data: request.data['mode_of_payment'] = obj.mode_of_payment_id request.POST._mutable = False return super().update(request, *args, **kwargs) def perform_create(self, serializer): contact = serializer.validated_data.get('contact') if contact.user != self.request.user: raise ValidationError({'contact': ['Contact does not exists']}) obj = serializer.save() given_amount_updated.send( sender=self.__class__, instance=obj, amount=self.request.data.get('amount', None), action='given' ) The signal should be sent only when the record is successfully created or updated. I'm able to send the signal in perform_create() method by putting after serializer.save() but how to do this in update(). Also I want to send updated obj as instance to the signal. -
Django: error_messages is not changing in form
I need to change the error_messages on a form from english to spanish. I've found this similar question: Django - change field validation message And I'm using it's second option 2.1. but It is not working, why? my_default_errors = { 'required': 'Este campo es obligatorio', 'invalid': 'Ese nombre de usuario ya está tomado' } class SignUpForm(UserCreationForm): first_name = forms.CharField(label= "Nombre", max_length=100, required=True) last_name = forms.CharField(label = 'Apellido', max_length=100, required=True) username = forms.CharField(label='Nombre de usuario', max_length=100, required=True, error_messages=my_default_errors) email = forms.EmailField(label='Correo electrónico', max_length=60, required=True) password1 = forms.CharField(label = 'Contraseña', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirmar contraseña', widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2') -
How to make DjangoTemplates work recursively
I have a template home.html which is the view of an app in Django. Now, I've added some templating in the html file to allow dynamic generation of HTML. For example I use {% load static %} and then href="{% static "path/to/resources" %}". So, when I open the app, after running the server, the path is dynamically created. Now, the problem is that the static files, that are dynamically loaded, also need to load other static files (and extend a template as well). I thought that DjangoTemplating might be working recursively, and will work on the called file too, but sadly that is not true. So, what should I do to make sure that all my templating logic is taken into consideration by Django, and is allowed to run? home.html snippet: {% load static %} <area alt="andhra" title="Andhra Pradesh" name="andhra" href="{% static "personal/pages/andhra.html" %}" shape="poly" ... /> andhra.html looks something like: {% extends "personal/post.html" %} {% blockcontent %} <style> #slider { width: 80%; .... <div class="carousel-inner"> <div class="carousel-item active"> {% load static %} <img class="d-block w-100" src="{% static "personal/images/andhraImages/1911-1915.jpg" %}" alt="First slide"> </div> ... {% endblock %} Which wants to extend the template:post.html which has {% blockcontent %}and {% endblock … -
Django override Save() Split into 3 separate entries
I have a model for Website which takes a domain_name entry class Website(models.Model): domain_name = models.URLField(unique=True) sub_domain =models.CharField(max_length=56, blank=True, default='') suffix = models.CharField(max_length=56, blank=True, default='') I'm then trying to split the domain parts using tldextract which is working well, on entry of a website by a user i want to store the sub_domain, domain and the suffix, so I've tried a lot of ways but can't seem to get the individual values stored def __str__(self): return self.name def validate_and_split_domain(self): domain = self.domain_name.lower() # make all lower case because django isn't case sensitive values = list(tldextract.extract(domain)) #Split values into a list self.sub_domain, self.domain_name, self.suffix = values[0], values[1], values[2] def save(self, *args, **kwargs): self.validate_and_split_domain() super(Website, self).save(*args, **kwargs) -
Django form update to secondary table(model)
I would like my Django form on 'POST' of results to update my PlayerPoints value to +3 for ALL the players on the winning team. The results model has a:- 'matchdate' field = foreignkey to MatchDaySquadRed or Blue model (which also has my playername field = foriegnkey to Player model), 'winningteam' field foreignkey to Team model, So for each result I should be able to find all the players in the winningteam, then add + 3 to the PlayerPoints model for that player. How do I first retrieve a list of all winning players by joining 3 tables (result, MatchDaySquad, Player). Then with that data update all the players in the PlayerPoints table to + 3 in one go. The models are listed below. Could I have a worked example please. class MatchDay(models.Model): matchdate = models.DateField(primary_key=True) FIVEASIDE = '5' EIGHTASIDE = '8' MATCH_CHOICE = ( (FIVEASIDE, '5-a-side'), (EIGHTASIDE, '8-a-side'), ) matchtype = models.CharField( max_length=10, choices=MATCH_CHOICE, default=FIVEASIDE, ) class MatchDaySquadRed(models.Model): matchdate = models.ForeignKey(MatchDay, null=True, blank=True, on_delete=models.SET_NULL) playername = models.ManyToManyField(Player) teamname = models.ForeignKey(Team, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return '%s' % (self.matchdate) class MatchDaySquadBlue(models.Model): matchdate = models.ForeignKey(MatchDay, null=True, blank=True, on_delete=models.SET_NULL) playername = models.ManyToManyField(Player) teamname = models.ForeignKey(Team, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return … -
Use a file input for a text field?
I have a Django model with a TextField. When I use a ModelForm to collect data to add/edit this model, I get a textarea in the HTML form, but I'd like to use a file input instead. I think what I need to do is to set the widget for this field on my form class using django.forms.FileInput, or maybe a subclass of that input, but it isn't clear to me how to make this work (and I'm not positive this is the right approach). So, how can I use a file input to collect data for a model using a ModelForm? -
How to rank myself as a software engineer?
Working with many software engineers around, How do I rank my self or How do I determine the levels of my skills. -
Using Django, how to count amount of free shelf space using a queryset?
Im developing an inventory management web app that allows teams, within an organisation, to be assigned boxes to store things in. There are multiple storage rooms and multiple shelves and sections. Every box is assigned a project. I would like to write a queryset in Django that shows how many empty spaces there are in a given room (how many locations there are that do not have boxes assigned to them) e.g. for the above picture showing room A Room: A Empty Spaces: 4 Here is a simplified version of my code: HTML: {% for each_space in Room_data %} { <p>"Room": "Room {{each_space.loc_room}}",</p> <p>"Empty Spaces": *** HERE I NEED HELP ***,</p> }, {% endfor %} Model: class Location(models.Model): loc_room = models.CharField() loc_section = models.IntegerField() loc_shelf = models.CharField() class Box(models.Model): box_contents = models.CharField() project_assigned_to = models.ForeignKey() Location = models.OneToOneField() class Project(models.Model): project_name = models.CharField() project_manager = models.ForeignKey() Views: def dashboard(request): Room_data = Location.objects.all() return render(request, 'main_app/dashboard.html' , {"Room_data":Room_data}) I've been stuck on this for a lot of today so I was hoping somebody might know the best direction forward. Thank you in advance. -
Use REMOTE_USER and traditional Django user at the same time
What's the best way to use django.contrib.auth.middleware.PersistentRemoteUserMiddleware with every connected user AND the traditional Django login user system? I understand that I need to keep two authentication backends in settings: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend', # Access via remote_user 'django.contrib.auth.backends.ModelBackend', # If the previus fails, access via model (REQUIRED FOR SUPERADMIN IF USER IS AnonymousUser!!!) ] But how use @login_required decorator properly? I have already read the docs here but they are not useful. -
Didn't working in inclusion tag with API. Did not receive value(s) for the argument(s): 'request'. Django 2.1.5
I want to get weather for cities (with ip and API) and redirect it to base template. I do this with include_tag. But crashes TemplateSyntaxError at /post/ 'city_weather' did not receive value(s) for the argument(s): 'request'. weather.py PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', ) @register.inclusion_tag('post/weather_tpl.html') def city_weather(request): remote_address = request.META.get('REMOTE_ADDR') ip = remote_address x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: proxies = x_forwarded_for.split(',') while (len(proxies) > 0 and proxies[0].startswith(PRIVATE_IPS_PREFIX)): proxies.pop(0) if len(proxies) > 0: ip = proxies[0] reader = geoip2.database.Reader('post/GeoLite2-City_20190108/GeoLite2-City.mmdb') try: city = reader.city(ip).city.name except: city = "London" url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&lang=ru&appid=**********************' city_weather = requests.get(url.format(city)).json() weather = { 'city' : city, 'temperature' : str(city_weather['main']['temp'])+'°C,', 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'] } next = request.META.get('HTTP_REFERER') if next: next = urlunquote(next) if not is_safe_url(url=next, allowed_hosts={request.get_host()}): next = '/' return {'next_page': next, 'city': city, 'weather' : weather } weather.html {{ next }} {{ city }} {{ weather }} base_generic.html ... {% load all_comments %} {% city_weather %} ...