Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: The QuerySet value for an exact lookup must be limited to one result using slicing using django
i am writing a logic that would allow me display all the quizes that a teacher have created from the database, now i want to make this more precise by only showing a student a quiz based on the courses they enrolled in, i am trying to write this filter and it not working as expected models.py Class Course(models.Model): course_creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="quiz_user") course_title = models.CharField(max_length=255) slug = models.SlugField(unique=True) def __str__(self): return self.title class UserCourse(models.Model): user = models.ForeignKey(User , null = False , on_delete=models.CASCADE) course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="usercourse") payment_status = models.CharField(max_length=100, choices=PAYMENT_STATUS, default="pending") date = models.DateTimeField(auto_now_add=True) class Quiz(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="quiz_user") title = models.CharField(max_length=255) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True) def __str__(self): return self.title views.py def StudentQuizList(request): user_course = UserCourse.objects.filter(user=request.user) quizzes = Quiz.objects.filter() context = { # 'user_course': user_course, 'quizzes': quizzes, } return render(request, 'student_dashboard/quiz.html', context) error The QuerySet value for an exact lookup must be limited to one result using slicing. -
how can i persist data on website in django?
i have just started using django and dabbling with front end technologies i wrote a small web app and i want to push this up on a host server. my question is how do i update the website without losing the data in the dblite and user tables? won't i overwrite the db? this concept confuses me a little bit. i understand how this would work if i had a backend app servicing the webaite but this is going to be a website just for me and a few friends and family members. ... -
Validation isn't working for SerializerMethodField
I am working on my Django DRF app. I have two models Organization and BankAccount class Organization(models.Model): ... class BankAccount(models.Model): is_main = models.BooleanField(default=False) # organization should have 1 main account organization = models.ForeignKey( Organization, related_name="accounts", on_delete=models.CASCADE, ) ... I want to validate Organization data Organization must have at least one account with is_main=True but my validation isn't working (it looks like there are no validate_accounts cals. class OrganizationSerializer(serializers.ModelSerializer): accounts = serializers.SerializerMethodField() class Meta: model = Organization fields = '__all__' read_only_fields = ("id",) def get_accounts(self, obj): if obj.accounts is not None: return BankAccountSerializer(obj.accounts, many=True).data return None def validate_accounts(self, value): """ Organization should have account with 'is_main' true """ raise ValueError(value) # Don't see exception in logs if not value: return value for account in value: # check all accounts if account["is_main"] == True: return value raise serializers.ValidationError("Organization should have main account (is_main=true)") Example: For this data I expect validation error: (only one acc with "is_main": false,) "accounts": [ { "id": 1, "is_main": false, "bank_name": "Sber", "bank_bik": "123", "bank_account": "123", "correspondent_account": "312", "organization": 3 }, ] -
How to use mapbox vector tiles in a performant way?
I am a bit confused about Mapbox MVT. As I understood, a tile is a little piece of map, as in a jigsaw puzzle. Not completely sure about the working of MVT. https://docs.mapbox.com/data/tilesets/guides/vector-tiles-introduction/#benefits-of-vector-tiles Here, it says Vector tiles are really small, enabling global high resolution maps, fast map loads, and efficient caching. So the thing is I am trying to get all the coordinates from db which can go up to more than 10K and currently getting the data from postgis using: query = f""" SELECT NULL AS id, ST_AsMVT(q, 'default', 4096, 'mvt_geom') FROM (SELECT "locations"."name", ST_AsMVTGeom(ST_Transform(locations.geom, 3857), ST_TileEnvelope(1, 0, 0), 4096, 0, false) AS mvt_geom FROM locations) AS q; """ with connection.cursor() as cursor: cursor.execute(query) rows = cursor.fetchall() mvt = bytes(rows[-1][-1]) return Response( mvt, content_type="application/vnd.mapbox-vector-tile", status=200 ) Now I am wondering about the performance issues, as everytime a user will visit it will put stress on db. And another problem I am having is when using vector tiles as a source, it calls the source url and (hitting the db) everytime I move the map. type: 'vector', tiles: [ 'http://url/{z}/{x}/{y}.mvt' ] Is it possible to call the source url at a specific zoom level and until then all the … -
django.db.utils.IntegrityError: (1048, "Column 'user_id' cannot be null") in DRF
I have an app and I use django.contrib.auth.models.User as authentication models then I use for serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' # fields = ['first_name', 'last_name', 'email', 'password', 'username'] def validate(self, attrs): if 'name' in attrs.keys(): name = attrs['name'] name = name.split(' ') first_name, last_name = name[0], name[1] attrs['first_name'], attrs['last_name'] = first_name, last_name attrs['password'] = make_password(attrs['password']) return attrs then I use for view set: class UserViewSet(viewsets.ViewSet): permission_classes = (permissions.AllowAny,) # authentication_classes = (TokenAuthentication) ... def create(self, request): # return response.Response(data=request.data) # user = User.objects.filter(username=request.data['username']).exists() # return response.Response(data= user) if User.objects.filter(username=request.data['username']).exists(): serials = UserSerializer( data=request.data, context={'request': request} ) user = None if serials.is_valid(): user = serials.save() else: user = UserSerializer(request.data, many=True) token, created = Token.objects.get_or_create(user=user) return response.Response( data={ 'token': token.key, 'user': UserSerializer(user).data } ) ... And after that I got this error: django.db.utils.IntegrityError: (1048, "Column 'user_id' cannot be null") -
Allow data insertion only after time duration threshold in django
I have a model in Django with a DateTimeField attribute. I want to forbid insertion of new data in the database if the duration between the datetime field of the new data and the latest datetime field in the database is less than some duration threshold. class MyModel(models.Model): time_stamp = models.DateTimeField(default=timezone.now, null=True) When I want to insert a datapoint say today, and the latest time stamp in my database is yesterday, and the duration threshold is one month (this operation should not be possible). -
Django form's redirect me to the wrong URL if the input data is invalid
I am very new to Django and working on a marketplace site. I have a few forms on my main listing page, one for taking bids and another for leaving comments. The bidding form when given a bid that is too low is supposed to redirect the used to the listing page now with an error displayed. What actually happens is that the URL changes and it displays a different view of the same listing page. I'm sure this can be solved easily with JavaScript and ignore the redirect all together, but I'd rather figure out why this is happening then try to work around it. When entering invalid data I expect to be taken back to my current page "listing/product_name", but instead I am taken to "bid/product_name". The same thing happens with the comments form "/comment/product_name", that form doesn't want to validate either. URLS from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("ended", views.ended, name="ended"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("bid/<str:listing>", views.bid, name="bid"), path("register", views.register, name="register"), path("watchlist", views.watchlist, name="watchlist"), path("close/<str:listing>", views.close, name="close"), path("newListing", views.newListing, name="newListing"), path("listing/<str:listing>", views.listing, name="listing"), path("comment/<str:listing>", views.comment, name="comment"), path("change_watchlist/<str:listing>", views.change_watchlist, name="change_watchlist"), ] views.py I know there is some messiness … -
How i can show image from database to page. Django
i have media directory in my project, and i can't take image from it. When i try getting image, then i got this Request URL:http://127.0.0.1:8000/auto/media/img/'MyImg'.jpg and obviously it can't work, so how can i do this? while doing this i am trying to get data in html like this {% for item in auto %} <div> <p>{{item.name}}</p> <p>{{item.info}}</p> <p>{{item.description}}</p> <img src="media/{{item.photo}}"> </div> <hr> {% endfor %} -
Django Forms: Validation forms error when apply two validations
I have a form with 'start=forms.DateInput', end=forms.DateInput and active=forms.CheckboxInput, but when I try to validate this fields, I have these errors. KeyError at /employee/edit/70000007/ 'end' ... if form.is_valid(): ... end = self.cleaned_data['end'] But this works fine when apply only one validator. def clean_end(self): start = self.cleaned_data['start'] end = self.cleaned_data['end'] if end < start: raise forms.ValidationError('end date cannot be less than start date.') return end def clean_active(self): active = self.cleaned_data['active'] end = self.cleaned_data['end'] if active and end: raise forms.ValidationError('active employee should cannot be end date') return active Thanks for your help. -
Django Error: maximum recursion depth exceeded while calling a Python object
enter image description hereI am trying to view the page in my browser but could not because of this error despite trying all sort of methods. I have tried different ways to solving it. Please anyone could try and help. Thank you -
Is there any GCash API for Django Web Apps
I want to integrate a Gcash API for the payments of the user in my ecommerce website -
Using a model to get the fields for another model
I have one model to define the fields in my system class MetadataField(models.Model): FIELD_TYPE = ( ('TXT', "Text"), ('CB', 'Checkbox'), ('DD', 'DropDown') ) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) title = models.CharField(max_length=100) type = models.CharField(max_length=200, choices=FIELD_TYPE, default='TXT') workflow = models.ManyToManyField('Workflow') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Each field is associated with a workflow. Here is my workflow model class Workflow(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) name = models.CharField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name I have a project model. class Project(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) title = models.CharField(max_length=100) workflow = models.ManyToManyField('Workflow') created_on = models.DateTimeField(auto_now_add=True) Now say there are 4 projects. Each project is associated with a workflow Project 1 : Workflow 1 Project 2 : Workflow 1 Project 3 : Workflow 2 Project 4 : Workflow 3 I want each project to have it's information (metadata). The metadata fields for every project should come from the fields created (in field model) for the associated workflow. It is like a form where the relevant fields are coming from the created fields and user can enter the value for each of those fields. How do I write a model to store this metadata? Will I have to … -
Django Using iex api from via model field
Hello so i will post my code, because I hope it explains my situation better than i can do :) Im struggeling with the views.py part because i dont know how I can use an argument for the iexcloud_watchlist. So if sb can explain how I am able to connect my api.py iexcloud_watchlist and watchlist_one from views.py correctly, I would be very thankful. I tried it with ticker = iexcloud_watchlist(query) , but thats not working bc it gave me the error watchlist_one() missing 1 required positional argument: 'ticker' models.py from django.db import models from django.contrib.auth.models import User class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20, unique=True) description = models.CharField(max_length=50, null=True) updated = models.DateTimeField(auto_now=True) ticker = models.CharField(max_length=10, default='') def __unicode__(self): return str(self) api.py import requests def iexcloud_watchlist(ticker): response = requests.get(f'https://cloud.iexapis.com/stable/stock/{ticker}/quote? displayPercent=true&token=mytoken') try: return response.json() except Exception as e: e = "Error" views.py def watchlist_one(request, pk, ticker): Watchlist.objects.get(id=pk) model = Watchlist.objects query = model.all().values_list('ticker', flat=True) ticker = iexcloud_watchlist(query) context = { 'list_ticker':query, 'ticker':ticker, } return render(request, 'App1/watchlist_one.html', context) -
Loop through Django context values
How do I render a context value as a key-value list in template? def random_view(request): my_context = { "name": "turkey", "fly": "no", "run": 20 } return render(request, 'test/test.html', my_context) If this is the views the views then how can I loop through the values and render a list in test.html using a loop? -
How to use "has_object_permission" to check post request before saving to database?
How can I use a condition like this to validate data before it is written to the database? I am using django rest framework class WarehouseIsMemberOfCompany(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return True return False def has_object_permission(self, request, view, obj): if request.user.company.id == obj.warehouse.company.id: return True return False -
How can I calculate Position based on another field of Django model instances?
I have a Django model that looks like this: class Image(models.Model): name = models.CharField(max_length=60) description = models.CharField(max_length=60, null=False) clicks = models.IntegerField(default=0) views = models.IntegerField(default=0) @property def weight(self) -> float: return round((self.clicks * 0.7 + self.views * 0.3), 2) Based on weight, I'd like to estimate a position field of Image. It should give a position based on weight of all instances of Image. The higher the weight, the higher the position (position 1 - highest weight, position 2 - second highest, etc.) How can I create a function that would take ALL the Image instances I have in the DB and calculate position for all of them? -
organizations.OrganizationGroups has no ForeignKey to 'auth.User'
The following exception has been appearing randomly in my Django admin installation. OrganizationGroups does not have a ForeignKey to auth.User. This exception is also appearing in different apps of the system, and it is always organizations.OrganizationGroups has no ForeignKey to 'app.Model' I'm currently running: Django Version: 3.2.13 Python Version: 3.9.2 OrganizationGroups model: class OrganizationGroups(models.Model): id = models.BigAutoField(primary_key=True) organization = models.ForeignKey( Organization, models.DO_NOTHING, null=True, blank=True ) group = models.ForeignKey(Group, models.CASCADE, blank=True, null=True) class Meta: db_table = 'organization_groups' unique_together = (('organization', 'group'),) def __str__(self) -> str: return self.organization.name Traceback (most recent call last): File “/usr/local/lib/python3.9/dist-packages/django/core/handlers/exception.py”, line 47, in inner response = get_response(request) File “/usr/local/lib/python3.9/dist-packages/django/core/handlers/base.py”, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/options.py”, line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/utils/decorators.py”, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/views/decorators/cache.py”, line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/sites.py”, line 232, in inner return view(request, *args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/options.py”, line 1660, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File “/usr/local/lib/python3.9/dist-packages/django/utils/decorators.py”, line 43, in _wrapper return bound_method(*args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/utils/decorators.py”, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/options.py”, line 1540, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File “/usr/local/lib/python3.9/dist-packages/django/contrib/admin/options.py”, line 1604, in _changeform_view … -
How to get the value within the a tag
<td> <a href="/Codes/A">'A' Codes</a> </td> <td> <a href="/Codes/B">'B' Codes</a> </td> <td> <a href="/Codes/C">'C' Codes</a> </td> I want to get the values A, B, and C from the tag -
Set default value Django Models
I need to set a date to Enddate if the user didn't enter it by taking the value from Starting input, Let's say I have this Model: class DataSet(models.Model): Event = models.CharField(max_length=50,blank=True ,null=True) Starting = models.DateField() Enddate = models.DateField(blank=True ,null=True) Times = models.PositiveIntegerField(max_length=4,blank=True ,null=True) postdate = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.Stating class Meta: ordering = ('-Enddate',) and the form is; class DataSet_F(forms.ModelForm): Event = forms.CharField(label='Event') Starting = forms.DateField(label='Start date',widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'})) Enddate = forms.DateField(label='End date',required =False,widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'})) Times = forms.IntegerField(label='Time',required =False) class Meta: model= DataSet fields=['Event','Starting','Enddate','Times'] How I set Enddate equal to Starting when the user didn't enter the value, then set Times equal to 1. Many thanks -
Nginx is showing 400 Bad Request No required SSL certificate was sent
I'm trying to establish SSL connection and I'm getting 400 No required SSL certificate was sent response from the server. I used this tutorial for it I tried everything to solve this issue, but it seems that there is something wrong with the cloudflare certificate because when I disable ssl_verify_client it is working (with security alert). Here is my nginx configuration: server { listen 443 ssl http2; listen [::]:443 ssl http2; ssl_certificate /etc/ssl/cert.pem; ssl_certificate_key /etc/ssl/key.pem; ssl_client_certificate /etc/ssl/cloudflare.crt; ssl_verify_client on; server_name example.com www.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/www/exampleproject; } location /media/ { root /home/username/www/exampleproject; } location / { include proxy_params; proxy_pass http://unix:/home/username/www/exampleproject/exampleproject.sock; } } -
Formatting Django forms elements in html templates
I have a contact form that I'm trying to use in one of my Django templates. I created a class for it in forms.py: class ContactForm(forms.Form): name = forms.CharField(max_length=100) email_address = forms.EmailField(max_length=150) message = forms.CharField(widget = forms.Textarea,max_length=2000) and added it to my views.py: def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Website Inquiry" body = { 'name': form.cleaned_data['name'], 'email': form.cleaned_data['email_address'], 'message':form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, 'admin@example.com', ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ("BobbleHead:home") form = ContactForm() return render(request, "BobbleHead/contact.html", {'form':form}) and am now trying to get the form to render with specific html formatting in my template (contact.html), but am having difficulties. Previously, I was using the built in Django capabilities to render, like this: <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> That worked fine, but I don't like the way it looks on my webpage and wanted to clean up the formatting. I want the form to render with specific formatting, like this: <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <div class="w3-col m6"> <form action="/home" target="_blank"> {% csrf_token %} <div class="w3-row-padding" style="margin:0 -16px 8px -16px"> <div class="w3-half"> <div class="fieldWrapper"> <input class="w3-input w3-border" type="text" placeholder="Name" required name="name"> </div> … -
Best Django method for multiple entries for the same field
A huge hello to the community! I am trying to figure out the best method to add multiple instances of the same field for a Recipe class I have created. When creating the new Recipe, I need to be able to add multiple instances of Ingredient, Measurement Unit, Unit Value. For example: ingredient = Lemon measurement_unit = ml unit_value = 100 I would then need to add another Ingredient and do the exact same thing. I would then be able to save the Recipe. What would be the best method to use to achieve this? -
Page Number and Total Pages in Header When Printing HTML to PDF
Background: I have a large HTML file that has 8 different pages. Some of the pages in the HTML can be larger than the 11in container size and the 11in stipulated in the @page CSS due to a lot of data in some of the tables. What am I trying to do?: I am trying to send in context data (written in Django / Python) to each table of unknown length. Once the data has been entered then I will use weasyprint to create the pdf. At the top of every page the page number and total number of pages should be added dynamically. The issue: When I print to PDF the header on the pages with a lot of rows (ones that are >11in) add the header but the header shows the same page number for of the split pages. In the example below it is on page 2 that is split into two pages and when you print to pdf the header on page 3 and 4 are incorrect. What have I tried?: Basically everything I could think of. At first I thought about just using paged media but I couldn't figure out how to put this complex … -
How to implement a database for storing parentId and a list of children?
I need to implement a POST request with data loading via two keys: "items" and "UpdateDate". But in the database with items it is necessary to store the parent (parentId) of the category /product and a list of children (children). and record the time from the "UpdateDate" key in the date field for all categories/products imported for this request The screenshots below show a detailed TT. I haven't been able to figure out how to implement a database on Django/Django Rest Framework for a week. Screens: class ShopUnit(models.Model): id = models.UUIDField(primary_key=True, verbose_name='Unique identifier', default=uuid.uuid4, editable=False, null=False) name = models.CharField(max_length=255, verbose_name='Category/Product name', null=False) date = models.ForeignKey('Date', on_delete=models.CASCADE, related_name='date', null=True, blank=True) parentId = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='сhilden', db_index=True) type = models.CharField(max_length=10, verbose_name='Element Type', choices=ShopUnitType.choices) price = models.PositiveIntegerField(null=True, blank=True, verbose_name='Цена') children = models.ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL, related_name='parent') There are small developments: https://i.stack.imgur.com/GdAaK.png https://i.stack.imgur.com/fzBdS.png https://i.stack.imgur.com/LRQIq.png https://i.stack.imgur.com/tssis.png -
I'm usin django allauth for authentication. I can't find iun the website the list of error returned by the framework
I want for example know all type of error that can be returned by allauth, where can I find this list please ? like this one : "non_field_errors": [ "Unable to log in with provided credentials." ]