Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prevent Django converting python's datetime.datetime.now() to UTC
My timezone is 'America/Mexico_City' or GMT-6. In my django project I have a model called "Itinerary" which stores two fields called "visit_date" and "add_date", both of type DateTime. With "add_date" I have no problem since it is "auto_now" and is marked as non-editable, so I'm fine with it storing the time in UTC. With "visit_date" is where the problems appears, the client only sends the time of his visit, as the server automatically creates the itinerary for tomorrow: import datetime import pytz from django.utils.timezone import get_current_timezone def some_view(...): some stuff my_tz=pytz.timezone('America/Mexico_City') day = datetime.datetime.now(tzinfo=my_tz).date() + datetime.timedelta(days=1) Then it is combined with time send by client: time=datetime.datetime.strptime(request.POST['time'], r'%H:%M') new_date=get_current_timezone().localize(datetime.datetime.combine(day, time, tz=my_tz)) Itineray.objects.create(...other fields, visit_date=new_date) I'm calling django built in function localize because if not, then a "naive date" error is thrown. I'm not concerned about timestamp for "visit_date", I only need that the date remains the same according to my timezone because when time becomes 18:00 in real life, stored date turns into an extra day. i.e: actual date is 2021-01-01 + 1 day (which is my desired behavior) = 2021-01-02 and then client chosen time. With 18:00 in real life the resulting date is 2021-01-03 then client chosen time. These … -
Django - Repeated variable in path when redirecting
I'm trying to redirect my project to a different page in case there is a validation error, but for some reason, I get the variables twice. context = { "job": Job.objects.get(id=job_id) } return render(request, "trip.html", context) def update(request, job_id): errors = Job.objects.helper_validator(request.POST) print(errors) if len(errors) > 0: for key, value in errors.items(): messages.error(request, value) return redirect(f'dashboard/{job_id}/update') else: job = Job.objects.get(id=job_id) job.title = request.POST["title"] job.desc = request.POST["desc"] job.location = request.POST["location"] job.save() return redirect("/dashboard/") path('dashboard/<int:job_id>/update', views.update), the error: The current path, dashboard/5/dashboard/5/update, didn't match any of these. -
Race condition get model in django
My question is simple, I want to avoid that 2 users get the same token, imagine I have from 50 available tokens only 1, and 2 users at the same time request for the final token (AT THE SAME TIME), then I suppose this code is going to get the same available token for both: Token.objects.get(sent = False) This SHOULDNT happen, how can I avoid this type of race conditions in django? -
Django, Nginx, Uwsgi 502 Bad Gateway error
I am trying to run my Django app using Nginx. When I run uwsgi --http :8000 --module ubergfapi.wsgi everything works, but when I running uwsgi --socket uwsgi_nginx.sock --module ubergfapi.wsgi --chmod-socket=666 I got 502 Bad Gateway when I request my_domain:8000. nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful sudo tail -30 /var/log/nginx/error.log Nginx.conf ser nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*.conf; server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /404.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } the symlink nginx config # the upstream component nginx needs to connect to upstream django { server unix:///root/ubergf/client/uwsgi_nginx.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of … -
which language is better for backend services?
I am a Front-end mobile app developer, now i know basics of JS but i dont know OOP in JS and reactive programming in JS , so the thing is that i now want to learn Back-end development to create my own rest api's. i have two choices PYTHON and JS, if i go for js that will be good because i know that Node.js is way more faster than Django, but if i go for PYTHON i can than easily do other stuff like ML and Game dev. stuff like that. also i will join my Computer science in few in future. so what should i do. Thank you. -
How to convert a dynamic website to an android app.?
I have a dynamic website build using Django framework MySQL as the database. I need to an android app for my website. I want to know if converting the website to an app is a good solution. Can you please list the trade offs in this method? -
django.db.utils.ProgrammingError: relation "subscriptions_plan" does not exist
I am trying to create a Plan instance using the django admin & shell. I am trying to make a Subscription model. The Plan model have multiple services throught a PlanService model. But something is wrong... Could you help to find it out? Help me to improve the models Console error: >>> p1 = Plan(code='PR', description='Premium', price=60000, tax=0) >>> p1.save() Traceback (most recent call last): File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "subscriptions_plan" does not exist LINE 1: UPDATE "subscriptions_plan" SET "status" = '(''Activo'', ''A... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/models/base.py", line 782, in save_base updated = self._save_table( File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/models/base.py", line 864, in _save_table updated = self._do_update(base_qs, using, pk_val, values, update_fields, File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/models/base.py", line 917, in _do_update return filtered._update(values) > 0 File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/models/query.py", line 771, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1500, in execute_sql cursor = super().execute_sql(result_type) File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1152, in execute_sql cursor.execute(sql, params) File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/xmedinavei/Desktop/version_project/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line … -
How to resolve error 404 on Django admin POST?
I have set up a Django app on Cpanel, and everything works great, except adding to models on the admin. When I send a post request on the main page, it works just fine, but from the admin page it keeps throwing Page not found (404) Request Method: POST Request URL: [HOST_URL]/admin/[app]/[model]/add/ Raised by: django.contrib.admin.options.add_view Said models contains an Image field. I have tried both AWS file storage and using dj-static, to no avail. Everything worked great when the site was running on Heroku, I don't know what to do -
Django strict checking for aware timestamps
In Django, if you have USE_TZ = True and pass a naive datetime to a database call, it logs the error: DateTimeField Model.field received a naive datetime (2021-01-01 00:00:00) while time zone support is active. However, Django goes ahead and does the operation anyway, assuming the system timezone. Is there any way to do stricter checking? Is there a setting so that Django will raise an exception rather than just logging a warning? -
Django How to search if field is ForeignKey?
Good day SO: So I have something like the following: class Nationalities(models.Model): country_name = models.CharField(...) class Profile(models.Model): name = models.CharField(...) name_kana = models.CharField(...) name_kanji = models.CharField(...) nationality = models.ForeignKey(Nationality...on_delete=models.CASCADE) What I tried: finalqs = "" nameqs = "" countryqs = "" if request.POST['search_name'] != '': nameqs = Q(name_kana__icontains=request.POST['search_name']) | ..... if request.POST['search_country'] != '': countryObj = Nationalities.objects.filter(country_name__icontains=request.POST['search_country']) countryqs = Q(nationality__icontains=countryObj) if nameqs != "" : if finalqs != "": finalqs += ", " + nameqs else: finalqs = nameqs if countryqs != "" : if finalqs != "": finalqs += ", " + countryqs else: finalqs = countryqs if finalqs != "": hrItems = Profile.objects.filter(finalqs) else: hrItems = Profile.objects.all() Right now, if I only search for names, I get the result that I want but if I include the country, it gives error message Related Field got invalid lookup: contains -
How do i retrieve a list of users for django-graphql-auth and graphene-django?
Using django==3.1.5 graphene-django==2.15.0 django-graphql-auth==0.3.15 django-graphql-jwt==0.3.0 I am trying to allow a foreign key to be set from a model to a user in my GraphQL API. class WorkOrder(BaseModel, models.Model): service_technician = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='service_technician', null=True ) When trying to query for the list of users, I get the expected response. query getUsers { users { edges { node { username, archived, verified, email, secondaryEmail, } } } } However, when trying to query for all workorders, I am getting an error { "errors": [ { "message": "Cannot query field \"serviceTechnician\" on type \"WorkOrderType\".", "locations": [ { "line": 35, "column": 5 } ] } ] } This is my current input for workorder and user in schema.py class UserInput(graphene.InputObjectType): id = graphene.ID() username = graphene.String() email = graphene.String() password1 = graphene.String() password2 = graphene.String() class WorkOrderInput(graphene.InputObjectType): id = graphene.ID() service_technician = graphene.List(UserInput) My UserType definition inherits from UserNode in graphql_auth\schema.py class UserType(UserNode): class Meta: model = get_user_model() filter_fields = app_settings.USER_NODE_FILTER_FIELDS exclude = app_settings.USER_NODE_EXCLUDE_FIELDS interfaces = (graphene.relay.Node,) skip_registry = True pk = graphene.Int() archived = graphene.Boolean() verified = graphene.Boolean() secondary_email = graphene.String() And finally, my CreateWorkOrder mutation class CreateWorkOrder(graphene.Mutation): class Arguments: input = WorkOrderInput(required = True) ok = graphene.Boolean() workorder = … -
Make a table row field in a django template multi column
I have a template that includes all the HTML for a table on a form. I am using a generic form for my model. My model looks like this: class Program(models.Model): air_date = models.DateField(default="0000-00-00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") running_time = models.TimeField(default="00:00:00") remaining_time = models.TimeField(default="00:00:00") title = models.CharField(max_length=255) locked_flag = models.BooleanField(default=False) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=255,blank=True) mc = models.CharField(null=True,max_length=64) producer = models.CharField(null=True,max_length=64) editor = models.CharField(null=True,max_length=64) remarks = models.TextField() audit_time = models.DateTimeField(null=True) audit_user = models.CharField(null=True,max_length=32) The template form looks like this: <form method="post"> {% csrf_token %} <TABLE BORDER="0" TABLE_LAYOUT="fixed" WIDTH="100%"> <TR BGCOLOR="#15C1B5"> <TD ALIGN="Right">Program Title:</TD><TD ALIGN="Left">{{ form.title }}</TD> <TD ALIGN="Right">Library:</TD><TD ALIGN="Left">&nbsp;{{ form.library }}</TD> <TD ALIGN="Right">Service Bureau:</TD><TD ALIGN="Left">&nbsp;{{ form.service }}</TD> </TR> <TR BGCOLOR="#15C1B5"> <TD ALIGN="Right">Program Id:</TD><TD ALIGN="Left">&nbsp;{{ program.pk }}</TD> <TD ALIGN="Right">Air Date:</TD><TD ALIGN="Left">&nbsp;{{ form.air_date }}</TD> <TD ALIGN="Right">Air Time</TD><TD ALIGN="Left">&nbsp;{{ form.air_time }}</TD> </TR> <TR BGCOLOR="#15C1B5"> <TD ALIGN="Right">Producer:</TD><TD ALIGN="Left">&nbsp;{{ form.producer }}</TD> <TD ALIGN="Right">Editor:</TD><TD ALIGN="Left">&nbsp;{{ form.editor }}</TD> <TD ALIGN="Right">MC:</TD><TD ALIGN="Left">&nbsp;{{ form.mc }}</TD> </TR> <TR BGCOLOR="#15C1B5"> <TD BGCOLOR="#99CCFF" ALIGN="Right">Duration:</TD> <TD BGCOLOR="#99CCFF" ALIGN="Left">&nbsp;{{ form.block_time }}</TD> <TD BGCOLOR="#8DF1BF" ALIGN="Right">Rem. Time:</TD> <TD BGCOLOR="#8DF1BF" ALIGN="Left">&nbsp;{{ form.remaining_time }}</TD> <TD BGCOLOR="#CC99CC" ALIGN="Right">Run Time:</TD> <TD BGCOLOR="#CC99CC" ALIGN="Left">&nbsp;{{ form.running_time }}</TD> </TR> <TR BGCOLOR="#15C1B5"> <TD ALIGN="Right">Remarks:</TD><TD COLSPAN="5"><PRE>{{ form.remarks }}</PRE></TD> </TR> </TABLE> The table looks fine - but the remarks field … -
How can a child class access its parent attributes without the "parent.attrib" syntax in Django?
I'm totally confused in Django I can create a child class which is PostAdmin(admin.ModelAdmin) with "admin.ModelAdmin" as its parent and assign a tuple to the "list_display"(tip: list_display is an attribute of admin.ModelAdmin class) inside the PostAdmin without writing "admin.ModelAdmin.list_display"...while in python to address a parent class's attribute one needs to use the "parent.attrib" syntax and the fact is when I try admin.ModelAdmin.list_display it gives me errors! here is the code in my "admin.py": from django.contrib import admin # Register your models here. from blog.models import post class PostAdmin(admin.ModelAdmin): admin.ModelAdmin.list_display= ('title','publish', 'status') admin.site.register(post,PostAdmin) what am I missing? I've searched a lot about python inheritance and couldn't understand the way the inheritance works in here...to be exact, How the child class (PostAdmin) assigns the "('title','publish', 'status')" to its parent(ModelAdmin)? how does it get there? here are some parts of admin.ModelAdmin codes(which is made by Django and located in options.py) that I found by going to ModelAdmin's definition the first time list_display is used in options.py (where ModelAdmin is defined) class BaseModelAdmin(metaclass=forms.MediaDefiningClass): #... def get_sortable_by(self, request): """Hook for specifying which fields can be sorted in the changelist.""" return self.sortable_by if self.sortable_by is not None else self.get_list_display(request) """Encapsulate all admin options and functionality for … -
Trying login at admin Django page
I'm taking the free Django course with Prof. Charles Severance (Dr. Chuck), and at Lesson 6, I am having some troubles to login at the admin page of django, i.e. I've created successfully the username and the password, but at the moment to enter I receive this message " Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. " . source page: http://djtutorial.dj4e.com/admin I am using the Dr chuck's link "http://djtutorial.dj4e.com/admin" to login, because he said I can not use the runserver cmd line in pythonanywhere, so that, I run the manage.py cmd and then reload the web page, but the problem is still there. When I try to connect within the local host there is any connection, so, I have to use http://djtutorial.dj4e.com/admin. I have already check the username and the password with the following cmds: from django.contrib.auth.models import User user = User.objects.get(username='username') user.check_password('password') TRUE What can I do? Thanks in advanced. -
How to group swagger API with drf_yasg
I am doing some migration work from Django 1.11 --> 3.1.5 previously with "rest_framework_swagger", I am able to accomplish swagger api grouping just by this in url.py url(r'^api/v9/test_token1$', api.test_token, name='test_token'), url(r'^api/v9/test_token2$', api.test_token, name='test_token'), and get this (notice it groups v9) However, I have tried with "drf_yasg" on Django 3.1.5 url.py path('/v2/token_api1', token_api1, name='token_api1'), path('/v2/token_api2', token_api2, name='token_api2'), my api definition (do note I am using @api_view) token = openapi.Parameter('token', openapi.IN_FORM, type=openapi.TYPE_STRING, required=True) @swagger_auto_schema( method="post", manual_parameters=[token], operation_id="token_api1" ) @api_view(['POST']) # this is optional and insures that the view gets formdata @parser_classes([FormParser]) def token_api1(request): token = request.POST['token'] return Response("success test_api:" + token, status=status.HTTP_200_OK) token = openapi.Parameter('token', openapi.IN_FORM, type=openapi.TYPE_STRING, required=True) @swagger_auto_schema( method="post", manual_parameters=[token], operation_id="token_api2" ) @api_view(['POST']) # this is optional and insures that the view gets formdata @parser_classes([FormParser]) def token_api2(request): token = request.POST['token'] return Response("success test_api:" + token, status=status.HTTP_200_OK) however, I get this (noticed v2 does not group). And also when I did a test, there were errors as well. (Code 404 Error: Not Found) How can I group these to API in drf_yasg and also making sure there is no error ? Note if the url.py is like this, there is NO error but it does not group path('token_api1', token_api1, name='token_api1'), path('token_api2', token_api2, … -
Django views: Using a queryset with exclude after a for loop
in my views.py I have a queryset (bytes) that I loop through, adding a style property to certain items in the queryset: bytes = Byte.objects.order_by('-publish_date') for d in bytes: if not d.published: d.style = 'my-style' Then in my views, I have another conditional statement: if most_recent != most_shared: bytes = bytes.exclude(byte_id=most_shared_id) But then when I sent bytes to the template, none of the info from the loop (if any item in the bytes got d.style) is there. How can I make this so when I use exclude I'm doing so on the bytes that just went through the loop?? -
Django logout method doesnt functionate
This is my first django project with login/out. On login the user is successfully redirected to his dashboard, however when I click logout nothing happens. Any ideas how can I fix this issue? view: def logout(request): #logout(request) if request.method == 'POST': auth.logout(request) messages.success(request, 'You are now logged out') return redirect('login') html: {% if user.is_authenticated %} <div id = 'dashboard' class="the-dashboard"> <div class="prof"> <p ><span class = 'fntmk'>Welcome</span> {{ user.username }}</p> <img src = "{% static 'images/profile-trans.jpg' %}"> </div> <div class="the-panel"> <form action = "{% url 'logout' %}" method = "POST"> {% csrf_token %} <a class = 'fntmk'><i class="far fa-user-circle size"></i>&nbsp;&nbsp;&nbsp;Profil</a> <a href="{% url 'logout' %}" class = 'logout fntmk prob' alt='exit'><span class="material-icons">logout</span><span class = 'odjavi'>Logout</span></a> </div></form> </div> {% else %} <div class="the-login"> <form action = "{% url 'login' %}" method = "POST"> {% csrf_token %} <input type = 'text' id = 'username' class = 'username-field' placeholder = 'username' required> <input type = 'password' id = 'password' placeholder = 'password' required> <a href= "{% url 'login' %}"> <button class = 'btn-login'>Login</button></a> </form> <a href = "{% url 'register' %}" class = 'register fntmk'>New User?</a> </div> {% endif %} urls> path('register/',register, name = 'register'), path('accounts/dashboard/',login, name = 'login'), path('',logout, name = 'logout'), -
Can't access text saved in a Quill form on Django template
In my django template I want to access the bio prop of an instance of my Creator class. This bio is set up as a QuillField in the Creator model class. When I try to access creator.bio, all that renders to the page is the following: <django_quill.fields.FieldQuill object at 0x1084ce518> What I want is the actual paragraph of formatted text (ie. the bio) that I typed into the form and saved. As of now, the QuillField is only accessible through the form in the Django admin page. The problem has nothing to do with the Quill UI, but rather being able to access the text I wrote into that form field and render it to the page in a readable format. From models.py: from django.db import models from django_quill.fields import QuillField class Creator(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=100, default='Creator') bio = QuillField() photo = models.ImageField(upload_to='images/', default='static/assets/icons/user-solid.svg') email = models.EmailField(max_length=100) website = models.URLField(max_length=1000, blank=True) facebook = models.URLField(max_length=1000, blank=True) twitter = models.URLField(max_length=1000, blank=True) instagram = models.URLField(max_length=1000, blank=True) def __str__(self): return self.name In views.py: def about(request): context = {"creators" : Creator.objects.all()} return render(request, 'about.html', context) And, in the template: <section id="creator-container"> {% for creator in creators %} <div class="creator-square"> <h4>{{ creator.name }}</h4> … -
How can i add a param to the existing url?...Django...Paginator
I have made a page with which displays some data from the database. I have added a paginator to my website. my website also has a search bar. so when the user searches for something....the URL is... .../search/?q=xyz so when I paginate the searched data with... <a href="?page={{ walls.next_page_number }}"> next page </a> it makes the URL as... .../search/?page=2 but that's an error...but, I want something like this... .../search/?q=xyz&page=2 how can I achieve this... -
Pulling a Database from Heroku and not able to process data
I used pg:pull to pull a database to my local database. It was all working as expected until it got to the processing data step. Here is the error I received, it was on the first entry in the database. pg_restore: processing data for table "a1pavingco.account_emailaddress" pg_restore: error: unrecognized data block type (0) while searching archive events.js:287 throw er; // Unhandled 'error' event ^ Error: write EPIPE at afterWriteDispatched (internal/stream_base_commons.js:154:25) at writeGeneric (internal/stream_base_commons.js:145:3) at Socket._writeGeneric (net.js:784:11) at Socket._write (net.js:796:8) at doWrite (_stream_writable.js:442:12) at writeOrBuffer (_stream_writable.js:426:5) at Socket.Writable.write (_stream_writable.js:317:11) at Socket.ondata (_stream_readable.js:695:22) at Socket.emit (events.js:310:20) at Socket.Readable.read (_stream_readable.js:493:10) Emitted 'error' event on Socket instance at: at errorOrDestroy (internal/streams/destroy.js:108:12) at Socket.onerror (_stream_readable.js:729:7) at Socket.emit (events.js:310:20) at errorOrDestroy (internal/streams/destroy.js:108:12) at onwriteError (_stream_writable.js:457:5) at onwrite (_stream_writable.js:484:5) at internal/streams/destroy.js:50:7 at Socket._destroy (net.js:677:5) at Socket.destroy (internal/streams/destroy.js:38:8) at afterWriteDispatched (internal/stream_base_commons.js:154:17) { errno: 'EPIPE', code: 'EPIPE', syscall: 'write' } I don't know what to make of this error or how to fix it. I can see the database via PGAdmin however there are no entries within the columns. I have tested that with queries that returned nothing. Any advice on how to solve this problem will be much appreciated! -
Weird try/except in Django's get_or_create()
I'm looking into the source of Django's get_or_create() method and wondering what the try/except on the line 590 is doing? Could it just be removed? -
Mismatching url from build_absolute_uri('/confirm/') Django Sendgrid
I am trying to send a confirmation email with sendgrid, but when user click the link, it generated My Page not found error: The current path,/confirm//confirm/, didn't match any of these. This my views.py message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject='Newsletter Confirmation', html_content='Thank you for signing up for my email newsletter! \ Please complete the process by \ <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \ confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'), sub.email, sub.conf_num)) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) def confirm(request): sub = Subscriber.objects.get(email=request.GET['email']) if sub.conf_num == request.GET['conf_num']: sub.confirmed = True sub.save() return render(request, 'app/index.html', {'email': sub.email, 'action': 'confirmed'}) else: return render(request, 'app/index.html', {'email': sub.email, 'action': 'denied'}) app level urls.py: path('confirm/', views.confirm, name='confirm'), path('delete/', views.delete, name='delete'), I know there must be the problem of build_absolute_uri('/confirm/') or the confirm view, I have tried different attempts by changing the url build_absolute_uri('confirm/') or build_absolute_uri('') but it still didn't match any url. -
Can a model have 2 many to many relations with another model?
I'm developing an application that has the following three models: Student, Subject and Skills. A Student can have many skills, and a Skill can have many student. A Subject can offer 0 or many skills after a Student complete it, however, a Student has to have 0 or many skills required to complete a Subject. How could I manage this? I've tried to create two many to many fields inside Subject called 'requiredskills' and 'offeredskills' both related to Skill, however it didn't work. -
PUT on many to many Django rest framework
models class Customer(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) phone = models.CharField(max_length=11,blank=True,null=True) likecus=models.ManyToManyField(smartphone ,verbose_name="лайк") class smartphone(models.Model): title=models.CharField(max_length=255) Serializer class CreateCustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('phone', 'likecus') I get the error that the required field of Customer is not sent. This setup works for PUT call however. The issue with PUT call is that when I call the PUT call again, it overrides the existing data in the CreateCustomerSerializer relation field with the new data and not simply appends the data of second API call to the first. How can I POST data so that I am able to link existing smartphone records with Customer records? through the Primary Key Related Field. I have this created has not changed. I don't know, some people have solved the problem this way. it doesn't work for me -
How to get next available object or primary key from database in django
I am trying for a music player and i want to get next music from database with current music's id. So if anyone could tell how to get next primary key with current id. This is the code for getting current music. music = Contents.objects.get(id=id) The id that I passed is primary key of current music. So instead of the code above please do suggest how can I get next music.