Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django, prefetch_related select_related for ForeignKey
There are two models: class Batch(models.Model): name = models.CharField(max_length=150) class Stage(models.Model): batch = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="stages") feild_1 = models.SmallInteterField(default=0) View: class BatchWiew(ListWiew): model = Batch template_name = index.html def get_context_data(self, **kwargs): context = super().get_context_data() context['batches'] = Batch.objects.?????????????????? index.html {% for batch in batches %} {{ batch.stages.last }} {% endfor %} 'last' in the block {{ batch.stages.last }} creates an additional query to the database for everyone 'batch'. How to immediately take the necessary data from the database to context['batches'] = Batch.objects.?????????????????? tried different options with prefetch_related, select_related it doesn't work -
Django – filter all products that have only empty variations
as the title says I'm trying to filter out all Products where all variations have a stock_quantity of 0. The variations are a separate class with a foreignkey to the Product. The related_name is set to 'variations'. Here is my attempt: Product.objects.annotate(variations_count=Count('variations')).filter(variations__stock_quantity=0) However, it seems that filters out all variations where at least one variation has a stock quantity of 0, not all of them. How can I solve this? Thanks! -
Django Templates - Add Selection boxes for Search Results
Not sure how to begin programming a change to my results template/screen... I have a search that users can use, it returns results from two related models with pagination. This works fine. Users wondered if I could add a selection box for each returned entry. If they selected 1 or more entries - then they could then push an export button, and all selected entries would be saved into a file with all fields listed in csv format. The more I think about it I think I would need a completely different results template without pagination, just because I need to pass the query set to something to print this out, but only want the ones that were selected... Anyone done anything like this? Not really sure if any will have an answer but figured I would put it out there. Thanks. -
Periodically and automatically create objects in Django
I am looking for a way to automatically and periodically (once per week) create objects in Django. The model looks like this: class SettingsWeekly(models.Model): year = models.IntegerField() week_number = models.IntegerField() fuel_cost = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) miles_per_galon = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) week_start = models.DateField() week_end = models.DateField() The idea is to have a new object each week with the current year, week number and some fields that will have values added after the object is automatically created. Thanks! I can get the current year and week_number, but how do I go about automatically creating objects once per week? -
Auth0 react native gives invalid tokens
I am developing an application with a React Native application and a Django Rest Framework backend. Now, when users are authenticated in React Native, and I use the getCredentials() function from the useAuth0() hook, I get an accessToken and an idToken. However, both of these tokens are unable to authenticate in the Django REST framework application, returning the following: { "detail": "Invalid token." } I followed this tutorial to integrate Auth0 with django. Maybe this has something to do with the fact that the Django api is registered as an API in Auth0 and that it has an identifier? Because this identifier is nowhere mentioned in the React native client. Any help/insights are appreciated. -
Django Admin Button: How to pass values from many-to-many through a button to a function?
New to programming, Python, and Django. I've written a standalone function that works well enough that generates a schedule for a tennis doubles league using a list of players, the number of courts available, and a duration, which right now I just print out as a CSV and send out to the league. My goal is to create an admin portal that generates the schedule based on league and player information created in an admin portal and ultimately have that schedule stored in a SQL db and ultimately accessed via a public portal. My immediate issue is that I'm unable to figure out how to pass (or print for that matter) the list of players in my league session. Additionally, I'm not sure exactly how to pass the required information from my admin site through the button to my function. Here's a screenshot of my LeagueSession admin page: As you can see, I've created a button and am printing some of the data I need. I can't get the playersinsession to print. Ultimately I need to pass this as a list, I think. So while printing this list would be a great start, I also need help with passing all … -
Implementing an agent in python/django
I would like to implement an agent with django / python which will interact with an external database, this agent will have to collect the data from the external database and will save it on the database of my application. Need help I need information about its implementation please, or a sample code. -
Django url template tag ovrwrite the last letter of the base address
When using the URL template tag I checked the source code of the html page and the url appears missing the last letter of the base address, see an example: ... <li><a href="{% url 'produtct' %}">Produtcts</a></li> ... returns ... <li><a href="/dec/produtct/">Produtcts</a></li> ... but the the base address is my-site.com/deck ... so, why dont returns ... <li><a href="/deck/produtct/">Produtcts</a></li> ... I checked my settings.py and urls.py and didn't see anything wrong, I don't know where else to look -
Atomic block django [closed]
Preciso desenvolver uma rotina no python utilizando django, onde, vou ter um block atomico que nele será efetuado algumas operações no banco e dentre elas, a criação de um registro especifico em uma determinada tabela no banco de dados que, se ocorrer qualquer erro nessa rotina, quero fazer o rollback de tudo menos da criação deste registro em especifico. Exemplo: def function_teste: with transaction.atomic(): obj_a.save() obj_b.save() with transaction.atomi(): obj_c.save() obj_d.save() raise #Neste ponto, ao gerar a exceção quero fazer o rollback apenas dos regisotr a, b, d. O re Obs.: Não consigo incluir um tratamento de excção dentro da function_teste para tratar a exceção e trabalhar com save points ou algo do tipo, pois, esse exmplo está bem simplicado. E na prática o que vai acontecer é que dentro da fuction_teste eu irei chamar diversas rotinas encadeadas que dentro dela vai ter a criação desse registro c e, quando o fluxo retornar para o método externo (function_teste) e ai ocorrer qualquer raise, eu preciso fazer rollback de tudo menos do registro c. O que quero implementar seria a mesma ideia de ter um autonomous transaction do oracle. Onde tenho uma transação e dentro dela cosigo fazer o commit de um … -
Django form widget - Add suffix while keeping the NumberInput
I have a form input on body height. I would like to put 'cm' after the height number (e.g. 183cm instead of just selecting 183) but keep it as a NumberInput. Is it possible to add the suffix in the widget? I have the following form.py: from django import forms from .models import Account class RegistrationForm(forms.ModelForm): body_height = forms.NumberInput(attrs={'min':120,'max':230,'step':1, 'required':False,}) class Meta: model = Account fields = ['body_height','otherfields'] def __init__(self, *args, **kwargs): self.fields['body_height'].widget.attrs['placeholder'] = 'Your height (centimeters)' -
How to assign default value of the model based on the value of ForeignKey
I have the Account model were I store information about preferred units. However I also want to allow user to change the units for particular exercise which by default should be Account.units. Here are my models: class Account(models.Model): """Model to store user's data and preferences.""" UNIT_CHOICES = [ ('metric', 'Metric'), ('imperial', 'Imperial') ] uuid = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=False) units = models.CharField(max_length=255, choices=UNIT_CHOICES, default=UNIT_CHOICES[0], null=False, blank=False) weight_metric = models.FloatField(null=True, blank=True) height_metric = models.FloatField(null=True, blank=True) weight_imperial = models.FloatField(null=True, blank=True) height_imperial = models.FloatField(null=True, blank=True) def __str__(self): return self.owner.email class CustomExercise(models.Model): UNIT_CHOICES = [ ('metric', 'Metric'), ('imperial', 'Imperial') ] uuid = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False) preferred_units = models.CharField(max_length=255, choices=UNIT_CHOICES, default=owner.units, null=False, blank=False) # <- throws an error that "ForeignKey doesn't have units attribute." name = models.CharField(max_length=255, null=False, blank=False) measure_time = models.BooleanField(default=False) measure_distance = models.BooleanField(default=False) measure_weight = models.BooleanField(default=False) measure_reps = models.BooleanField(default=False) def __str__(self): return f'{self.owner}:{self.name}' As posted in code sample I tried to get that default value from ForeignKey, which not unexpectedly did not work out. So my question is: what is the correct solution to implement this kind of feature? -
VsCode not Auto-importing Django depenencies
I'm learning Django and working with VsCode. In PyCharm, the imports are working fine. PyCharm importing However in VsCode: VsCode importing Is VsCode just not capable of this? Or is there something iffy with my configuration? I have the correct Python interpreter configured as well. I have Pylance installed and it suggests imports automatically for some other things, rather unhelpfully usually. e.g., VsCode importing unhelpful I have tried settings some options in settings.json. The python.analysis.extraPaths adding the path to django on the Python installation. I have tried python.analysis.indexing set to true as well. I haven't found any other solutions. -
Django APIView: how to display calculated value
I have to display a calculated value in APIVIEW, but I can't figure out how to set up the view, it's giving me an error. The code, that returns a simple JSON is working fine: def protein_coverage(request, protein_id): try: proteins = Protein.objects.filter(protein=protein_id) domain_length = 0 coverage = domain_length / protein_length except Protein.DoesNotExist: return HttpResponse({'message': 'This Protein does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ProteinCoverageSerializer(coverage) return JsonResponse(serializer.data,safe=False) I tried this for the APIView: class ProteinCoverage(generics.RetrieveAPIView): serializer_class = ProteinCoverageSerializer def get_queryset(self): pk = self.kwargs['protein_id'] proteins = Protein.objects.filter(protein=pk) domain_length = 0 coverage = domain_length / protein_length return coverage But it's giving me an error: Expected view ProteinCoverage to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I'm not sure, which API is suitable for this situation and how to pass a single variable to it. I also checked the documentation, but it's not clear. How do I convert this JsonResponse to APIView? -
Making Password First name in signup page in Django [closed]
Is there a way to not show password in the signup page and make the password the first name by default in Django and they will be able to login with that default password which is there first name I tried using the AbstractBaseUser But it did not Work -
Create multiple model instances upon creation of another model
What I am trying to achieve is the following: The user searches for a keyword in a form. The search query is saved in a model called TweetSearch. When the search is submitted a function get_tweets() will be run which scrapes tweets with the keyword that the user submitted. These tweets must be saved in a model called TweetInstance. Then some data from TweetInstance is shown in a dashboard. I don't know how to create instances of multiple models in one view, so I added a view in between the searchform and the dashboard that runs the function get_tweets() and adds them to the database. This does not work well and there must be a better way to do this. Can anyone help me? I tried the following: models.py: class TweetSearch(models.Model): from datetime import datetime, timedelta search_term = models.CharField(max_length=200, blank=True) QUERY_CHOICES = ( ('t', 'in tweet'), ('h', 'in hashtag'), ('u', 'username'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4) query_type = models.CharField(max_length=1, choices=QUERY_CHOICES, blank=True, default='t') start_default = datetime.now() - timedelta(days=30) start_date = models.DateTimeField(default=start_default) end_date = models.DateTimeField(default=datetime.now) language = models.CharField(max_length=200, blank=True, null=True) country = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) searcher = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): … -
Websockets won't work on docker with nginx
I have a problem with a real-time chat application on Django. The websockets won't work on nginx server. Am I missing something? The app only says: /ws/socket-server/ not found nginx.conf upstream project { server web:8000; } server { listen 80; location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles/; } #path to proxy my WebSocket requests location /ws/socket-server/ { proxy_pass http://project; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $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-Host $server_name; } } asgi.py """ ASGI config for project project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import scrumboard.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( scrumboard.routing.websocket_urlpatterns ) ) }) settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. from django.template.context_processors import media BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ SECRET_KEY = os.environ.get("SECRET_KEY") DEBUG = int(os.environ.get("DEBUG", default=0)) # 'DJANGO_ALLOWED_HOSTS' should be … -
Building wheel for lxml (setup.py): finished with status 'error'
I have this error while running docker Everything works in server but locally lxml finishes with this error: #0 55.92 Stored in directory: /root/.cache/pip/wheels/02/f8/c2/4a8e9dce6caefe8931213e951f7d1b19e6a7d86fc2becc228e #0 55.92 Building wheel for lxml (setup.py): started #0 57.58 Building wheel for lxml (setup.py): finished with status 'error' #0 57.60 error: subprocess-exited-with-error #0 57.60 #0 57.60 × python setup.py bdist_wheel did not run successfully. #0 57.60 │ exit code: 1 #0 57.60 ╰─> [88 lines of output] #0 57.60 Building lxml version 4.6.3. #0 57.60 Building without Cython. #0 57.60 Building against libxml2 2.9.10 and libxslt 1.1.34 #0 57.60 running bdist_wheel #0 57.60 running build #0 57.60 running build_py #0 57.60 creating build #0 57.60 creating build/lib.linux-x86_64-cpython-311 #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/sax.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/doctestcompare.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/pyclasslookup.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/ElementInclude.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/cssselect.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/_elementpath.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/builder.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/usedoctest.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml/includes #0 57.60 copying src/lxml/includes/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/includes #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/_setmixin.py -> build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/_diffcommand.py -> build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/diff.py … -
get the id of a related field and save data
I'm kinda new to DRF, I am building a database for attendance. I want to save an instance of AttendanceSlot in my Attendance but I don't know how to get id, so i can save it... models.py class AttendanceSlot(models.Model): department_id = models.ForeignKey("students.Department", verbose_name=_("department id"), on_delete=models.CASCADE) course_id = models.ForeignKey("students.Course", verbose_name=_("course id"), related_name= 'course', on_delete=models.CASCADE) lecturer_id = models.ForeignKey("lecturers.Lecturer", on_delete=models.CASCADE) date = models.DateField(_("attendance date"), auto_now=False, auto_now_add=True) start_time = models.TimeField(_("start time"), auto_now=False, auto_now_add=False) end_time = models.TimeField(auto_now=False, auto_now_add=False) longitude = models.CharField(_("longitude"), max_length=50) latitude = models.CharField(_("latitude"), max_length=50) radius = models.CharField(_("radius"), max_length=50) def __str__(self): return '{0}'.format(self.course_id.course_code) class Attendance(models.Model): slot_id = models.ForeignKey("attendance.AttendanceSlot", verbose_name=_("attendance slot"), on_delete=models.CASCADE) student_id = models.ForeignKey("students.Student", on_delete=models.CASCADE) performance = models.CharField(max_length=50) serializers.py class AttendanceSerializer(serializers.ModelSerializer): # student_id = serializers.SlugField(read_only=True) slot_id = serializers.PrimaryKeyRelatedField(queryset=AttendanceSlot.objects.all(), many=False) class Meta: model = Attendance fields = ['student_id', 'slot_id', 'performance'] views.py class Attendance(ListCreateAPIView): queryset = Attendance.objects.all() serializer_class = AttendanceSerializer def get_queryset(self, *args, **kwargs): id = self.kwargs['pk'] slot = AttendanceSlot.objects.get(id=id) return slot def perform_create(self, serializer): serializer.save(user = self.request.user, slot_id=self.get_queryset()) return super().perform_create(serializer) urls.py path('<int:pk>/', views.Attendance.as_view(), name='attendance'), -
Django - Storing user info sessions vs database
In my django website I have a login system which uses sessions to keep the user logged in across all pages. I would like to store recently viewed items for users if they are logged in or browsing as a guest user. When a user is logged in I would like the user to see their recently viewed items even when they access my website on another device. I understand that if a user is browsing as a guest recently viewed items would be stored locally in the browser. Would i need to store recently viewed items in a database so that it can be accessed and displayed on other devices. Or is there a way to achieve this with the use of sessions. example of request.session dict { "user_id":-1, # (-1), flag value when no user is logged in (browsing as guest) "recently-viewed":['sw0001a','sw0036a',...], "login_attempts":2, } -
serve Static Files and Media Files of Django app in Production using NGINX
The project works correctly, but I get a 404 error when reading static files! my settings.py: STATIC_URL = 'static/' STATIC_ROOT = '/home/static' MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') nginx.conf: user www-data; worker_processes 1; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; upstream main { server 127.0.0.1:8000; } server { listen 80; server_name localhost; charset utf-8; location /static/ { alias /home/static; } location / { proxy_pass http://main; } } } I`m not using gunicorn. are my settings wrong? -
I have a django website hosted on heroku so I want to setup site to site vpn connection between fortgate vpn. My site and another site. How?
I have a djano app hosted on heroku an I want it to exchange data with another site that is using Fortigate vpn. So I am required to setup my vpn connection to my site but heroku's private space and shiel are to expensive for me. Please help. I could find any vpn that is easy to configure its all complex. -
Django - Disable editing via view button
I am making a customer portal on django and on the admin panel i have created a list for all the users in the database. Apart from that i have also added 3 buttons in my table to View, Edit and Delete as shown: Now the problem is that when i click edit or delete button the code runs as it is intended to do. But when i click the view button it still allows the person to modify the details. I only want to use it as read-only. Can someone please help? This is my admin.py from django.contrib import admin from .models import Customer from .forms import CustomerForm from django.http import HttpResponse from django.utils.html import format_html # Write your models here class CustomerAdmin(admin.ModelAdmin): form=CustomerForm list_display = ['id','first_name','last_name','profile_picture', 'gender', 'date_of_birth', 'email', 'phone_number', 'address', 'marry_status','country','state','city','view_button', 'edit_button', 'delete_button'] list_display_links = ['id'] ordering = ('id',) def view_button(self, obj): return format_html('<a class="button" style="background-color: darkgreen;" " href="/admin/customer_form/customer/{}/">View</a>'.format(obj.id)) view_button.allow_tags = True view_button.short_description = 'View' def edit_button(self, obj): return format_html ('<a class="button" style="color: black; background-color: yellow;" href="/admin/customer_form/customer/{}/change/">Edit</a>'.format(obj.id)) edit_button.allow_tags = True edit_button.short_description = 'Edit' def delete_button(self, obj): return format_html('<a class="button" style="background-color: #ba2121;" href="/admin/customer_form/customer/{}/delete/">Delete</a>'.format(obj.id)) delete_button.allow_tags = True delete_button.short_description = 'Delete' admin.site.register(Customer, CustomerAdmin) -
No reverse match at /create Reverse for 'employees-list' not found. 'employees-list' is not a valid view function or pattern name
Reverse for 'employees-list' not found. 'employees-list' is not a valid view function or pattern name. im getting the error like this what can i do plz any one resolve thisenter image description here getting like want to redirect to the employees-list ... -
User object has no attribute 'code', when code is not passed to User.objects.create
Im using Django Rest Framework to create a view that verifies an otp. Currently, it works just fine. models.py class User(AbstractUser): phone_number = PhoneNumberField(blank=True) def __str__(self) -> str: return f"{self.username}" views.py class VerifyOTPCode(APIView): permission_classes=[AllowAny] def post(self, request): serializer = UserOTPCodeSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response(serializer.errors) serializers.py class UserOTPCodeSerializer(serializers.ModelSerializer): code = serializers.IntegerField() class Meta: model = User fields = ("first_name", "last_name", "email", "phone_number", "code") def validate(self, data): code, phone_number = str(data['code']), data['phone_number'] if is_six_digits(code) and is_otp_approved(code, phone_number): return data raise serializers.ValidationError('Code was not approved') def create(self, validated_data): del validated_data['code'] return User.objects.create(**validated_data) However, I want to use a generic for the view instead, so I tried refactoring it into the following views.py class VerifyOTPCode(generics.CreateAPIView): permission_classes= [AllowAny] serializer_class= UserOTPCodeSerializer Now, when I try to hit the endpoint, I get an error at create, that the User object has no attribute code, even though create removes code from validated_data, and another thing is that even with the error, a User object still does get created. Why is this error occurring and how can I fix it? Internal Server Error: /user/register/verify-otp/ Traceback (most recent call last): File "C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py", line 97, in … -
django rest framework serializer raising invalid errors
class AdvanceSearchSerializer(serializers.Serializer): all_of_these_words = serializers.CharField(allow_null=True, required=False) this_exact_phase = serializers.CharField(allow_null=True, required=False) any_of_these_words = serializers.CharField(allow_null=True, required=False) class myclass(viewsets.Viewsets): serializer = AdvanceSearchSerializer(data = request.data) it works fine. for now im passing data from post request in postman as form-data but when I change it to raw and wih json format it raising the below errors. show that this field is required even though i have set it to null true. { "response": false, "return_code": "field_error", "result": [], "message": { "all_of_these_words": [ "This field may not be blank." ], "this_exact_phase": [ "This field may not be blank." ], "any_of_these_words": [ "This field may not be blank." ] } }