Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django throwing error like " 'function' object has no attribute 'order_set' "?
I have edited views.py and after that it is throwing error like the screenshot below. Here are the codes. /apps/views.py contains from django.shortcuts import render from django.http import HttpResponse from .models import * def customer(request, pk): customers = Customer.objects.get(id=pk) order = customer.order_set.all() context={'customers':customers, 'order':order} return render(request, 'accounts/customer.html',context) and /templates/apps/name.html contains this code to render data from models to templates. {% for i in order %} <tr> <td>{{i.product}}</td> <td>{{i.product.category}}</td> <td>{{i.date_created}}</td> <td>{{i.status}}</td> <td><a href="">Update</a></td> <td><a href="">Remove</a></td> </tr> {% endfor %} I think this error has something to do with order_ser in views.py but i am not sure how to fix it. -
How to host Django project using FTP or cPanel on Hostgator
I want to host a my django website on hostgator but i don't know how to host a website in hostgator How to host Django project using FTP or cPanel on Hostgator can you please me -
Giving error 500 instead of 404 when debug is False Django
myapp/urls.py: handler404 = 'blog.views.not_found' handler500 = 'blog.views.server_error' views: def not_found(request, exceptions): return render(request, 'error/404.html') def server_error(request): return render(request, 'error/500.html') settings.py: DEBUG = False ALLOWED_HOSTS = ['*'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'staff.context_processors.staff_base', 'blog.context_processors.cart', 'blog.context_processors.setting', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' 404.html: {% extends 'blog/base.html' %} {% load static %} {% block title %}400{% endblock title %} {% block content %} <p>404 Error</p> {% endblock content %} in DEBUG = True show me regular 404 error, but in DEBUG = False show me 500 instead of 404 I saw other topics about this issue but i couldn't find any thing to help me. -
Django sub template not appearing in outputted html
I'm working with django 1.10 and python 3.6 in win 10. In my main template (index.html) I have: <div class="col-lg-5 col-sm-6"> <div class="clearfix"></div> <h2 class="section-heading">We can help:</h2> {% block 'body' %} {% endblock %} </div> need3.html template: {% extends 'index.html' %} {% block 'body' %} <p><big>Hello, ...... {% endblock %} my code has: def index(request): form = MyForm() return render(request, 'index.html', {'form': form, 'hero_phrase': 'Would you be interested in x?','body':'need3.html'}) However as you can see in the screenshot need3 template does not show up. What am I doing wrong? -
mod_wsgi: ModuleNotFoundError: No module named "xxx"
There's about a hundred posts on this subject and none of them seem to have much rhyme or reason. My configuration: Trying to build a container via Podman with Apache + mod_wsgi (4.6.4) + Django, there is no virtualenv. Install of compiled libs via CentOS package repo binaries. Python 3.6 via CentOS repo binary. Install of pure python libs via pip, to --user (/home/user/.local) Project folders are in /home/apache, no need for anything static I'll push all of that to a CDN. The test file example from the docs works fine. Migrations and post-migration signals work fine. The dev server works fine with the current config. The only environment variable I have specified Django and base-Python related is DJANGO_SETTINGS_MODULE which is set correctly to my base settings file. Apache config, straight from the Django 3.2 docs: WSGIPythonPath /home/apache <VirtualHost *:8080> ServerName localhost WSGIScriptAlias / /home/apache/base/wsgi.py <Directory /home/apache/base> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> And the result: [ 09:20:57.757787 2021] [wsgi:error] [pid 5:tid 140007184484096] Traceback (most recent call last): [ 09:20:57.758173 2021] [wsgi:error] [pid 5:tid 140007184484096] File "/home/apache/base/wsgi.py", line 16, in <module> [ 09:20:57.758542 2021] [wsgi:error] [pid 5:tid 140007184484096] application = get_wsgi_application() [ 09:20:57.758740 2021] [wsgi:error] [pid 5:tid 140007184484096] … -
Why extra_kwargs is used if it can be replaced?
I am writing a project using django-rest-framework and while using serializers, I realized that most of the keywords in extra_kwargs like "required, read_only, write_only, etc." can be substituted by read_only_fields, write_only_fields, "required" in serializer fields, etc. Does extra_kwargs have some feature that is unique? -
Json Response's innerHTML is showing multiple times every time save button is clicked in browser
I am building a BlogApp and I am trying to save form without refresh the page, So i am using ajax and Everything is working fine - Form is submitting fine. I am showing user a success message using innerHTML when form is submit BUT when i click submit button multiple time then innerHTML is also showing multiple times. views.py def blog_post_form(request): if request.is_ajax and request.method == 'POST': form = BlogPostForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() ser_instance = serializers.serialize('json',[ instance, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error":""}, status=400) template.html <form id="blogpost-form"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-primary" value="Submit" /> <form> <div class="container-fluid"> <table class="table table-striped table-sm" id="success"> <tbody> </tbody> </table> </div> <script> $(document).ready(function () { $("#blogpost-form").submit(function (e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: "{% url 'blog_post_form' %}", data: serializedData, success: function (response) { var instance = JSON.parse(response["instance"]); var fields = instance[0]["fields"]; $("#success tbody").prepend( `<h2>SuccessFully Saved</h2>` ) }, error: function (response) { alert(response["responseJSON"]["error"]); } }) }) }) </script> I tried multiple times by changing div data but it is still showing multiple times. Any help would be Much Appreciated. Thank You in Advance. -
pick color by evaluating string condition
I Have a data like below, using python I need to check criteria key and update the color any possible easy way to do that ? where criteria might come with more conditions like < > = != etc. { "data":{ "data1"{ "p1"{ "pre":"x", "post":"y", "delta:"", "color":"z", "criteria""if X < 2 then Z='#FF0011' else Z='#00FF00'" }, "p2"{ "pre":"x", "post":"y", "delta:"", "color":"z", "criteria""if X <= 10 then Z='#FF0000' else Z='#00FF00'" }, "p2"{ "pre":"x", "post":"y", "delta:"", "color":"z", "criteria""if X < 10, y > 5 then Z='#FF0000' else Z='#00FF00'" }, "p2"{ "pre":"x", "post":"y", "delta:"", "color":"z", "criteria""if X =0, y >5 then Z='#FF0000' else Z='#00FF00'" }, } } } -
How to display one <ul> list into unlimited columns?
I'm using Django for backend and I want to display the below ul in unlimited columns with overflow-x : auto. <ul class="list"> {% for i in skills %} <li>{{i}}</li> {% endfor %} </ul> sample output: 1 7 . . . 2 8 . . . 3 9 . . . 4 10 . . . 5 11 . . . 6 12 . . . -
Delay Kubernetes Deployment from Python Client
I have a Django software that, using Kubernetes Official Client to interface with my kubernetes cluster and deploy pods. These pods are dockerized Scala SBT apps, and as soon as I launch them all together, it takes a lot of time to compile. Putting some time.sleep() will actually optimize the releases, but it will also delay the response.. And i have to avoid this. I'm trying to see about multiprocessing and actually works on a test file, which is: import time from multiprocessing import Pool def test1(): time.sleep(1) print("before test1: " + str(time.time())) time.sleep(3) print("after test1: " + str(time.time())) def test2(): print("before test2: " + str(time.time())) time.sleep(4) print("after test2: " + str(time.time())) def main(): print(time.time()) pool = Pool() result1 = pool.apply_async(test1) result2 = pool.apply_async(test2) result1.get() result2.get() main() Infact, the "after test1" and "after test2" will be executed at the same time. But when i transfer these statements where it's needed, it stops parallelizing. the structure of the test file is the same of where i need it. a def with the pool instanciating defs inside, and a sleep inside these defs. I also tried using other libraries, like threading, asyncio etc.. all worked fine in the test file. I was … -
Fields of QuerySet are not accessible from views.py in Django
I am trying to create a track report since past two weeks in which I'm constantly failing. I have 3 models, Student, Course and Fee. I want to create a report which will bring all the data contained by these 3 models, together, with an ID of its own. The models: class Student(models.Model): roll_number=models.IntegerField(primary_key=True) name=models.CharField(max_length=50) email=models.EmailField(max_length=60) city=models.CharField(max_length=20) class CourseChoices(models.Model): courses=models.CharField(max_length=30, blank=True) def __str__(self): return self.courses class Course(models.Model): roll_number=models.ForeignKey(Student, on_delete=CASCADE) course=models.ForeignKey(CourseChoices, on_delete=CASCADE) class Fee(models.Model): roll_number=models.ForeignKey(Student, on_delete=CASCADE) amount_to_be_paid=models.DecimalField(max_digits=7, decimal_places=2, default=0) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Final_amount_to_be_paid=models.DecimalField(max_digits=5, decimal_places=2, default=0) Amount_received=models.DecimalField(max_digits=5, decimal_places=2, default=0) Balance=models.DecimalField(max_digits=5, decimal_places=2, default=0) batch=models.IntegerField() Now, a student may pay his/her fee in installments, so that will create multiple instances in the track report. I want the user to track each transaction with the primary key/id. Below is an example: One member here suggested me to create another model named Report: class Report(models.Model): id = models.CharField(max_length=7, primary_key=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) fee = models.ForeignKey(Fee, on_delete=models.CASCADE) def _get_next_id(self): last = self.objects.aggregate(max_id=models.Max('id'))['max_id'] if last is None: last = 1 self.id = "{}{:04d}".format('HB', last) def save(self, *args, **kwargs): if not self.id: self.id = self._get_next_id() super().save(*args, **kwargs) And then when the transaction happens - I save an additional instance of Report that contains links … -
python requests json argument not converted to URL parameters
I have a Django backend and can receive and respond to query parameters such when in URL: http://localhost:8000/stac_management/stac/search?bbox=115.378418,5.375398,127.199707,19.352611 When using python requests to send a POST, using the params argument also respond well since the query parameters are converted and passed into the url same as above. import requests import json #URL='https://api.ops.dev.phl-microsat.upd.edu.ph/stac_management/stac/search' URL='http://localhost:8000/stac_management/stac/search' payload = {'bbox': '115.378418,5.375398,127.199707,19.352611'} response = requests.post(URL, params=payload) print('url:', response.url) # url: http://localhost:8000/stac_management/stac/search?bbox=115.378418,5.375398,127.199707,19.352611 However, when I use the json argument for request the payload does not convert to query parameters. Thus my backend cannot receive a query parameter. response = requests.post(URL, json=payload) print('url:', response.url) # url: http://localhost:8000/stac_management/stac/search I am using a library that will POST to my backend and it is using the json argument for requests. I am having problem receiving the query parameters since what I get is None. I am using Django Viewset and expecting the bbox using: class SearchViewSet(viewsets.ViewSet): permission_classes = [AllowAny] def list(self, request): ... bbox = request.query_params.get('bbox', None) How can I receive a query parameter when using the json argument from requests into my Django app? Also the fix is should be within my backend since I cannot change the library for using json argument. -
Django and DevOps roadmap [closed]
Hey everybody I've been searching the whole internet for help in finding the roadmap for Django framework and DevOps engineer. I already read some docs and find some roadmaps like https://roadmap.sh/ but these documents are so general. in my case, I want to Grouping developers by their skill like when someone comes to our team I show them the learning roadmap and tell them due to this roadmap you are junior if you want to be a senior developer you must learn these things too. I know this method is not so good for measuring developers levels but this is the begging of my journey. I need your comments, sources, articles, or every other thing that can help me. in general, I want to make a roadmap for those who want to see their progress and can help themselves. by this you know if you learn other things it will help you be a better developer or DevOps and can find better job offers. thank you, all. -
OSError: [WinError 123] while installing allauth in django
The problem is so simple. I've installed django all auth, all based on documentation: Running pip install django-allauth on cmd Changing settings.py installed apps to: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', # Third party apps 'rest_framework', 'api', 'management', ] And then I cannot run the server, getting the below error: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' What I have done to solve the problem: I searched several questions and realized there can be two reasons for this error: When the package is not installed. For this, I checked my virtual env packages using pip list and well, django-allauth is installed. When we got misspelling. For this one, I've just copied and pasted all required options directly from the documentations. There cannot be any misspelling. Any help is appreciated! -
How to resolve ValueError while deploying Django project on IIS?
On begining, i dont have experience in deploy on production, so please forgive my stupid question. What i have done: all steps from toturial https://www.youtube.com/watch?v=APCQ15YqqQ0&t=882s , it's call Default Web Site, and it works, by analogy i deploy my project called SLK but on port 81 on second web site, and tree looks like this: i change web.config for project SLK, moved it to main catalog C:\inetpub\wwwroot (at toturial was web.config maid for toturial project, i changed all entries for my project) turn off Default Web Site, turn on my and got this masage on IIS, on localhost:81: When i start project manualy in 127.0.0.1:8000 on Debug mode it's works. Please for sugestions and ideas Django ver 3.2 Python ver 3.9 Windows 10 -
how to django graphql framework add social account in google and facebook login?
how to use social account in django graphql framework Google login Facebook login I'm trying to implementation of django social account add query and mutation on graphql rest framework. I don't know use graphql framework. Any one answer me, very kind thankful mine -
How to post an image on Django Rest server using fetch API?
I have a Django Rest Framework view that accepts an image and a style sting: class PostImage(APIView): serializer_class = GetImageSerializer parser_classes = [MultiPartParser] def post(self, request, format=None): print(request.data) # debug img = request.data.get('image') ... response = FileResponse(img) return response I get the correct output using Postman. Here's the curl command that it executes: curl --location --request POST 'http://127.0.0.1:8000/style_transfer/style/' \ --form 'image=@"/C:/User/949690-kg.jpg"' \ --form 'style ="models\\\\tokyo_ghoul\\\\tokyo_ghoul_aggressive.pth"' Here's the javascript snippet generated by postman for the same task. I've added content-type because it is required by DRF. var formdata = new FormData(); formdata.append("image", fileInput.files[0], "/C:/Users/949690-kg.jpg"); formdata.append("style\n", "models\\\\tokyo_ghoul\\\\tokyo_ghoul_aggressive.pth"); var requestOptions = { method: 'POST', body: formdata, redirect: 'follow', headers: { "Content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" } }; fetch("http://127.0.0.1:8000/style_transfer/style/", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); On executing the above snippet on postman, I get the following error: { "detail": "Unsupported media type \"application/javascript\" in request." } The strange part is that the curl command generated by postman work as expected. I have also asked this question a few days back here, and it has some more context. Why does this happen and how to fix this? -
Two way replication of data between two postgresql 13.1schemas
All, I have a Django multitenant application with PostgreSQL (13.1) as a backend. I’m in a situation where I need to replicate the data between “table 1” and “table 2”. Right now, I’m using logical replication (publish-subscribe) for this one-directional replication. But, we need to replicate the data in two ways (ie. From A B and BA). I have some questions for the experts while learning more about this situation. This would help me in finding a solution Context We have a user with permission in both schemas Uses logical replication (Publish subscribe) Logical replication from table 1 to Table 2 is working fine But need to replicate data in both directions (ie. From A B and BA) Simultaneous data medication won’t happen in (in schema 1 or Schema 2) Questions Will this result in an infinite loop? Is there any way to avoid this looping? -
user = get_user_model().objects.create_user(email,password)
I am getting this error while executing .I have made a test models file to test my models using TDD.I could find the error i have also tried models.User.create_user but that also didnt work. Here is my test_models.py ''' class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test creating a new user with email""" email = 'hassansahi6464@gmail.com' password = 'admin' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """Test the email for user is normalized""" email = 'hassansahi6464@GMAIL.COM' user = get_user_model().objects.create_user(email,'admin') self.assertEqual(user.email,email.lower()) and here is my models from django.db import models from django.contrib.auth.models import UserManager , AbstractBaseUser , BaseUserManager , PermissionsMixin from django.db.models.base import Model # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): user = self.model(email=self.normalize_email(email) , **extra_fields) user.set_password(password) user.save(using = self._db) return user class User(AbstractBaseUser,PermissionsMixin,Model): email = models.EmailField(max_length=100,unique=True) name = models.CharField(max_length=150) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager USERNAME_FIELD = 'email' Settings.py AUTH_USER_MODEL = 'core.User' -
Django cannot find CSS when deployment
I have an issue with my deployment. When I run my project in my localhost it works perfect. But when I deploy iti cannot find css files. That's why looks bad and doesn't get any style. How can I fix it? settings.py ... STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join('static'),) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... Note: And I don't know if it is related but there is an error in console: Refused to apply style from 'https://...ing.com/static/css/signup.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. -
I am looking for some final year web project unique ideas ? please do let me know some new web project ideas?
Please let me know the best topics for building A web application. -
How to add weeks to a datetime column, depending on a django model/dictionary?
Context There is a dataframe of customer invoices and their due dates.(Identified by customer code) Week(s) need to be added depending on customer code Model is created to persist the list of customers and week(s) to be added What is done so far: Models.py class BpShift(models.Model): bp_name = models.CharField(max_length=50, default='') bp_code = models.CharField(max_length=15, primary_key=True, default='') weeks = models.IntegerField(default=0) helper.py from .models import BpShift # used in views later def week_shift(self, df): df['DueDateRange'] = df['DueDate'] + datetime.timedelta( weeks=BpShift.objects.get(pk=df['BpCode']).weeks) Error BpShift matching query does not exist. Commentary I used these methods in hope that I would be able to change the dataframe at once, instead of using df.iterrows(). I have recently been avoiding for loops like a plague and wondering if this is the "correct" mentality. Is there any recommended way of doing this? Thanks in advance for any guidance! -
Django Admin redirects to a looped URL
when I'm trying to open Django admin in my project, it redirects to a weird URL that looks some kind of loop happened. I've unregistered all models from the admin module but the problem is still the same. at this moment there's no models added to Django admin and its URL looks like this: path('admin', admin.site.urls) but when I'm trying to open the admin URL (localhost:8000/admin), it redirects me to this URL: http://localhost:8000/adminlogin/?next=/adminlogin%3Fnext%3D/adminlogin%253Fnext%253D/adminlogin%25253Fnext%25253D/adminlogin%2525253Fnext%2525253D/adminlogin%252525253Fnext%252525253D/adminlogin%25252525253Fnext%25252525253D/adminlogin%2525252525253Fnext%2525252525253D/adminlogin%252525252525253Fnext%252525252525253D/adminlogin%25252525252525253Fnext%25252525252525253D/adminlogin%2525252525252525253Fnext%2525252525252525253D/adminlogin%252525252525252525253Fnext%252525252525252525253D/adminlogin%25252525252525252525253Fnext%25252525252525252525253D/adminlogin%2525252525252525252525253Fnext%2525252525252525252525253D/adminlogin%252525252525252525252525253Fnext%252525252525252525252525253D/adminlogin%25252525252525252525252525253Fnext%25252525252525252525252525253D/adminlogin%2525252525252525252525252525253Fnext%2525252525252525252525252525253D/adminlogin%252525252525252525252525252525253Fnext%252525252525252525252525252525253D/adminlogin%25252525252525252525252525252525253Fnext%25252525252525252525252525252525253D/adminlogin%2525252525252525252525252525252525253Fnext%2525252525252525252525252525252525253D/admin I'm troubling with this issue for some days and couldn't find any solution! any ideas? -
how to add related product list in django on my ecommerce website
I have a ecommerce website an d it my project detail page I want to load related product list of that subcategories of which the current item detail is showing on product_detail.html but i don't figure out how to achieve that any idea how to achieve that right now i show all the item list in realated products section but i don't want that here is my codes my views.py class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.filter() return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('size') cart = request.session.get('cart') if cart: quantity = cart.get(item) if quantity: cart[item] = quantity+1 else: cart[item] = 1 else: cart = {} cart[item] = 1 request.session['cart'] = cart return redirect('products:detail', item_id=item_id) my html <div class="product"> <div class="col-11"> <h4 style="color: #025;">Related Products</h4> <div class="scrolling-wrapper"> {% for items in item %} <a href="{% url 'products:detail' item_id=items.id %}"><img class="card col-3" height="300px" width="100%" src="{{ items.first.url }}" alt=""></a> {% endfor %} </div> </div> </div> </div> my models.py class Subcategories(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_categories') name = models.CharField(max_length=200, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Item(models.Model): … -
Heroku login fails: Error: unable to get local issuer certificate when trying to deploy django app
I want to deploy my django app to heroku. I am using company PC, windows10. Company is not IT company, it is contruction company. So IT team is not helpfull in some development cases. When I want to login from heroku cli, I got this error: D:\coding\taksi>heroku login heroku: Press any key to open up the browser to login or q to exit: Error: unable to get local issuer certificate What have I tried already: Check/Set Variable SSL_CERT_DIR=YourCetrFolder (I don't have such file, company IT team has no idea about this) I did my deployment via browser, but some tasks are not possible with web interface. for example I want to create super user after deployment, I want to migrate my database after deployment. those tasks are impossible via heroku web.(as far as i know, of course if there is a way to do those via heroku web page, please let me know. as long as it does my job, it is not important whether it is heroku cli or heroku webpage for me) thanks in advance.