Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to Proxy Apache properly
I use a Django application. I want to access it via Apache. So, I've made DEBUG=False and tried to proxy ProxyPass "/" "http://localhost:8000/" So it routes to my application. Only problem is.. the static files don't load with this method. Therefore, I tried to put static folder in /var/www/html/static In console, this is where all the calls are going but they still don't load. This is my config file There must be something i'm missing or do not understand. Can someone please enlighten with some explanation! -
Django: there is no unique constraint matching given keys
I created an extension of the standard user model in models.py called Client. I added a manytomany relationship to it to indicate which clients are related to another: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) clients = models.ManyToManyField("self", blank=True) This works perfectly fine in my local dev environment where I use python manage.py runserver. However, when I try to run python manage.py migrate on our testing server using a postgresql database, I get the following error: psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "content_client" What am I missing here? -
Django Rest Framework upload_to doesn't work as desired
I'm passing callable for image field in my project like this def profile_picture_path(instance, filename): """Path for uploading profile pictures in media directory""" return f"user/profile_picture/{instance.pk}/{filename}" class User(AbstractUser): profile_picture = models.ImageField(_("profile picture"), upload_to=profile_picture_path, null=True, blank=True) When I add a user through the admin panel, the image gets a proper path: user/profile_picture/3/pfp.png. Problem comes when I send a post request to registrate: user/profile_picture/None/pfp.png # views.py @api_view(["POST"]) def register_view(request): """ Register View which takes only post method. """ serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # serializers.py class UserSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): exclude = kwargs.pop("exclude", None) super().__init__(*args, **kwargs) if exclude is not None: for field_name in exclude: self.fields.pop(field_name) password = serializers.CharField(write_only=True) class Meta: model = User exclude = ["deleted", "deleted_by_cascade"] How can I fix this and get correct path for image uploads? -
using EmailMultiAlternatives in Django but it randomly stopped sending emails
I'm using Django and the email code is within a try except block that also creates a user. The code is creating the user, but when it comes to sending the welcome email, it's suddenly failing, and defaults to the except clause, which notifies the user that an account already exists with that email. After some debugging I realized that all of the code works right up until msg.send(), but this particular code hasn't been touched since February, when the website went live. I don't understand why it stopped working. in my settings.py: EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mandrillapp.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True in my views.py: htmly = get_template('main/new_account.html') d = {'name': data['first_name'], 'base': os.getenv('HOST_URL')} subject, from_email, to = 'New Account', os.getenv('EMAIL_HOST_USER'), email html_content = htmly.render(d) msg = EmailMultiAlternatives( subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") try: msg.send() except: print('message did not send') in my terminal: Conflict: /api/user/account/create -
i added & instead of | between Q objects but it does not work
Sometimes i will search for type and color only or name and year only, so Q should be able to compile request together for example if i write "url/search/?q=action&q=Blue" it returns only the last query which in this case is "Blue" views.py def search_result(request): query = request.GET.get('q') qs = Content.objects.distinct().search(query=query) query_string = request.GET.get('q') query_string = query_string.replace(';',',') page = request.GET.get('page', 1) pagination = Paginator(qs, CONTENTS_PER_PAGE) try: qs = pagination.page(page) except PageNotAnInteger: qs = pagination.page(CONTENTS_PER_PAGE) except EmptyPage: qs = pagination.page(pagination.num_pages) context = { 'SearchResults': qs, 'query': query_string, } return render(request, 'home/search_result.html', context) models.py class ContentQuerySet(models.QuerySet): def search(self, query=None): if query is None or query == "": return self.none() lookups = Q(genre__name__icontains=query) & Q(distributor__icontains=query) & Q(title__icontains=query) & Q(channels__name__icontains=query) & Q(year__icontains=query) return self.filter(lookups) class ContentManager(models.Manager): def get_queryset(self): return ContentQuerySet(self.model, using=self._db) def search(self, query=None): return self.get_queryset().search(query=query) class ChannelQuerySet(models.QuerySet): def search(self, query=None): if query is None or query == "": return self.none() lookups = Q(name__icontains=query) return self.filter(lookups) class ChannelManager(models.Manager): def get_queryset(self): return ChannelQuerySet(self.model, using=self._db) def search(self, query=None): return self.get_queryset().search(query=query) -
gmail is not sending from django web application
I have created a Python-Django web application. I tried to send an email to a user, but it is not working. How Can I solve it ? #SMTP Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_POSRT = 587 EMAIL_USE_TLS =True EMAIL_HOST_USER = 'fhcollege@gmail.com' EMAIL_HOST_PASSWORD = '' This from my settings.py file My views.py file is email=EmailMessage( 'PAYMENT SUCCESSFULL', 'welcome', settings.EMAIL_HOST_USER, ['fhcollege@google.com'] ) email.fail_silently = False email.send() How can I solve the issue ? The Error showing is TimeoutError at /payments/4 [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Request Method: POST Request URL: http://127.0.0.1:9000/payments/4 Django Version: 4.0.2 Exception Type: TimeoutError -
i am not able to link pages in django my code is correct .What else i need to do?
in urls.py file my code is: from django.urls import path from . import views urlpatterns = [ path("<str:name>", views.index ,name="index"), ] in views.py file my code is: from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList, Item # Create your views here. def index(response,name): ls=ToDoList.objects.get(name=name) return HttpResponse("<h1>%s</h1>" %ls.name) path also added in urls.py-mysite error showing page not found -
Remove inheritance from model retaining IDs
I have a two classes, one of which inherits from the other class Drink(models.Model): .... class Juice(Drink) .... Now, this was a mistake and I would like to remove the inheritance and have the Juice model to be a normal model Juice(models.Model). Yet, I would like to retain the sequence of IDs that are in the superclass. Due to the inheritance, the superclass has an auto ID field and the subclass has a pointer field (drink_ptr_id). What happens now when I just change the syntax is that django tries to add an auto ID field to the juice model and wants me to set a default value. The obvious problem is that I need the sequence of the supermodel to be copied into the auto ID field of the subclass model and I cannot just add a default value. A second problem - which is rather strange to me - is that the subclass already has an auto-incremented ID field, so there is a clash between the newly created field and the old id field. I tried to follow the advice given in this post: Remove model inheritance and keep id in newly created autofield, which is pretty much a … -
Why isn't Mypy inferring a 3rd-part library function's type?
Considering this code: class ExportView(IndexView): model_admin: Optional[ModelAdmin] = None def export_csv(self) -> HttpResponse | StreamingHttpResponse: fields = getattr(self.model_admin, "csv_export_fields", []) return render_to_csv_response(self.queryset.all().values(*fields)) I get the following error from Mypy on the return line: error: Returning Any from function declared to return "Union[HttpResponse, StreamingHttpResponse]" [no-any-return] render_to_csv_response is a method from django-queryset-csv, and Pyright correctly infer its return type as being a Union[HttpResponse, StreamingHttpResponse]. I thought that Mypy was not reading the 3rd-part library, as if running with --follow-imports=skip, but my pyproject.toml config has set silent, which behaves in the same way as normal [tool.mypy] plugins = ["mypy_django_plugin.main"] disallow_untyped_defs = true ignore_missing_imports = true follow_imports = 'silent' no_incremental = true warn_redundant_casts = true warn_unused_ignores = true warn_return_any = true warn_unreachable = true enable_error_code = 'ignore-without-code' show_error_codes = true Changing it to normal doesn't fix the issue either. Any idea how to get Mypy to find the proper type, like Pyright does out of the box? -
ImportError: cannot import name 'zoneinfo' from 'backports' (unknown location)
I am trying to deploy my Django model on an Apache2 server and it is running well on 'ip':8000. But when i am trying to run without 8000 port after completing all prerequisites i am getting this error [Thu Jul 07 10:18:36.178228 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module [Thu Jul 07 10:18:36.178240 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] return _bootstrap._gcd_import(name[level:], package, level) [Thu Jul 07 10:18:36.178247 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] File "/root/novo-ai-api-main/backend/dj/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 20, in <module> [Thu Jul 07 10:18:36.178253 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] from django.db.backends.base.base import BaseDatabaseWrapper, timezone_constructor [Thu Jul 07 10:18:36.178260 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] File "/root/novo-ai-api-main/backend/dj/lib/python3.8/site-packages/django/db/backends/base/base.py", line 12, in <module> [Thu Jul 07 10:18:36.178277 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] from backports import zoneinfo [Thu Jul 07 10:18:36.178308 2022] [wsgi:error] [pid 368483:tid 139647379601152] [remote 106.79.194.125:58245] ImportError: cannot import name 'zoneinfo' from 'backports' (unknown location) These are my all working files 000-default.conf <VirtualHost *:80> #ServerAdmin webmaster@localhost DocumentRoot /root/novo-ai-api-main ErrorLog /root/novo-ai-api-main/error.log CustomLog /root/novo-ai-api-main/access.log combine <Directory /root/novo-ai-api-main/backend/server/server> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /root/novo-ai-api-main/static <Directory /root/novo-ai-api-main/static> Require all granted </Directory> WSGIScriptAlias / /root/novo-ai-api-main/backend/server/server/wsgi.py WSGIDaemonProcess django_app python-path=/root/novo-ai-api-main/backend/server python-home=/root/novo-ai-api-main/backend/dj/ WSGIProcessGroup django_app … -
Struggling to display data I am trying to insert on webpage
I am currently doing CRUD with Products model and I am having a hard time displaying the data that I am trying to insert. model class Products(models.Model): categories = models.CharField(max_length=15) sub_categories = models.CharField(max_length=15) color = models.CharField(max_length=15) size = models.CharField(max_length=15) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) prod_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) show and insert function def show(request): showall = Products.objects.all() print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.POST == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') form = POLLSerializer(data = insert_clothes) if form.is_valid(): form.save() print('data',form.data) print(form.errors) messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print(form.errors) else: print('GET',id) return render(request,'polls/product_insert.html') html page of insert and show respectively <form method="POST"> {% csrf_token %} <table> <thead> <tr> <td>Categories</td> <td> <select class="form-select" aria-label="Default select example" name="categories"> <option selected>Open this select menu</option> <option value="1">9-6 WEAR</option> <option value="2">DESI SWAG</option> <option value="3">FUSION WEAR</option> <option value="">BRIDAL WEAR</option> </select> </td> </tr> <tr> <td>Sub-Categories</td> <td> <input type="text" name="sub_categories" placeholder="SUB_CATEGORIES"> </td> </tr> <tr> <td>Colors</td> <td> <input type="text" name="color" placeholder="Enter Colors"> </td> </tr> <tr> <td>Size</td> <td> <select class="form-select" aria-label="Default select example" name="size"> <option selected>Open this select menu</option> <option value="SM">SM</option> … -
Is there a signal/hook to know when a password reset has been triggered or if a password reset email has been sent in django allauth?
I'm trying to send emails via another service for password reset alone. Django only allows you to set one email provider, but I'm not sure how to delegate different emails to different email providers. Is this possible to do by listening to a signal like password_reset_sent or something similar? What I want to achieve is this: Default email sending: use client X if password reset email sending: use client Y Is this possible using django allauth? -
Django With Apache And mod_wsgi: Memory Leak?
My problem is that over time the memory usage (especially the virtual memory) increases until the system freezes. Last time the virtual memory of the "/usr/sbin/apache2 -k start" process has used over 8GB virtual memory. It was several days from the last apache2 restart. I have a virtual Machine with 1GB RAM and 15GB HDD where I have Ubuntu 22.04 installed with Apache/2.4.52 over apt with mod_wsgi, a python virtual environment where Django 4.0.5 is installed via pip. I do not run Django in daemon mode but in the "default" mode. I changed nothing in apache2.conf. My site-configuration looks like this: WSGIPythonHome /var/www/venv WSGIPythonPath /var/www/venv/fye_backend <VirtualHost *:80> ServerAdmin (my email) WSGIScriptAlias / /var/www/venv/fye_backend/fye/wsgi.py ErrorLog /var/www/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> I server the files like this code (in views.py): def example(request): key = request.GET.get("key") some_info = some_model.objects.get(key) return HttpResponse(some_info) 1 Day current Virtual Memory usage 1 Day current RAM usage If more information is needed please let me know. Thanks! -
Django Rest Framework JWT authentication - user logged in after drop database
Like I mentioned in the title. I have a DjangoRestFramework application which uses JWT token authentication on the backend. The issue occurs when I log as user, and save the token in the cookies. Next, I drop the database, and create same user with same credential programatically on the backend. Finally when I open the browser, the user is still logged in, although technically the whole database was wiped out, and set up from scratch. Is this the expected behaviour for JWT or maybe there is a way to make sure, that those tokens expire when database is dropped ? Thanks -
Django: How to get value in one model from the other model?
It feels like a very simple question, but how to get value in one model from the other one in django? I have my models.py like this: class Patient(models.Model): id = models.AutoField(primary_key=True, verbose_name='Patient ID') class Salvage_Treatment(models.Model): id = models.AutoField(primary_key=True) id_patient = models.ForeignKey(Patient, on_delete=models.CASCADE) Salvage_treatment_end_date = models.DateField() class Survival_Parameters(models.Model): id = models.AutoField(primary_key=True) salv_treat = models.ForeignKey(Salvage_Treatment, on_delete=models.CASCADE) salvage_treatment_end_date = models.DateField() id_patient = models.ForeignKey('Patient', on_delete=models.CASCADE) Let's assume that I have a patient with id_patient = 2 and I fullfiled the Salvage_Treatment form for him with id=1 (id of this form) and some date in Salvage_treatment_end_date. Now I need to have this same date to be put automatically in Survival_Parameters.salvage_treatment_end_date. How can I do that? I don't want to choose which Salvage_Treatment form to get the data from - instead I ONLY want to select the patient's ID. -
get error message on already registerd email
i got a popup on this code for sucess when someone subs to newsletter, i cant figure out how to get an popup when there is an error when it dosent work due to email already in database. with a message that email is already registerd. The multiple email code i already got in my django code that handels the multiple email part. email = models.EmailField(max_length=255, unique=True) {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} <div id="delivery-banner" class="row text-center"> <div class="col bg-success text-white"> <h4 class="logo-font my-1">Sign up to Newsletter and get 5% discount</h4> </div> <div class="content-wrapper text-center bg-warning container-fluid" id="newsletter-wrapper"> <form v-on:submit.prevent="onSubmit"> <div class="card text-black bg-warning mb-3"> <div class="card-footer"> <div class="alert alert-success" role="alert" v-if="showSuccess"> You are Subscribed to our Newsletter! </div> <h2>Subscribe to our newsletter</h2> <div class="form-group"> <input type="email" class="" v-model="email" name="email" class="input" placeholder="e-mail address" required> </div> <div class="form-group"> <button class="btn btn-success ">Submit</button> </div> </div> <div class="social"> <a target="_blank" rel="noopener noreferrer" href="https://facebook.com/" class="btn btn-social-icon btn btn-primary btn-outline-facebook "><i class="fa fa-facebook"></i></a> <a target="_blank" rel="noopener noreferrer" href="https://youtube.com/" class="btn btn-social-icon btn btn-danger btn-outline-youtube"><i class="fa fa-youtube"></i></a> <a target="_blank" rel="noopener noreferrer" href="https://twitter.com/" class="btn btn-social-icon btn btn-info btn-outline-twitter"><i class="fa fa-twitter"></i></a> <a target="_blank" rel="noopener noreferrer" … -
DRF - Inconsistency in Throttling
Hi I am facing extreme inconsistency in Throttling mechanism in Django rest framework. I have the api endpoint to throttle 10 requests/sec but when I send 20 requests at the same time using Apache Benchmark the api should throttle 10 requests whereas it throttles 4, 6 and it is inconsistent. sometimes it does not even throttle any requests. class StatusApiThrottle(CustomeRateThrottle): rate = '10/s' scope = 'status' def allow_request(self, request, view): # independent throttle for GET request on view if request.method == "POST": return True return super().allow_request(request, view) cache configuration CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "myapp" } } Run the app using gunicorn gunicorn app --workers 2 --threads=2 Testing using Apache benchMark $ ab -n 20 -c 20 -v 1 http://127.0.0.1:8080/api/v1/access/842b1012-53ef-4e98-9a20-484e681c3789 result #1 Complete requests: 20 Failed requests: 6 result #2 Complete requests: 20 Failed requests: 3 -
PermissionError: [Errno 13] Permission denied: '/app/vol/web/static'
So I deployed my Django Project on local server, using docker, but I got this error: PermissionError: [Errno 13] Permission denied: '/app/vol/web/static' Here is my settings.py: STATIC_URL = '/static/static/' MEDIA_URL='/static/media/' MEDIA_ROOT = 'vol/web/media' STATIC_ROOT = 'vol/web/static' my settings.py is located in app/app/settings.py -
comment on a blog post django
I m trying to make a comment system on a blog website with using the slug instead of pk im running into not NULL constraint failed: home_comment.post_id error my error is coming in the form_valid function in the class based view form.instance.post_id = self.kwargs['pk'] how do i do this ^ with the slug form.instance.post__slug = self.kwargs['slug'] (this is showing an error) views.py class AddCommentView(CreateView): model = Comment form_class = AddCommentForm template_name = "add_comment.html" def form_valid(self, form): form.instance.post__slug = self.kwargs["slug"] form.instance.name = self.request.user return super().form_valid(form) models.py class Post(models.Model): title = models.CharField(max_length=1000, default="Title") author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=1000, default="Category") body = models.TextField(default="This is the Body of the Post.") slug = models.SlugField(max_length=1000, null=True, blank=True) created_time = models.DateTimeField(auto_now_add=True) created_date = models.DateField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) updated_date = models.DateField(auto_now=True) likes = models.ManyToManyField(User, related_name="blog_posts_likes") dislikes = models.ManyToManyField(User, related_name="blog_posts_dislikes") class Meta: verbose_name_plural = "Blogs & Posts" def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = generate_slug(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return f"/blogs/post/{self.slug}" class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") name = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateField(auto_now_add=True) time_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Post Comments" def __str__(self): return "%s - %s" % (self.post.title, self.name.username) def get_absolute_url(self): return f"/blogs/post/{self.post.slug}" html file {% … -
Insert data using serializer class django-rest-framework
I am a beginner with Django and especially with the Django REST framework. Inside "UserRegistration" class, I want to create a new user and ExtendUser using "UserSerializer". how can I do that? this is my models.py class ExtendUser(models.Model): user = models.OneToOneField(User, related_name='user_name', on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=16) picture = models.ImageField(upload_to='userImages/', default="default.webp", blank=True) def __str__(self): return str(self.user) this is my serializers.py class UserSerializer(serializers.ModelSerializer): password2 = serializers.CharField(write_only=True, style={'input_type':'password'}) class Meta: model = User fields = ['email', 'first_name', 'password', 'password2'] extra_kwargs = {'password' : {'write_only':True,}} def save(self): name = self.validated_data['first_name'] password = self.validated_data['password'] password2 = self.validated_data['password2'] if len(password) < 8: raise serializers.ValidationError({'error':'Password must be 8-16 Characters '+ 'and contain both numbers and letters/special character.'}) if password != password2: raise serializers.ValidationError({'Password':'Password and Confirm Password Should be Same!'}) email = self.validated_data['email'] if User.objects.filter(email=email).exists() == True: raise serializers.ValidationError({'E-mail': f"{email} this email already been used. Try another email."}) user = User.objects.create_user(username=email, email=email, password=password, first_name=name) return user class ExtendUserSerializer(serializers.ModelSerializer): class Meta: model = ExtendUser fields = '__all__' this is my views.py class UserRegistration(APIView): def post(self, request): user = UserSerializer(data=self.request.data) if user.is_valid(raise_exception=True): user.save() refreshToken = RefreshToken.for_user(user) context = {'access': str(refreshToken.access_token), 'refresh': str(refreshToken)} return Response(context, status=status.HTTP_201_CREATED) return Response(user.errors, status=status.HTTP_400_BAD_REQUEST) -
Best practice to read and filter a big CSV file in Django
I'm researching the way to read a big CSV file and display it as a datatable in Django admin. I need the filter function as well. Could anyone suggest to me which library to support? -
Block Content Tag Not Working In Django When Inheriting From Base.html
I have seen other questions like this but none of them solve my issue. I have been using Django for a while and i have been exploring the block content part now. But i have run into a problem. The base.html looks like this: and my home.html looks like this: as per the internet the home.html page should have hello and replaced text. But I only see hello in the page it would be amazing if you would be able to help me on this as soon as possible. :) -
Saving logged in user info in django model
I am trying to update planTable model with the current logged in user automatically. In my planForm form, I have excluded "user" field. These are my code snippets. views.py def createPlan(request): form = planForm if request.method == "POST": form = planForm(request.POST) if form.is_valid(): form.save() return redirect('index') context = {'form':form} return render(request, 'workoutapp/create_plan.html', context) @login_required(login_url='/register_user/') def myPlan(request): my_plan = planTable.objects.filter(user=request.user) print('user : ', request.user) #print('data : ', my_plan) context = {'my_plan':my_plan} return render(request, 'workoutapp/my_plan.html', context) models.py class planTable(models.Model): DAYS = ( ("sunday", "sunday"), ("monday", "monday"), ("tuesday", "tuesday"), ) day = models.CharField(null=True, max_length=10, choices=DAYS) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) category = models.ForeignKey(workoutTable, null=True, on_delete=models.CASCADE) exercise = models.ForeignKey(itemTable, null=True, on_delete=models.CASCADE) def __str__(self): return self.day forms.py class planForm(ModelForm): class Meta: model = planTable fields = 'day', 'category', 'exercise' create_plan.html <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="submit"> </form> My requirement is that when the logged in user clicks on submit button, the fields in planTable should get populated with the values. But after logged in user click on submit button, only day, category and exercise gets populated, the user field stays blank. Is there any way for the user field to get populated depending on the logged in user? -
MultipleObjectsReturned() in Django error
I have posted the code below, when I try to view this model as an object in http://127.0.0.1:8000/admin/ I get the following error: MultipleObjectsReturned at /admin/configuration/epemployeeposition/2/change/ get() returned more than one Epemployeeposition -- it returned more than 20! Does anyone know how to fix this? I would greatly appreciate the help! This is my model of the object giving me an error in models.py. To create this model I autogenerated it from the postgres database using python manage.py inspectdb. I have only removed manage = False in the Meta class postgres database: Postgres Database View models.py: class Epemployeeposition(models.Model): companyid = models.IntegerField(db_column='CompanyID', primary_key=True) employeeid = models.IntegerField(db_column='EmployeeID') linenbr = models.IntegerField(db_column='LineNbr') isactive = models.BooleanField(db_column='IsActive') positionid = models.CharField(db_column='PositionID', max_length=20, blank=True, null=True) startdate = models.DateTimeField(db_column='StartDate', blank=True, null=True) startreason = models.CharField(db_column='StartReason', max_length=3) enddate = models.DateTimeField(db_column='EndDate', blank=True, null=True) isterminated = models.BooleanField(db_column='IsTerminated') termreason = models.CharField(db_column='TermReason', max_length=3, blank=True, null=True) isrehirable = models.BooleanField(db_column='IsRehirable') noteid = models.UUIDField(db_column='NoteID') createdbyid = models.UUIDField(db_column='CreatedByID') createdbyscreenid = models.CharField(db_column='CreatedByScreenID', max_length=8) createddatetime = models.DateTimeField(db_column='CreatedDateTime') lastmodifiedbyid = models.UUIDField(db_column='LastModifiedByID') lastmodifiedbyscreenid = models.CharField(db_column='LastModifiedByScreenID', max_length=8) lastmodifieddatetime = models.DateTimeField(db_column='LastModifiedDateTime') tstamp = models.BinaryField() class Meta: db_table = 'EPEmployeePosition' unique_together = (('companyid', 'employeeid', 'linenbr'), ('noteid', 'companyid'),) Here is the full Traceback of the error Traceback: Traceback (most recent call last): File "/home/descartes/source/bitserf/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in … -
Field 'id' expected a number but got '' in django
blog_id is not get. help me to solve this --- models.py class Blog(models.Model): title = models.CharField(max_length=500) body = models.TextField() last_updated_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add=True) author_instance = models.ForeignKey(AuthorInstance, on_delete=models.PROTECT) status_draft = models.BooleanField(default=False, blank=True, null=True) status_publish = models.BooleanField(default=False, blank=True, null=True) likes = models.ManyToManyField(UserInstance, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') def total_likes(self): return self.likes.count() views.py def like_post(request): post = get_object_or_404(Blog, id=request.POST.get('blog_id')) how to solve????