Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login_redirect_url not working. View always redirecting to index
This is my login redirect url in settings.py: LOGIN_REDIRECT_URL='/category/all' And this is my login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") Whenever the user logs in I want to redirect him to the category/all page but it is always redirecting to index("/") and this might be because I am using return redirect("/").Also even when I have login required for some view then too even when the url is like: http://localhost:8000/login/?next=/cart/ Instead of redirecting me to cart it redirects too index. Please help me to work around this so that the redirect works properly. -
Uploaded media files not displaying after deploying on Heroku
After deploying my Django web app on Heroku, whenever I upload any image to the site, the image displays for some time then after stops showing... my uploaded images only shows temporary. How can I resolve this issue, I have installed white noise and added it to middleware in settings.py still the issue persists. -
Django did not display the uploaded image from cloudinary
May I know how to display the img that uploaded to cloudinary from django templates? I have tried the {{ obj.img.url }} but returned error: attribute has no file associated with it. Did I missed somethings? model.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) wts_img = models.ImageField(upload_to='wts/', blank=True, null=True) html: {% load cloudinary %} {% for order in orders %} <img src="{{ order.wts_img.url }}" > {% endfor %} setting.py: CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'xxxxx', 'API_KEY': 'xxxxxxx', 'API_SECRET': 'xxxxxxxxxx' } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' -
Django. How to kind of "spread" object when passing as with parameter to include?
I have a component which i include like that: {% include "components/item_link.html" with target="_blank" href=link.href icon=link.icon text=link.text %} There are lots of repetitions of link.. Is there a way to "spread" object and include it like that? {% include "components/item_link.html" with target="_blank" ...link %} -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' Django
Why am i getting this error here? It very wierd, sometimes it works and sometimes it does not. Can someone explain if they understand. The error accures in my views.py file: fotlister = Produkt.objects.filter(under_kategori__navn__iexact="lister") kalkuler = ProduktKalkureing.objects.all() beregning = {} if request.method == "POST": omkrets = request.GET.get('omkrets') for i in kalkuler: kalk = math.ceil((int(omkrets)/i.lengde)*1000) add = ({'produkt_tittel': i.produkt.produkt_tittel, 'produkt_bilde': i.produkt.produkt_bilde, 'produkt_info': i.produkt.produkt_info, 'produkt_link': i.produkt.produkt_link, 'pris_heltall': i.produkt.pris_heltall, 'antall_kalk': kalk, 'total_kost': kalk * i.produkt.pris_heltall }) beregning.update(add) What im trying to do is get the value from a POST request and calculate based on that value. Also i would like to put all the values into a dictionary, also having trouble with that. All i would like to put all the information in the add dictionary and display that on my template. Thanks for any answers, im just trying to understand how python operates. -
Django. How to use filters in include with clause
I have link component which i include like that {% include "components/item_link.html" with href="{{ title | lower | slugify }}" %} It renders with href equal to {{ title | lower | slugify }} instead of properly filtered title value (string) -
How do I fix a reverse error in Django when redirecting?
I am currently working on a website where you can create a shopping list. I am trying to insert items into the shoplist. So things like banana, cake, etc would go into shoplist. I got everything to work. When I create the item, it goes inside the database but when I try to redirect back to the website where I pressed create item, it shows the error Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['shoplist/(?P<item_id>[0-9]+)/$'] Also, when I try to enter my details page, it shows the error Reverse for 'createitem' with arguments '('',)' not found. 1 pattern(s) tried: ['shoplist/(?P<item_id>[0-9]+)/createitem/$'] I think I did something wrong when making my paths or doing something wrong syntax wise. Nothing I found on the internet is fixing it. Is there a way to fix this problem? Thank you very much! views.py def createitem(request, item_id): if request.method == 'GET': return render(request, 'shoplist/createitem.html', {'form':ItemForm(), 'id':item_id}) else: form = ItemForm(request.POST) itemlist = form.save(commit=False) itemlist.shoplist = Shoplist.objects.filter(user=request.user, pk=item_id).first() itemlist.user = request.user itemlist.save() return redirect('detail', pk=item_id) urls.py from django.contrib import admin from django.urls import path from shoplist import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), #authentication path('signup/', views.usersignup, name='usersignup'), path('logout/', … -
login page doesnot show any field
I am using Django 2.2.15 my views.py code for login page is given below, from django.contrib.auth import authenticate, login, logout def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('store') context = {} return render(request, 'registration/login.html', context) and my main part of login.html code is given below, <h2>Login to your account</h2> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> </form> But when I start to refresh my login page it doesnot showing any field for login page like below screen shot, login page please help me to sort out this problem. -
DRF other fields in serializer on get and on post
I'm trying for a few hour how to get other fields representation in serializer when i'm doing get and other when i'm doing post. I want this all data which are in author field in json, but lower in html form i want only choose exist user from list. When i change author field to display only url then i can choose author from list. Is it possible to get author info like on first screen and have only possibility to choose author from user list without editing all user fields? -
Programatically adding an image to Wagtail from one's local machine
I'm trying to add images to a model on my Wagtail site with a manage.py command. I found this post that covers it, but it's using a requests.get() call to the image from the internet. I have my images saved locally and have tried to adapt the linked code unsuccessfully: from django.core.files.images import ImageFile from wagtail.images.models import Image path = f"{img_directory}/{filename}" img_bytes = open(path, "rb").read() img_file = ImageFile(BytesIO(img_bytes), name=filename) img_obj = Image(title=filename, file=img_file) print(img_obj.file) img_obj.save() The print(img_obj.file) statement does print the filename as defined, but when I try to call img_obj.save(), I get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: wagtailimages_image.width I'm guessing that I'm opening the file wrong and it's not reading it as an image as I want it to, but I can't figure out where exactly I'm going wrong. -
How can I prevent a full table scan in this PostgreSQL query?
This query is contstructed using the Django ORM. I have indexed on all ID columns, so I was surprised when EXPLAIN showed a prohibitively long full table scan on orders_query. The long-running piece is in the very top of the EXPLAIN log, but here's the relevant portion (the very top lines): GroupAggregate (cost=999695.25..19231670646.03 rows=1897315 width=105) Group Key: users_profile.id, users_user.last_login -> Sort (cost=999695.25..1007470.17 rows=3109968 width=73) Sort Key: users_profile.id, users_user.last_login -> Hash Right Join (cost=738.71..387928.02 rows=3109968 width=73) Hash Cond: (orders_query.user_id = users_user.id) -> Seq Scan on orders_query (cost=0.00..345054.24 rows=2943324 width=8) -> Hash (cost=702.78..702.78 rows=2874 width=73) -> Hash Right Join (cost=301.35..702.78 rows=2874 width=73) Question: Is there another index I can make to avoid this Seq Scan that slows down the SQL query? SELECT "users_profile"."id", "users_profile"."created", "users_profile"."modified", "users_profile"."guid", "users_profile"."user_id", "users_profile"."charter_role_id", "users_profile"."owner_id", "users_profile"."volume_limit", "users_profile"."vol_limit_ovrd", "users_profile"."charter_vol_limit_contrib_ovrd", "users_profile"."sponsored_ovrd", "users_profile"."view_peers_ovrd", "users_profile"."inherit_permits", Count(DISTINCT "orders_order"."id") AS "orders", (SELECT Count(DISTINCT U0."guid") AS "io" FROM "orders_order" U0 INNER JOIN "users_user" U1 ON ( U0."user_id" = U1."id" ) INNER JOIN "users_profile" U2 ON ( U1."id" = U2."user_id" ) WHERE U2."owner_id" = "users_profile"."id" GROUP BY U2."owner_id") AS "indirect_orders", Count(DISTINCT "orders_query"."id") AS "searches", (SELECT Count(DISTINCT U0."guid") AS "isch" FROM "orders_query" U0 INNER JOIN "users_user" U1 ON ( U0."user_id" = U1."id" ) INNER JOIN "users_profile" U2 … -
Exception Value: Value too long for type character varying(2)
So I am using React and Django. I currently have a problem with submitting forms because I am gettin the strange error Exception Value: Value too long for type character varying(2) Models.py for the Model in question: @python_2_unicode_compatible class Member(models.Model): class Meta: ordering = ('last_name', 'first_name') first_name = models.CharField(max_length=50, db_index=True) last_name = models.CharField(max_length=50, db_index=True) dob = models.DateField(verbose_name='Date of Birth', null=True, blank=True, help_text='format: 1999-12-31') card_number = models.CharField(max_length=10, help_text="The ID number on the membership card", unique=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) latest_membership = models.ForeignKey('Membership', null=True, blank=True, related_name='latest_member') email = models.EmailField(blank=True) phone = PhoneNumberField(blank=True) street_1 = models.CharField(max_length=200, blank=True) street_2 = models.CharField(max_length=200, blank=True) city = models.CharField(max_length=100, blank=True) state = USStateField(choices=us_states, blank=True) zip_code = models.CharField(max_length=16, blank=True) I see there is some fields with max_length but I know I am not violating the constraint. API for React form: def redesign_member_form(request): if request.method == 'POST': errors = {} try: data = json.loads(request.body) data["dob"] = parse(data["dob"]) print("dob parsed") Member.objects.create(**data) except Exception as e: errors["error"] = e.message return JsonResponse(errors, status=400) return HttpResponse(status=200) else: return HttpResponse(status=400) The react form: import React from 'react'; import Form from '../../components/form/Form'; import { FormContext } from '../../components/form/Form'; import FormDropdown from '../../components/form/FormDropdown'; import FormDatePicker from '../../components/form/FormDatePicker'; import FormInput from '../../components/form/FormInput'; import FormButton from '../../components/form/FormButton'; … -
how edit names of field in django filters, and add styling
I am following a tutorial to make a django app, I was making a filter table however there are some issues in it. I have already tried things suggested in other answers, and they did not work for me. In the image attached as you can see I have underlined the names of the fields that I want to change and don't know how to do it, django just named those fileds by itslef and I want to change it, also please tell how can I use bootstrap to make it look good. Thank you.. filters.py file - import django_filters from django_filters import DateFilter, CharFilter from . models import * class OrderFilter(django_filters.FilterSet): start_date = DateFilter(field_name="date_created", lookup_expr="gte") # lookup_expression, gte-> # greater than or equal to end_date = DateFilter(field_name="date_created", lookup_expr="gte") # lookup_expression, lte-> less # than or equal to note = CharFilter(field_name="note", lookup_expr="icontains") class Meta: model = Order fields = '__all__' # we are excluding these because we want to customize them exclude = ['customer', 'date_created'] model - Order - in models.py - class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for Delivery', 'Out for Delivery'), ('Delivered', 'Delivered') ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = … -
What order do JavaScripts need to be written in Python?
After much trial and error I discovered that to get my date widget to work I needed to do this - <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script> If I put my scripts the other way round, the date widget would not work. It never dawned on me that the order the scripts were in would have an impact on whether the code worked or not. Would an experienced Python programmer be able to tell, just by looking at the two scripts, what order they need to be in? To prevent future problems, is there anything I can check, to work out what orders script need to be written in? -
Django ORM: distinct and annotate
Let's say I have a table like this: class Developer(models.Model): first_name = models.CharField(max_length=255) last_name= models.CharField(max_length=255) team = models.CharField(max_length=255) closed_tickets = models.IntegerField() objects = DeveloperManager() I want to write a query which returns: Write SQL to show percentage of team tickets closed by every developer and rank developers by contribution level. something like this: is there a way to it in a one query? I am trying to think in the direction of annotation with distinct clause class DeveloperManager(models.Manager): def rank(self): return self.order_by('team').annotate( total=models.Sum( 'closed_tickets' ), piece=models.F('closed_tickets') / models.F('total'), ).distinct('team').values() but it returns me an error: NotImplementedError: annotate() + distinct(fields) is not implemented. -
azure invalid username when migrating django database
I followed [Tutorial: Deploy a Django web app with PostgreSQL in Azure App Service][1] I created the DB and the app till I get to : Run Django database migrations Open an SSH session in the browser by navigating to https://.scm.azurewebsites.net/webssh/host run the "python manage.py migrate" it gives me this error FATAL: Invalid Username specified. Please check the Username and retry connection. The Username should be in <username@hostname> format. (antenv) root@5f4958961a00:/home/site/wwwroot# thnx in advance [1]: https://%3Capp-name%3E.scm.azurewebsites.net/webssh/host -
DRF serilaizers nested create/update with 2 FK
My models class Checklist(models.Model): checklist_name = models.CharField(max_length=255) is_done = models.BooleanField(default=False) class Category(models.Model): checklist_name = models.ForeignKey(Checklist, on_delete=models.CASCADE, related_name="checklist_name") category_name = models.CharField(max_length=255) is_done = models.BooleanField(default=False) class Task(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') task_name = models.CharField(max_length=255) How can I create/update nested serializers with 2 Foreignkey starting from Checklist ? -
django filter queryset based on list of dates and get the count on each day
I have a model like this class MyModel(models.Model): date = models.DatetimeField(auto_now_add=True) and i have a list of dates (dates of last seven days, it can be dates of last 30 days as well). What i am trying to do is get the number of MyModel objects created in a particular day in all of the dates. Like below. [{'date1': 2}, {'date2': 3}, {'date3': 7}....{'daten':26}] the keys of the dictoary are dates and values are the number of objects created in that particular date. by using a forloop and hitting db multiple times i am getting the output, but is there a way to get it from a single query ? -
i want to import all classes from a model.py which is not in my app modules in Django
in Django, my model.py is out of my App modules I want to import all the classes from that model.py to all modules. I searched a lot I didn't get anything can anyone help me -
How to deserialize nested django object
I'm not really sure how I'm able to access the data of a nested serializer, with a one-to-many relation. Here's my models: class Album(models.Model): id = models.CharField(max_length=255, null=True, blank=True) name = models.CharField(max_length=255, null=True, blank=True) class Title(models.Model): name = models.CharField(max_length=255, null=True, blank=True) album = models.ForeignKey( Album, related_name='titles' ) then I have 2 serializers: class AlbumSerializer(serializers.ModelSerializer): titles = TitleSerializer(many=True) class Meta: model = Album fields = ['id', 'name', 'titles'] def create(self, validated_data): album = Album.objects.create( id=validated_data.get('id'), name=validated_data.get('name') ) titles = validated_data.pop('titles') for title in titles: title['album'] = album _title = Title(**title) _title.save() return album class TitleSerializer(serializers.ModelSerializer): class Meta: model = Title fields = ['name'] To deserialize and save I run the following: album = AlbumSerializer(data=input_json) album.is_valid() album.save() my problem is now, that I'm unable to access the items. Accessing the type of album.instance.titles gets me <class 'django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager'>. How can I get the titles out of it, or what am I doing wrong that I do not get a list of Titles in there? -
Django manage.py migrate command cannot access Linux environment variables
Python cannot access environment variables while running any command. For example, after running python3 manage.py migrate an error occurs: django.db.utils.OperationalError: (2006, "Access denied for user 'dbmasteruser'@'0.0.0.0' (using password: YES)") But if I insert a plain string value for database password instead of os.environ.get('PASSWORD'), command works fine. All environment variables are written in setenv.sh file, but I have also tried to set them alternatively using command export PASSWORD=password. Executing command using sudo doesn't work either. However, Apache deployment server can read those environment variables without any issues, but the problem occurs while running migrations or any other command. How can I solve it? -
Static files doesn't load anymore - Django
In the beginning everything worked perfectly fine, but now I have a problem where my static files doesn't load. I think this is a very weird problem since I didn't really touch anything that could've had an influence on the problem when it happened. Everything else is working fine, I just can't get the static files for some reason. I sometimes get a 200 http response trying to get the static files like so: [20/Aug/2020 16:12:51] "GET /order/checkout/ HTTP/1.1" 200 2029 [20/Aug/2020 16:12:51] "GET /static/my_pizza_place/js/client.js HTTP/1.1" 200 2194 [20/Aug/2020 16:12:51] "GET /static/css/master.css HTTP/1.1" 200 80 [20/Aug/2020 16:12:51] "GET /static/css/global.css HTTP/1.1" 200 530 But it's still not applying the styling to my html code. I usually just get a 304 http response on my client.js file though. I feel like I have tried almost everything at this point, so I hope you guys can help me figuring out what the problem is. My files: SETTINGS.PY BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] BASE.HTML <!DOCTYPE html> {% load static %} <html lang="en"> <head> ... <link rel="stylesheet" href="{% static 'css/master.css' %}"> <link rel="stylesheet" href="{% static 'css/global.css' %}"> <script src="{% static 'my_pizza_place/js/client.js' %}" defer></script> </head> <body> <div class="container mycontent"> {% block … -
Require second login for users on Django based site
I have a Django 2.2 based project that uses a custom user model, the built-in Auth app and Django-All-Auth for user management. Almost every page on the site is behind a login and we use varying levels of permissions to determine what can be accessed a user. So far, so good, but now I'm being asked to designate everything behind a specific part of the site as "sensitive", requiring a second login prompt. What this means is that the client wants to see a login appear when they try to access anything under /top-secret/ the first time in a set time, say 30 mins, regardless of whether they're already logged in or not. I've dug around on the internet for ideas on how to do this, but so far I've been unable to find a good solution. Has anyone here had any experience with something similar, and if so, could they point me in the right direction? -
Python intermittent OpenSSL error: FileNotFoundError: [Errno 2] No such file or directory
I'm getting an intermittent error on my production Django website (running under UWSGI) when trying to use the kubernetes client library. The error seems to be urllib3, or perhaps OpenSSL. The strange thing is, I can simply restart my server and the problem goes away, but only temporarily. After a while I start seeing this error again: Traceback (most recent call last): File "/srv/hive/lib/python3.6/site-packages/urllib3/util/ssl_.py", line 353, in ssl_wrap_socket context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) FileNotFoundError: [Errno 2] No such file or directory This is extremely difficult to troubleshoot, because restarting the server makes the problem go away for a few hours. I added some extra logging to the load_verify_locations function in urllib3/util/ssl_.py to see what file it's trying to open. The ca_certs argument is passing in a temp file, /tmp/tmp2xng8a6e. The other two arguments are None. So, why a temp file, and why is it missing? Is there a reason why the temp file would get deleted, or why urllib3 might not be creating the temp file in the first place? Here's the full exception with traceback: Aug 20 10:36:05 ERROR django.request: Internal Server Error: /code/projects/test-project/ Traceback (most recent call last): File "/srv/hive/lib/python3.6/site-packages/urllib3/util/ssl_.py", line 353, in ssl_wrap_socket context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) FileNotFoundError: [Errno 2] … -
How to connect oracle 11g with django project?
I am new to Django and Oracle sql.I need to connect my Django project with my Oracle database.I am using Oracle 11g and Django 3.0 Can you please explain the whole procedure to connect them form a to z?