Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not find a version that satisfies the requirement pywin32 on cpanel
My os is windows 10 where I can install pywin32 without having any problem but When I'm going to install pywin32 on Cpanel(Namecheap) in my Django app then showing the following error. Please notice the image where everything is almost the same version just python 3.9.2 on windows and python 3.8.6 on Cpanel. Also, I tried several pywin32 version on CPanel but didn't work. enter image description here Which procedure I should follow to install pywin32 or pypiwin32 on my Cpanel? Thanks in Advance. -
How to return to HTTP_REFERRER instead of passing a template to TemplateResponse?
I am writing an application that has a page with content ideas. User has the ability to schedule any post right from this page. The schedule button calls a view SocialPost that schedules a post and then redirects the user to the same page from where it came using return HttpResponseRedirect(request.META.get('HTTP_REFERER')). This works perfectly fine. However, I am also using a middleware and TemplateResponse hook to decrement the user-allocated quota. I understand that in order to make TemplateResponse hook to work I should return TemplateResponnse in the view instead of HttpResponseRedirect. The problem is that I don't have the html file path to pass in TemplateResponse. The equivalent I have been using is return TemplateResponse(request, request.META.get('HTTP_REFERER')). This is not working. Can you please guide how to redirect to the same page from user came using TempalteResponse. -
How to prevent a user from manually going to some specific urls?
In my app, I want the user to access one specific url when he has paid the money via paypal client-side integration. my paypal integration comes from here. Now at the end(of the given link) I have to redirect the user to another page, by doing this, onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer alert('Transaction completed by ' + details.payer.name.given_name + '!'); window.location.href='/accepted/{{transaction_id}}'; }); Now at the accepted page, I have to do some serious tasks that includes inserting records to database about the whole transaction. If user pays the money and go to that page, it's fine. But if the user inspected the page(by pressing F12) and manually moved to that url, he wouldn't pay but the transaction will be stored on the database. How can i avoid this? Please guys, I have been stuck for a long time. Thank you:) -
How to refer a submit element after submiting the form?
I am trying to refer a submit element after submitting a form but it is not working. At first, a tab named London consists a form and after submitting the form the result is stored in Paris tab. But after I submit the form, the form redirects to the same page and to the same tab instead of Paris tab. Here is the code: main.html <div class="tab"> <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button> <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button> <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button> </div> <div id="London" class="tabcontent "> <h3 class='poppins'>Your Map</h3> <form method='POST' onsubmit="openCity(event, 'Paris'); return false">{% csrf_token %} {{ form.as_p }} <input type='submit' value='Save' class="login-btn poppins"/> </form> </div> <div id="Paris" class="tabcontent"> <h3>Paris</h3> <p>Paris is the capital of France.</p> <img src="{{ image_url }}"> </div> <div id="Tokyo" class="tabcontent"> <h3>Tokyo</h3> <p>Tokyo is the capital of Japan.</p> </div> </div> </div> <script> function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } Here is the Image of the main.html -
Django redirect a custom rendered 404.html template
I want to redirect a custom template when an invalid url is entered in my Django website. When an incorrect URL, for example /home/ll, is entered then 404.html is shown on the screen and the url is redirected to /error. -
(Internal Server Error) on django web push notifications with heroku
I'm building a messages app where a user can send incognito messages so the reciever wouldn't know who send the message.. any way just needed to implement push notifications so whenever new message come to a user he receives a push notificatoin I've followed this article which i found after some searching and it worked perfect for me on the local host ,how ever when i tried to deploy my app on heroku that didn't work things I've faced 1- error on the front end first time i tried it out it worked perfect but just as I reloaded the page I found this error in the console registerSW.js:66 POST https://stalker-rat.herokuapp.com/webpush/save_information 500 (Internal Server Error) this 66 line is responsible for saving the information about the registered service worker I think , but this caused problems as the service worker was already saved , i thought that the browser would handle this .. any way this is my code const res = await fetch('/webpush/save_information', { method: 'POST', body: JSON.stringify(data), headers: { 'content-type': 'application/json', }, credentials: "include" }); at first i thought this was some thing about the csrftoken but adding it to the post request didn't do any thing error … -
from ._compat import PY2 ModuleNotFoundError: No module named 'pydrive._compat'
On running the script in init.py file: from ._compat import PY2 from .constants import FIELD_TYPE from .converters import escape_dict, escape_sequence, escape_string from .err import ( Warning, Error, InterfaceError, DataError, DatabaseError, OperationalError, IntegrityError, InternalError, NotSupportedError, ProgrammingError, MySQLError) from .times import ( Date, Time, Timestamp, DateFromTicks, TimeFromTicks, TimestampFromTicks) I get the following error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "E:\project\pydrive-project-master\pydrive-project-master\pydrive\pydrive\__init__.py", line 27, in <module> from ._compat import PY2 ModuleNotFoundError: No module named 'pydrive._compat' I already have PyDrive installed in the environment. How do I resolve this error? -
Running Total in Django Template
I listed debit and credit for my account transactions. Now I want to running total in last column by debit subtracted by credit added with previous arrived amount as running total (as you know). Thanks for your support. my view: def listaccounttrans(request): alltrans = FinTransDetail.objects.all() context = {'alltrans': alltrans} return render(request, 'waccounts/list_account_trans.html', context) my html: {{% extends 'wstore_base_generic.html' %}} {% block content %} <h3>Table</h3> <div> <table id="customers" > <thead> <tr> <td>AcctCode</td> <td>TransNo</td> <td>TransDate</td> <td>AcctDetail</td> <td>Debit</td> <td>Credit</td> <td>Balance</td> </tr> </thead> <tbody> {% for acct in alltrans%} <tr> <td>{{ acct.fd_acct }}</td> <td>{{ acct.fd_no}}</td> <td>{{ acct.fd_no.fh_dt}}</td> <td>{{ acct.fd_no.fh_detail }}</td> <td>{{ acct.fd_debit }}</td> <td>{{ acct.fd_credit }}</td> <td>{{ acct.fd_no}}</td> # needs running total here# </tr> {% endfor %} </tbody> </table> </div> {% endblock %} my template is showing now: AcctCode TransNo TransDate AcctDetail Debit Credit Balance 1101 94 May 18, 2021 Detail 11.00 0.00 94 (needs to be replaced with 1101 94 May 18, 2021 Detail 0.00 11.00 94 running balance) [total balance] -
Django models to hold a list of objects from another Model
I am creating a shopping cart for an e-commerce platform. I have made a Products model and the I need to create a Cart model. One cart can have multiple products in it. I need to create a field products in the cart which is a list of multiple product objects. I am not sure how to do it but I can think of two ways:- Create a list of ids of all the products Create a list which contains the product objects inside of them (this might save lookup time) The product model looks like this:- class Product(models.Model): # Define the fields of the product model name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to='market/static/images/products') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) # Foriegn key with Category Model store = models.ForeignKey(Store, on_delete=models.CASCADE, default=1) The foreignkey relation doesn't seem to work here because it only stores one entry at a time. I think ManytoManyFields might work but I am not able to connect it between these two models. -
Django: Unable to use prefetch_related
What I want to do is that for a particular Cylinder Id , if cylinder is issued then the user name and the issue date will be displayed in cylinder List , like this cylinderId | date | type | status |availability| issuedate | userName | returndate | 1 | 11/11| co2 | fill | available| 12/11(if exists)| xyz | 13/11(if exists) so for that i used prefetch_related but it is not displaying anything in cylinder List:- here is model:- class Cylinder(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','available'), ('Unavailable','unavailable'), ('Issued','issued') ] cylinderId=models.CharField(max_length=50,primary_key=True,null=False) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.cylinderId)]) def __str__(self): return str(self.cylinderId) class Issue(models.Model): cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE) userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) super().save(*args,**kwargs) def __str__(self): return str(self.userName) here is cylinder list view:- def cylinderListView(request): cylinder=Cylinder.objects.all().prefetch_related('issue_set') return render(request,'entry/cylinderList.html',locals()) here is cylinderList template:- {% extends 'base.html'%} {% block content %} <div class="alldiv"> <h1 align="center">All Cylinder list</h1> {% if cylinder %} <div class='centerstage'> <div class="post"> <table border="5" cellspacing="5" width="100%" > <thead> <tr bgcolor="#99c2ff"align="center"> <th height="50" width="50">Cylinder Id</th> <th height="50" width="50">Date</th> <th height="50" width="50">Gas Name</th> <th height="50" width="50">Cylinder Size</th> <th height="50" width="50">Status</th> <th height="50" width="50">Availability</th> <th height="50" width="50">Issued Date</th> <th height="50" width="50">Customer</th> <th height="50" width="50">Return Date</th> </thead> <tbody> … -
django path in boutton page not found
button Update urls path('devices/', views.devices, name='devices'), path('update_device/str:pk/', views.update_device, name='update_device'), views @login_required(login_url='login') def update_device(request, pk): device = Device.objects.get(id=pk) form = Adevice(instance=device) context = {'form':form} return render(request, 'accounts/device.html', context) #ajouter device @login_required(login_url='login') def device(request): form = Adevice() if request.method == 'POST': form = Adevice(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'accounts/device.html', context) -
How to enable the ltree extension on google cloud sql
First of al: ltree is a postgres plugin, which seems to be officially supported by google (see GCP PostgreSQL extensions) In the same documentation I read that you need to enable the extension first (like on a normal postgres database). My backend application is written in the django framework and I basically instruct it to run the following command, which works without hick ups on my local machine: CREATE EXTENSION IF NOT EXISTS ltree; However, when I run that migration, I get the following error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.InsufficientPrivilege: permission denied to create extension "ltree" HINT: Must be superuser to create this extension. This makes sense since according to the documentation, "the postgres user must be part of the cloudsqlsuperuser role". However, I see no way to give my user that role. I tried the default postgres user, which according to the documentation page above should be configured correctly, but it basically does not work. When I dig deeper in the cloudsql documentation, I read something even more surprising: it does not seem to be possible to create superusers according to this documentation. So, the question is quite simple: How … -
Djoser not sending emails when default emails are overridden
I have a DRF project that uses Djoser for authentication. The plan is to override Djoser's default activation email and send something an HTML template email. Here's what I have: # settings.py DJOSER = { "SEND_ACTIVATION_EMAIL": True, "ACTIVATION_URL": "activate/{uid}/{token}", "EMAIL": {"activation": "base.emails.ActivationEmail"}, } # base/emails from django.contrib.auth.tokens import default_token_generator from djoser import email, utils from djoser.conf import settings class ActivationEmail(email.ActivationEmail): template_name = "emails/activation.html" def get_context_data(self): # ActivationEmail can be deleted context = super().get_context_data() user = context.get("user") context["first_name"] = user.first_name context["uid"] = utils.encode_uid(user.pk) context["token"] = default_token_generator.make_token(user) context["url"] = settings.ACTIVATION_URL.format(**context) return context # templates/emails/activation.html {% extends "emails/base.html" %} {% load static %} {% block subject %}Account Activation on Dummy{% endblock %} {% block heading %} Account Activation {% endblock %} {% block content %} You're receiving this email because you need to finish activation process. Please click on the button below to activate your account: <br><br><br> <a href="{{ url }}" target="_blank" style=" text-decoration: none; font-family: lato, 'helvetica neue', helvetica, arial, sans-serif; font-size: 20px; color: #fff; background-color: #0b913a; padding: 10px 25px; border-radius: 5px; " >Activate</a > <br><br><br> Best Regards,<br> The DUMMY Team <br><br> <p style=" margin: 0; -webkit-text-size-adjust: none; -ms-text-size-adjust: none; mso-line-height-rule: exactly; font-size: 14px; font-family: lato, 'helvetica neue', helvetica, arial, sans-serif; line-height: … -
Django extend base.html work on all pages but one
Today i tried to setup Django authentification on an app and it's working a 99%. The registration and login are working perfectly but i have a problem on the userprofile page. Registration, login and userprofile templates all have the extends base.html and it's working for the registration and login, but on the userprofile page i get an error saying that the source base.html can't be round. Strangest thing is that the path value that Django trie is the correct one, same as the other two templates. This is the structure of my templates folder : Templates Account Registration.html Login.html Userprofile.html Base Base.html Most of the post if have found about extend base error usualy incombe the extend not working at all or not working in one folder but working in the others where mine work for two templates out of 3 in the same folder. I tried to remove most of the code in my userprofile template to see if anything was messing with the extend but even there i get the same error. -
Django Content Management System
When I try to add a new data in CMS of Django. So I press the button, and then it shows me this. RuntimeError at /admin/booktest/bookinfo/add/ generator raised StopIteration Request Method: POST Request URL: http://../admin/booktest/bookinfo/add/ Django Version: 1.8.2 Exception Type: RuntimeError Exception Value: generator raised StopIteration Exception Location: C:\Users\Nitro5\Desktop\pyango\lib\site-packages\django\http\multipartparser.py in read, line 337 Python Executable: C:\Users\Nitro5\Desktop\pyango\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\Nitro5\\Desktop\\pyango\\pyango\\test1', 'C:\\Users\\Nitro5\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Nitro5\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Nitro5\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Nitro5\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Nitro5\\Desktop\\pyango', 'C:\\Users\\Nitro5\\Desktop\\pyango\\lib\\site-packages'] And I went to the file 'multipartparser.py'. I tried to add 'try-except StopIteration'.But it didn't work. So....anyone can help? -
How to descrease SQL queries count generated by model method in Django?
I have model method that calculates object status using some data that is not "ForeignKey" from django.db import models class Product(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=20, null=True) def status(self): sales_data = Sale.objects.filter(some_string_parameter='goods', entity_ref=self.id).aggregate(Max('discount')).get('value') if not sales_data: return "No Sale" elif sales_data >= 50: return "Sale over 50%" elif sales_data < 50: return "Sale less than 50" I have a page with the product list (all products in the database) where I need to show its status. {% for product in products %} {{ product.name }} - {{ product.status }} {% endfor %} Each product.status generates extra SQL request. Is there any way to "prefetch" model method result for all objects in queryset? -
how to play a specific timestamp in a video file using django 3
I want to create a website similar to http://playphrase.me in this project the user searches for a word or phrase and then short video clips of that phrase being used in different movies and tv series is played for the user. In my views.py, i search srt subtitles for a keyword or phrase and then get the name, url path, and the timestamp during which a word or phrase is being said in a video file. I can send these info in a json or dict to template, my problem is how to play these files. I want my video player to start and stop playing a video at the specific timestamp that i provided. Please tell me which video player to use and how. -
How to save and run python function in HTML button?
Context: For a face recognition project, user should upload a selfie and that pic will be saved in a S3 bucket (AWS) so the final result will be a template with that selfie and the person who looks like you. So, I want a button that save the image uploaded by user and at the same time, run the face recognition function. template: <form method="post" enctype="multipart/form-data" id="upload-form" action="{% url 'erp:fibocal' %}"> <div class="card-footer"> <button type="submit" class="btn btn-primary btn-flat" onclick="showLoaderOnClick('{% url 'erp:fibocal' %}')"> <i class="fas fa-save"></i> ¡Encontrá tu parecido! </button> </div> </form> And that button don´t save the image in my s3 bucket, only runs "erp:fibocal" that is a function in views.py: def fibocal(request): if request.method == 'POST': img_loaded = request.FILES['image'] imagenes = FR(img_loaded) return render(request, 'base.html', {'name': imagenes[0], 'prct':imagenes[1]}) else: return render(request, 'home/register.html', {}) ``` I think that I should save the image at the "fibocal" function but I don´t know how. Thanks! -
AttributeError: 'ParsedRequirement' object has no attribute 'req' in PIP 21.1.1
I am currently upgrading a project from Django 2.1 to Django 2.2. In doing so, I have been getting the following error when doing pip install -r requirements.txt. Running command git clone -q git://github.com/user/djangocms-comments /tmp/pip-req-build-x00esn u5 ERROR: Command errored out with exit status 1: command: /home/user/miniconda3/envs/python-3.6-test-web/bin/python -c 'import io, o s, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-req-build-x00esnu5/setup.py'"'"'; __file__='" '"'/tmp/pip-req-build-x00esnu5/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if o s.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read ().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_i nfo --egg-base /tmp/pip-pip-egg-info-xm4vt9bf cwd: /tmp/pip-req-build-x00esnu5/ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-req-build-x00esnu5/setup.py", line 188, in <module> install_requires = [str(ir.req) for ir in requirements] File "/tmp/pip-req-build-x00esnu5/setup.py", line 188, in <listcomp> install_requires = [str(ir.req) for ir in requirements] AttributeError: 'ParsedRequirement' object has no attribute 'req' ---------------------------------------- It appears that the package djangocms_comments is outdated in how it uses pip. I have gathered that much by searching this site. However, I am unsure how to fix this. The error happens here. Any help or guidance would be appreciated. -
403 forbidden when accessing django admin folder
I found many threads about similar problems but nothing worked so far. I'm deploying a web app on production server using uwsgi and nginx. The backend is in Django, frontend in Vue.js. I want to access the Django admin panel. I ran python3 manage.py collectstatic, chown -R www-data:www-data /home/debian/public/static/ and made sure that rights are ok (rwx r-x r-x www-data:www-data for folders and www-data:www-data rw- r-- r-- for files). nginx.conf user www-data; ... location /admin/ { alias /home/debian/public/static/admin/; } When I try accessing the admin panel (https://my-site.com/admin/) I get a 403 forbidden from nginx. error.log from nginx directory index of "/home/debian/public/static/admin/" is forbidden, [...] However, if I go to https://my-site.com/admin/css/base.css, I can see the css file. Other unrelated static folders, such as swagger doc (using drf-yasg), work fine. If I add an index.html file in /home/debian/public/static/admin/, nginx serves the index.html file as expected. Any idea what am I missing ? -
why isn't the code inside head tag working when code inside body is working?
<!DOCTYPE html> <html> <head> {% if title %} <title> Django blog - {{title}} </title> {% else % } <title> Django blog </title> {% endif %} </head> <body> {% for post in posts %} <h1>{{post.title}}</h1> <p>By {{post.author}} on {{post.date_posted}} </p> <p>{{post.content}} </p> {% endfor %} </body> </html> When i run the code the head tag is empty and there is no title but the for loop executes to give the result i expected. -
CreateUser View returning IntegrityError on form submit
I have a CreateUser view that uses the generic CreateAPIView as a sign up view in the API I'm working on. I'm using a custom User model which uses the django.contrib.auth.models.AbstractUser model. On submitting the form (or sending data via a frontend), I'm getting an error, and I can't seem to find what I'm doing wrong. class UserSerializer(ModelSerializer): class Meta: model = User fields = ("username", "email", "password") extra_kwargs = {"password" : {"write_only" : True}} def create(self, validated_data): user = User.objects.create( email=validated_data["email"], username=validated_data["username"] ) user.set_password(validated_data["password"]) user.save() Token.objects.create(user=user) return user View. class CreateUser(CreateAPIView): serializer_class = UserSerializer permission_classes = () authentication_classes = () Error: "IntegrityError at /api/users/sign_up/ NOT NULL constraint failed: users_user.email -
Django rest framework merging two serializers data based on following requirement
I have two models one is Video which contains all the user uploaded details and other model is LikedVideo which contains details of liked videos by the user. Video model class Video(models.Model): """ All videos available for the users """ video = models.FileField(blank=True, default='') user = models.ForeignKey(User, related_name='user_videos', related_query_name='person', on_delete=models.SET_NULL, null=True) category = models.ForeignKey(VideoCategory, related_name='video_category', on_delete=models.SET_NULL, null=True) channel = models.ForeignKey(Channel, related_name='video_channel', on_delete=models.SET_NULL, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) deleted_at = models.DateTimeField(null=True) active = models.BooleanField(default=1) description = models.TextField(null=True) short_description = models.CharField(max_length=150, null=True) def __str__(self): return f"{self.user.username}_{self.category.video_type}_{self.channel.channel_name}" LikedVideo model class LikedVideo(models.Model): """ Contains all the liked videos by user """ video = models.ForeignKey(Video, related_name='video_liked', on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, related_name='user_liked', on_delete=models.SET_NULL, null=True) liked = models.BooleanField(default=0) def __str__(self): return f"{self.user.username}" VideoSerializer class VideoSerializer(ModelSerializer): uploaded_at = serializers.ReadOnlyField() class Meta: model = Video fields = ["id", "video", "category", "uploaded_at", "channel", "description", "short_description"] def to_representation(self, instance): rep = super(VideoSerializer, self).to_representation(instance) rep['category'] = instance.category.video_type rep['channel'] = instance.channel.channel_name return rep def validate_channel(self, value): print(self.context['request'].user) if Channel.objects.filter(user=self.context['request'].user, channel_name=value).exists(): return value raise serializers.ValidationError(_(f"Channel {value} does not belongs you. Please, enter a channel belongs to you")) LikedVideoSerializer class LikedVideoSerializer(serializers.ModelSerializer): class Meta: model = LikedVideo fields = ["id", "video", "liked", "user"] VideoListAPIView class VideoListAPIView(generics.ListAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer def list(self, request, format=None): … -
Showing same template for all url of an Django app
Here are the two views : from django.shortcuts import render from django.views import View from django.http import HttpResponse class sectionOfficer_home(View): def get(self, request, *args, **kwargs): return render(request, 'sectionofficer/UI/index.html', {}) class sectionOfficer_main(View): def get(self, request, *args, **kwargs): return render(request, 'sectionofficer/UI/404.html', {}) Here is my urls.py of the app sectionOfficer: from django.urls import path from .views import (sectionOfficer_home, sectionOfficer_main) app_name= 'sectionofficer' urlpatterns = [ path('', sectionOfficer_home.as_view(), name = "sectionofc"), path('secmain', sectionOfficer_main.as_view(), name = "sectionofc") ] And here is the global urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',views.home), path('students', views.dataViewer), path('sectionoffc', include('sectionofficer.urls')), path('secmain', include('sectionofficer.urls')), ] But it showing always the first view template for any different url. What is wrong here ? Help please. -
django.db.utils.IntegrityError: NOT NULL constraint failed: like model
I am getting django.db.utils.IntegrityError: NOT NULL constraint failed: feed_like.user_id on my model . How can i solve it my models.py class Like(models.Model): post = models.ForeignKey(Posts, related_name='likes', on_delete=models.CASCADE) user = models.ForeignKey(HNUsers, related_name='likes', on_delete=models.CASCADE) liked = models.BooleanField(default=False, blank=True, null=True) class Meta: verbose_name_plural = "Likes" my views.py @api_view(['GET', 'POST']) @permission_classes((permissions.AllowAny,)) @parser_classes([FormParser, MultiPartParser]) def like_post_api(request): if request.method == 'POST': data = request.data print(data) serializer = PostLikeSerializer(data=request.data) print("print ", serializer) post = Posts.objects.get(id=data['post']) print(post) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) my serializer.py class PostLikeSerializer(serializers.ModelSerializer): user = CommentUserSerializer(read_only=True, many=False) class Meta: model = Like fields = ( 'id', 'user', 'post', )