Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django not sending mail even if password is wrong its showing email sended
I have been struggling to solve this for the last 3 hours but couldn't find it. My problem is that Django is not sending email and even if I enter the wrong username and password it shows successful .It never sends mail. Please tell me what I am doing wrong.Here is my settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '******************' EMAIL_HOST_PASSWORD = '********' My urls.py file: path('reset_password_complete',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done'), path('reset_password/',auth_views.PasswordResetView.as_view(),name="reset_password"), I am using the default view of Django but even if my password is wrong or username is wrong it shows me email has been sent but it has not.Please help me. -
Reverse for 'likes' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['datasecurity/likes/<int:pk>'] Like buttton error in django
registration and login page is working properly but mine like button is not working .. I don't know why... Can somebody help me to solve this issue … it will be great help please help Thank you! views.py` from django.shortcuts import render, get_object_or_404 from datasecurity.models import Post from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login required # Create your views here. def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() context={"post":post} return render(request, "datasecurity/blogHome.html", context) @login_required def likes(request, pk): post=get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:blogHome', args=str(pk))) urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/<int:pk>', views.likes, name = "likes"), ] data.html {% extends 'careforallapp/navbar.html' %} {% block body_block %} {% load static %} Welcome to Data Security {% for post in allPosts %} <div class="line-dec"></div> <span >This is a Bootstrap v4.2.1 CSS Template for you. Edit and use this layout for your site. Updated on 21 May 2019 for repeated main menu HTML code.</span > </div> <div class="left-image-post"> <div class="row"> <div class="col-md-6"> <div class="left-image"> {% if post.img %} <img src="{{ post.img.url }}" alt="" /> {% endif %} </div> </div> <div … -
LayoutError at /invoice/ Flowable <PmlTable@0x1D09C899130 7 rows x 5 cols(tallest row 841)> with cell(0,0)
I am trying to print invoice in pdf format in django i used xhtml2pdf to convert html doc to pdf but when i try to run my code it gives me this error : LayoutError at /invoice/ Flowable <PmlTable@0x1D09C899130 7 rows x 5 cols(tallest row 841)> with cell(0,0) containing '<PmlKeepInFrame at 0x1d09b77d670> size=x'(538.5826771653543 x 5893.228346456693), tallest cell 841.9 points, too large on page 2 in frame 'body'(538.5826771653543 x 785.19685039370 this is in my views.py from django.http import HttpResponse from django.views.generic import View from booking.utils import render_to_pdf from django.template.loader import get_template class GeneratePDF(View): def get(self, request, *args, **kwargs): template = get_template('invoice.html') context = { "invoice_id": 1234, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", } html = template.render(context) pdf = render_to_pdf('invoice.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") and this is my urls.py from django.urls import path from booking.views import GeneratePDF app_name = 'booking' urlpatterns = [ path('invoice/', GeneratePDF.as_view(), name ="invoice"), ] -
How to properly upload files when also sending data to the server
I have implemented an view that is for registering an organization. How do I successfully upload files given the following payload: { "admin":{ "username":"kapyjovu@abyssmail.com", "first_name":"Cindy", "last_name":"Georgia", "password":"password", "email":"kapyjovu@abyssmail.com" }, "org":{ "name":"ARIZONA LAW SOCIETY", "short_name":"ALS", "tag_line":"ALS", "email":"kapyjovu@abyssmail.com", "company_phone": "+2540000000", "po_box": "200", "location":"NAKURU", "first_logo": "https://www.mintformations.co.uk/blog/wp-content/uploads/2020/05/shutterstock_583717939.jpg", "second_logo": "https://www.mintformations.co.uk/blog/wp-content/uploads/2020/05/shutterstock_583717939.jpg", "third_logo": "https://www.mintformations.co.uk/blog/wp-content/uploads/2020/05/shutterstock_583717939.jpg" } } class OrganizationRegistration(generics.CreateAPIView): queryset = Organization.objects.all() permission_classes = (permissions.AllowAny,) serializer_class = OrgRegistrationSerializer """End point to register organization""" def post(self, request, format=None, *args, **kwargs): try: admins = Group.objects.get(name__iexact='admin') admin_role = Role.objects.get(name__iexact="admin") except: # the admin group is admins = Group.objects.create(name="admin") admin_role = Role.objects.create(name="admin") # finally: try: admin = User.objects.create( username=request.data['admin']['username'], email=request.data['admin']['email'], first_name=request.data['admin']['first_name'], last_name=request.data['admin']['last_name'], ) location_name = request.data['org']['location'].upper() location_obj, _ = Location.objects.get_or_create(name=location_name) area_name = location_obj.name except Exception as e: # print(e) return Response(data={"msg":str(e),"success":False, "data": None},status=status.HTTP_400_BAD_REQUEST) # admin.set_password(request.data['admin']['password']) try: # Create Random Password password = User.objects.make_random_password(length=10) admin.set_password(password) admin.save() # add the user creating the Organization to the admin group # admins.user_set.add(admin) admin.groups.add(admins) admin.roles.add(admin_role) first_file_logo = request.data['org']['first_logo'] second_file_logo = request.data['org']['second_logo'] third_file_logo = request.data['org']['third_logo'] org = Organization.objects.create( name=request.data['org']['name'], email=request.data['org']['email'], location=request.data['org']['location'], short_name = request.data['org']['short_name'], tag_line = request.data['org']['tag_line'], company_phone = request.data['org']['company_phone'], po_box = request.data['org']['po_box'], first_logo = first_file_logo, second_logo =second_file_logo , third_logo = third_file_logo ) admin.org_id = org.id admin.save() # add the user creating the Organization to admins by DEFAULT … -
How to access the items inside a list of query sets in django?
I have to display MULTIPLE posts from MULTIPLE users that the logged in user is currently following on a single page using the django templates. This is the function I've written: def following(request, userName): userProfiles = FollowingList.objects.filter(listOwner = request.user) print("userProfile is ", userProfiles) listOfAllPosts = [] #get posts against following for uP in userProfiles: getPosts = Posts.objects.filter(created_by = uP.followingID) print("Value of getPosts is", getPosts) for i in getPosts: listOfAllPosts.append(getPosts.values('created_by', 'postContent', 'dateAndTime')) print("Printing ALL posts", listOfAllPosts) return render(request, "network/following.html", { "listOfAllPosts" : listOfAllPosts }) The result I get from the listOfAllPosts looks like this: [<QuerySet [{'created_by': 12, 'postContent': 'I have hot air balloon rides', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 21, 3, 192704, tzinfo=<UTC>)}, {'created_by': 12, 'postContent': 'adding second post', 'dateAndTime': datetime.datetime(2021, 2, 1, 7, 2, 51, 734510, tzinfo=<UTC>)}]>, <QuerySet [{'created_by': 11, 'postContent': 'Hello Sifaah', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 4, 31, 410825, tzinfo=<UTC>)}]>] However, I want the result to look like this so I can easily print it on the HTML page: [<QuerySet[{'created_by': 12, 'postContent': 'I have hot air balloon rides', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 21, 3, 192704, tzinfo=<UTC>)}, {'created_by': 12, 'postContent': 'adding second post', 'dateAndTime': datetime.datetime(2021, 2, 1, 7, 2, 51, 734510, tzinfo=<UTC>)}, {'created_by': 11, 'postContent': 'Hello Sifaah', 'dateAndTime': … -
Getting to next page via correct user input in Django
i wanted to create some "riddle" page but i got stuck in creating the functionality of the riddle itself. So what I want to do is, I want to have just a plain html page where i can put some text/pictures etc. and at the end of that block there should be a user input prompt with a commit/send button. If the input is the correct answer to the riddle, the user should get to the next riddle stage. If not, he/she should get an info that the answer wasnt correct. As I am learning Django right now I wondered how it should be designed according to it, and therefore I have no sample code or anything. I would really appreciate some help on how to do that, because from what I understand i would need a function that takes the user input, compares it to some kind of a "solution database" and, depending on input, shows the user the specific page. I already found some more sophisticated site protections to mimic this : https://github.com/MaxLaumeister/pagecrypt/tree/master/python but for my causes i think its a bit over the top. Perhaps this topic is interesting for some of you, Thank you! -
Accessing global dictionaries
I don't think there's much explanation to this, the problem is straight forward. I get an error saying Error: "if i in items: NameError: name 'items' is not defined" code: class Cart: items = {} def addToCart(item): global items for i in item: if i in items: items[i] += item[i] else: items.update(item) def removeFromCart(item): global items for i in item: if i in items and items[i] > 1: items[i] -= 1 elif i in items and items[i] <= 1: items.pop(i, None) -
How to Share Files Through Django Channels, now there are incomplete solutions like from S3 buckets and all
I'm developing a chat application in Django and I want to share files through django channels. I just found some solutions that are based on this topic, but all are incomplete. So please help me for figure it out. Now I'm sending messages like the below mentioned code.. document.querySelector('#chat-message-submit').onclick = function(e) { let msg = $('#chat-message-input').val() var messageInputDom = document.querySelector('#chat-message-input'); var message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'command':'new_message', 'message': message, 'from': username, })); messageInputDom.value = ''; } -
How to make Django output PDF from DIV?
I am trying to render PDF from certain DIV (and what is contained within DIV) in Django project. Get a pdf file with contents of "printMe" div.. <div id="dontPrintMe"> content </div> <div id="printMe"> content (including lot of other divs, tables and css) </div> I tried a lot of things.. JSPdf: it would work, but within the DIV i have a lot of tables and JSPdf is giving me errors.. html2canvas: it doesn't work at all, the qualitty is crap xhtml2pdf: this didn't worked at all, no idea why.. Can you recommend me a way, how to output a certain part of a website as a PDF? I think i could do this with Django, but every tutorial i found is about making a pdf from scratch, not converting a current website that is based on template (and html and css) to convert with click of a button to "Download PDF".. for now i am using document.print() and it kinda works, but when saving as PDF it doesn't use generated name for PDF.. And this is actually my first Django project, i just got stucked here.. Maybe it is not possible at all? Thanks! This is what i am using now, … -
Django contact form with user supplied email address without using email delivery service
so my last question was confusing, so I'm hoping this time is better. I want to implement a contact form in django that a user enters their email address into. The one way I've found on how achieve is with an email delivery service like sendgrid, but i want to know if it's possible without an email delivery service. This my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'server.domain.tld' EMAIL_HOST_USER = 'info@domain.tld' EMAIL_HOST_PASSWORD = 'email_password' EMAIL_PORT = 587 EMAIL_USE_TLS = True This is my forms.py: class ContactForm(forms.Form): from_email = forms.EmailField( required=True, widget=forms.EmailInput(attrs={"placeholder": "Your email address", "class": "heading"}), label='' ) subject = forms.CharField( required=True, widget=forms.TextInput(attrs={"placeholder": "Your subject", "class": "heading"}), label='' ) message = forms.CharField( required=True, widget=forms.Textarea(attrs={"placeholder": "Your message here"}), label='' ) This is my views.py def contact_page_view(request): contact_query = ContactForm(request.POST or None) if request.method == 'POST': if contact_query.is_valid(): from_email = contact_query.cleaned_data['from_email'] subject = contact_query.cleaned_data['subject'] message = contact_query.cleaned_data['message'] try: send_mail(subject, message, from_email, ['info@openitmation.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponse('Message successfully sent.') return render(request, 'pagesapp/contact.html', {'contact_sub': contact_query}) The current problem with my code is that it will only send successfully when "from_email" email matches the account in settings.py, times out otherwise. Anyone know how to configure django to send using a user … -
The relationship between Model A and Model B is based on the display of information about Model B from the Model A information filter In django
I have a model called tag in which there is a category field for the input word. Now I want to use the tag model in my product model so that only the words in the product category are displayed I have no idea for it this is TAG model: class TAG(models.Model): class categorychoices(models.TextChoices): general = 'general', _('عمومی') product = 'product', _('محصول') post = 'post', _('مقاله') main = 'main', _('صفحه اصلی') product_list = 'product_list', _('صفحه لیست محصولات') product_detail = 'product_detail', _('صفحه جزییات محصول') gallery = 'gallery', _('گالری') about = 'about', _('صفحه تماس با ما') contact = 'contact', _('صفحه ارتباط با ما') blog = 'blog', _('صفحه بلاگ') category = models.CharField(max_length=15, verbose_name='تنظیم برای', default=categorychoices.general, choices=categorychoices.choices) word = models.CharField(max_length=50, verbose_name='کلمه کلیدی', default=' ') and this is Product model : class Product(models.Model): name = models.CharField(max_length=50, verbose_name="نام محصول") category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, verbose_name="دسته بندی") image = models.ImageField(upload_to="products", verbose_name=" تصویر محصول") video_aparat = models.CharField(max_length=100, verbose_name='لینک ویدیو در آپارات', default='link',help_text='لینک را از قسمت اشتراک گذاری و قسمت embed کپی کنید کلمه embed باید داخل لینک باشد') video_youtube = models.CharField(max_length=100, verbose_name='لینک ویدیو در یوتیوب', default='link',help_text='لینک را از قسمت اشتراک گذاری و قسمت embed کپی کنید کلمه embed باید داخل لینک باشد') tag = models.ManyToManyField(TAG, verbose_name='کلمه کلیدی') active = … -
I deployed a django project on Heroku. When i set debug = True, everything works, when i set debug=False, It gives me server 500 error
I deployed a django project on Heroku. When i set debug = True, everything works, when i set debug=False, It gives me server 500 error both on local server and heroku production server. Allowed hosts is already set. everything is properly configured. Also kindly help me how to handle the secret key in heroku. project is hosted in Git hub. kindly go through the link https://github.com/peter-nani/core_project -
the redis.py causing errors i dont know why it is wrong celery==5.0.5 and redis ==3.5.3 and project is done in docker
celery_shopify1 | celery_shopify1 | Please specify a different user using the --uid option. celery_shopify1 | celery_shopify1 | User information: uid=0 euid=0 gid=0 egid=0 celery_shopify1 | celery_shopify1 | warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( celery_shopify1 | [2021-02-02 04:31:16,480: CRITICAL/MainProcess] Unrecoverable error: SyntaxError('invalid syntax', ('/usr/local/lib/python3.8/site-packages/celery/backends/redis.py', 22, 15, 'from . import async, base\n')) celery_shopify1 | Traceback (most recent call last): celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in get celery_shopify1 | return obj.dict[self.name] celery_shopify1 | KeyError: 'backend' celery_shopify1 | celery_shopify1 | During handling of the above exception, another exception occurred: celery_shopify1 | celery_shopify1 | Traceback (most recent call last): celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/worker/worker.py", line 205, in start celery_shopify1 | self.blueprint.start(self) celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 115, in start celery_shopify1 | self.on_start() celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/apps/worker.py", line 139, in on_start celery_shopify1 | self.emit_banner() celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/apps/worker.py", line 154, in emit_banner celery_shopify1 | ' \n', self.startup_info(artlines=not use_image))), celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/apps/worker.py", line 217, in startup_info celery_shopify1 | results=self.app.backend.as_uri(), celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 44, in get celery_shopify1 | value = obj.dict[self.name] = self.__get(obj) celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/app/base.py", line 1196, in backend celery_shopify1 | return self._get_backend() celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/app/base.py", line 912, in _get_backend celery_shopify1 | backend, url = backends.by_url( celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/app/backends.py", line 70, in by_url celery_shopify1 | return … -
Django backend with React frontend & using filterset API - how to fetch data?
I have setup an app with a Django backend and React frontend. If I type a URL into a browser I get the correct data back from Django. How do I construct the URL argument for the fetch call in React to take account of the API options? Here's the raw URL that works: 127.0.0.1:8000/api/app/?quantity=2&zip=&id= -
django is_valid returns false for model form even though all fields have a value
Why does this returns an invalid form? I click browse, select a csv file, select a user, check the boolean box, and submit. upload.html <form action = "" method = "POST" class = "mtop-25"> {% csrf_token %} {{form}} <button type = "submit" >Upload File</button> </form> models.py class Csv(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) file_name = models.FileField(upload_to='csvs', max_length = 100) public = models.BooleanField(default = False) def __str__(self): return "File id: {}".format(self.id) forms.py class CsvForm(forms.ModelForm): class Meta: model = Csv fields = '__all__' labels = {'file_name' : 'Browse'} views.py def upload(request): form = CsvForm if request.method == 'POST': form = CsvForm(request.POST or None, request.FILES or None) return HttpResponse(form.is_valid()) else: return render(request, 'upload/upload.html', {'form' : form}) -
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