Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Paginating Django View with Foreign Key Data
I'm trying to build a simple Django gallery that allows photos to be added to an album. Everything thus far is working fine (upload photo, add to album, paginated all photos listing, photo details/display pages, etc), until I try to display the 'album' pages. I can get the page to render the the album and all of the associated photos, but if I try to paginate the album, things start to get weird. Here are my models: # models.py class Albums(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=500) slug = models.SlugField(max_length=500, unique=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) class Photos(models.Model): id = models.AutoField(primary_key=True, unique=True) album = models.ForeignKey( Albums, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Album" ) photo = models.ImageField(upload_to="photos/") slug = models.CharField(max_length=16, null=False, editable=False) # I know I'm not using a SlugField here; that's on purpose title = models.CharField(max_length=500) description = models.TextField(blank=True, null=True) upload_date = models.DateTimeField( default=timezone.now, verbose_name="Date uploaded" ) def __str__(self): return self.title def save(self, *args, **kwargs): [...] # stuff to get the image's EXIF data and use that to set the slug self.slug = str(datetime.strftime(img_date, "%Y%m%d%H%M%S")) [...] # plus a bunch of other stuff that happens … -
Django dynamic url parameters
I'm trying to make an example for a product page where people can put designs on their product's. I'm using django and try to make my "designer" page behave differently on the type of product selected. I want to have it behave like www.mysite.com/designer/foo where foo is the name of the product I have gotten to make it work like www.mysite.com/designer?product=foo but i like the simplicity of the first url more and i can't imagine that wouldn't be possible. urlpatterns = [ path('', overview, name='overview'), path('designer/', designer, name='designer'), path('administration/', administration, name='administration'), path('admin/', admin.site.urls), ] my url patterns are like this, i've tried fiddling around with some examples using regex behind the "/" after designer. but i can't get it to work, the server keeps trowing Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/designer/exampleA I'm afraid i don't know where to start looking and how to properly formulate my question as webdeveloping is quite new to me. -
create dynamic feedback form using Django
I am trying to create a dynamic feedback form using Django in which form creator can ask anything in any format(i.e. Boolean, text, etc). Is there any way to do this. Thanks :) -
Twilio - how to handle inbound sms
I just made an account on twilio and I was able to configure things so that I can send sms through a django app I wrote. However, now I am trying to understand what hapens to inbounds sms. Basically, if someone replies to the message that they receive through my Twilio, what happens to that text? -
Django return PDF from chromium with custom name
I am using chromium within django to export a PDF file. It is working well, but the exported file "myfile.pdf" is saved to my app's root directory. I am trying to determine the best way to serve the file with a custom name and date, while also not filling the web app with these left over files. Should I use a temporary directory? Here is my code so far: class PrintPDF(DetailView): template_name = "print.html" def get(self, request, *args, **kwargs): html_file = self._create_html_file(request) cmd = settings.PDF_EXPORT_COMMAND cmd_options = [ "--headless", "--print-to-pdf=myfile.pdf", "--disable-gpu", "--run-all-compositor-stages-before-draw", "--virtual-time-budget=10000", "--force-device-scale-factor=1", "--no-sandbox", "--disable-dev-shm-usage", html_file, ] subprocess.check_call(cmd + cmd_options, timeout=600) os.remove(html_file) return FileResponse(open("myfile.pdf", "rb"), content_type="application/pdf") def _create_html_file(self, request): self.object = self.get_object() context = self.get_context_data(object=self.object) html = render_to_string(self.template_name, context, request) tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".html") with open(tmp.name, "w") as f: f.write(html) return tmp.name -
Limit Django data to current user
Hoping you can help me. I am trying to run the below - for ONLY the current requesting user. But it pulls back the data for all users. Can you help me to figure out why that is? open_tasks = skills.objects.filter(creator=request.user).raw(''' SELECT *, round(((closed_points)/(open_points+closed_points)*100),2) as points_pct, round(((closed_count)/(open_count+closed_count)*100),2) as closed_pct from ( SELECT id, sum(open_points) as open_points, sum(closed_points) as closed_points, sum(open_count) as open_count, sum(closed_count) as closed_count from ( SELECT id, case when status = 'open' then sum(points) end as open_points, case when status <> 'open' then sum(points) end as closed_points, case when status = 'open' then sum(count) end as open_count, case when status <> 'open' then sum(count) end as closed_count from ( SELECT category as id, status, sum(cast(points as int)) as points, count(*) as count FROM voximisa_skills group by category, status)s group by id, status)p group by id)j ''') -
Django-how to set only one review per user and movie
movies_detail.html {% extends 'base.html' %} {% block content %} <img src="{{ articles.image.url }}" width="200px" height="300" style="display: inline-block;" > <div id="movie_plot"> <h2>{{articles.title}}</h2> <p>{{articles.plot}}</p> {{articles.category}} <p>{{articles.cast}}</p> </div> {% if isReviewAllowed == True %} <div class="isReviewAllowed"> <div class="nav_button"><a class="new_movie" href="{% url 'movies:review' slug=articles.slug %}">Create Review</a></div> </div> {% endif %} {% for review in all_reviews %} {% if review.Review == movie.title %} <div class="all_reviews"> <div class="review"> <p><span style="font-weight: normal;">Reviewed by: </span> {{review.user}} </p> <p><span style="font-weight: normal;">Description: </span>{{review.text}}</p> <form style="text-align: center;" action="{% url 'movies:like' slug=articles.slug %}" method="post"> {% csrf_token %} <button style="color: white; background: #104e89;" type="submit", name="review_id", value="{{ review.id }}", class="btn btn-primary btn-sm">Like</button> {{review.count_likes}} </form> </div> {% elif review.movie.title == movie.title %} <div class="review"> <p><span style="font-weight: normal;">Reviewed by: </span> {{review.user}} </p> <p><span style="font-weight: normal;">Description: </span>{{review.text}}</p> </div> </div> {% endif %} {% endfor %} {% endblock %} so the problem is when i create review with (for example:nir_user make review for batman movie) the review appears in all the movies and not in the specific movie tell me please if you want me to show you more code. -
Working with websockets on multiple tab to check realtime send and receive events
I am stuck in a strange situation. I don't know how to describe it. Well, I have set up WebSockets in my project, On the client side I'm using react, And on the server side, I'm using Django channels. On a single tab, all flow is working fine. e.g : I'm sending data from the client-side with sockets to the server and receiving it back on the client-side. but on the other tab, it doesn't receive at the same moment or we can say real-time receiving . I'm basically trying to build a notification system on WebSockets. -
How to fix 500 internal server error while using Django and React
I'm trying to create a simple shopping cart with django and react. When I click on the add-to-cart button I get 500 Internal Server Error from react. The error it's displaying in django is: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x00000268F76AEFA0>": "order_product.user" must be a "User" instance. I have tried every means I know but I'm still not able to fix it. Below is the programme: DJANGO urls.py path('add-to-cart/', add_to_cart_view.as_view(), name='add-to-cart'), views.py class add_to_cart_view(APIView): permission_classes = [] def post(self, request, *args, **kwargs): id = request.data.get('id', None) if id is None: return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST) product = get_object_or_404(Product, id=id) requested_product = order_product.objects.create( product=product, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if not order.products.filter(product__id=requested_product.id).exists(): order.products.add(requested_product) return Response(status=HTTP_200_OK) else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.products.add(order_product) return Response(status=HTTP_200_OK) REACT export const AddToCartURL = "http://127.0.0.1:8000"; const handleAddToCartURL = async (id) => { try { const res = await axios.post(`${AddToCartURL}/add-to-cart/`, {id}); setProduct(res.data); console.log(res.data) } catch (err) { } }; return( <Box sx={{ flexGrow: 1 }} m={4}> <Grid container spacing={3}> <Grid item xs={9}> <Item> <img src={product.image} alt="" /> <div> <p>{product.description}</p> <p>{product.label}</p> <p>{product.price}</p> </div> <button color='primary' onClick={() => handleAddToCartURL(product.id)}> <AddShoppingCartIcon /> </button> </Item> </Grid> <Grid item xs> <Item>Similar Products</Item> … -
Is there a way to auto-import all the models in my folder when loading __init__.py?
In my Python 3.9, Django 3.2 project, I have this general folder structure - manage.py + cbapp + models - __init__.py - vendor.py - user_preferences.py In my init.py file, I have all my model entries listed out ... from .vendor import Vendor from .user_preferences import UserPreferences ... Each model class, e.g. Vendor, has this general sturcture from django.db import models class Vendor(models.Model): ... Every time I add a new model I have to add a line into my init.py file. Is there any way I can write my init.py file so that it will just auto-import new files I add into my models directory? -
makemigrations ignoring all the fields (DJANGO)
as the title says there is a problem that I cannot resolve and that is that when I'm making migrations of my admin_db app it's just ignoring all the fields even though there are no commas etc and syntax is pretty much clean well I'm pasting my code.. any help would be really appreciated. P.S I'm using MYSQL as my database This is my admin model which I want to migrate from django.db import models from datetime import datetime # Create your models here. class Admin(models.Model): Admin_Email: models.EmailField(primary_key=True, editable=False) First_name: models.CharField(max_length=25) Last_name: models.CharField(max_length=25) Gender: models.CharField(max_length=1) Date_of_registration: models.DateField(default=datetime.now, editable=False) Date_of_Birth: models.DateField() CNIC: models.BigIntegerField(max_length=13, unique=True) City: models.CharField(max_length=50) Area: models.CharField(max_length=50) Address: models.CharField(max_length=100) Phone_num: models.BigIntegerField(max_length=11, unique=True) class Salt(models.Model): Admin_email = models.OneToOneField(Admin, on_delete=models.CASCADE) Salt = models.CharField(max_length=25, unique=True) class Password(models.Model): Admin_email = models.OneToOneField(Admin, on_delete=models.CASCADE) hash = models.CharField(max_length=255, unique=True) corresponding migrations 0001_initial.py # Generated by Django 3.2.8 on 2021-11-07 18:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Admin', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Salt', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Salt', models.CharField(max_length=25, unique=True)), ('Admin_email', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='admin_db.admin')), ], ), migrations.CreateModel( name='Password', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('hash', models.CharField(max_length=255, unique=True)), ('Admin_email', … -
drf action views with similar url_path not showing on drf swagger
I have two action views with same url_path ('favorite') but different methods to handle retrieving and deletion of an object. Only one of these action views is mapped and show on swagger API (using drf-yasg). from django.utils.decorators import method_decorator from drf_yasg.utils import no_body, swagger_auto_schema from rest_framework.decorators import action from rest_framework.mixins import ListModelMixin from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.status import (HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework.viewsets import GenericViewSet from housery.house.models import House from utils.drf_params import app_id from utils.mixins import FilterQueryByHouse from .serializers import HouseSerializer @method_decorator(name="list", decorator=swagger_auto_schema( manual_parameters=[app_id] )) class HouseViewSet(FilterQueryByHouse, ListModelMixin, GenericViewSet): queryset = House.objects.filter().prefetch_related( "opening_hours", "special_opening_hours__opening_hours", ) serializer_class = HouseSerializer def get_permissions(self): if self.action in ["list"]: return [AllowAny()] return [IsAuthenticated()] @action(methods=["get"], detail=True, url_path="favorite", url_name="favorite-read") def retrieve_favorite(self, request): """Retrieve favorite house""" if request.user.favorite_house_id: instance = request.user.favorite_house Response(self.get_serializer(instance=instance).data, status=HTTP_200_OK) return Response(status=HTTP_404_NOT_FOUND) @action(methods=["delete"], detail=False, url_path="favorite", url_name="favorite-remove") def unset_favorite(self, request): """Remove favorite house""" request.user.favorite_house = None request.user.save() return Response(status=HTTP_204_NO_CONTENT) @swagger_auto_schema(request_body=no_body) @action(methods=["post"], detail=True) def favorite(self, request, pk): """set given house id as favorite house""" instance = self.get_object() request.user.favorite_house = instance request.user.save() return Response(self.get_serializer(instance=instance).data, status=HTTP_201_CREATED) I would only get either "get" (retrieve_favorite) or "delete" (unset_favorite), but not both. I am sure I am doing some stupid that I could not … -
Write correct cycle for nested JSON data
I have some data: { "id": 56, "number": "82467", "date": "2021-08-19", "exams": [ { "type": "fff123", "stamp": "2021-08-19R17:00:17", "review": [ { "code": "1118", "value": "3", } ], }, { "type": "nnn123", "stamp": "2021-08-19R12:00:47", "review": [ { "code": "1120", "value": "1", }, { "code": "1121", "value": "2", }, ] } ] } Please tell me ,how I can get for "type": "nnn123", two value because now I get just one only first.I do something wrong in cycle, but I don't know what .How I can to get two values ? { "code": "1120", "value": "1", }, { "code": "1121", "value": "2", } , please maybe someone knows how I must correct write my code def get_object(self): number = self.kwargs['number'] type = self.kwargs['type'] obj = get_object_or_404(self.queryset.filter(number=number)) data = obj.exams filtered_exams = list(filter(lambda x: x["type"] == type, data)) for i in filtered_exams[0]['review']: return i -
Automatically Add Logged In User Under 'Created_By' to Model in Django Rest Framework
I have a model called Properties as shown below. I'm trying to save a given property in my DB with the current logged in user from a form in my dashboard. My user model is a custom user model AUTH_USER_MODEL = 'Landlords.Profile' At first i had no created_by and all was well. But then when i introduced it, made the necessary migrations, when i try to submit data from the form i now get this error. django.db.utils.IntegrityError: null value in column "created_by_id" of relation "Properties_rentalproperties" violates not-null constraint DETAIL: Failing row contains (1, Prime Apartments, Apartment, Kileleshwa, Nairobi, 10, 2021-11-07, 2021-11-07, null). How to assign my logged in user to a the property created In Django Rest framework? Most solutions on SO are geared towards class-based API views. How can i do this with function-based API views? Is there something i'm missing or doing wrong? My Model from django.db import models from django.conf import settings class RentalProperties(models.Model): property_name = models.CharField(max_length=255) property_type = models.CharField(choices=TYPE, max_length=255) property_location = models.CharField(max_length=255) county = models.CharField(choices=COUNTY, max_length=255) number_of_units = models.IntegerField() created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default='') date_created = models.DateField(auto_now_add=True) last_modified = models.DateField(auto_now=True) def __str__(self): return self.property_name class Meta: verbose_name_plural = "Properties" My serializer from apps.Properties.models import RentalProperties … -
Where can I write server code for stripe payment in Django project?
This post is hidden. You deleted this post 1 min ago. I am working on React JS to implement stripe payment gateway. I am using Django as a backend Server. In stripe documentation. https://stripe.com/docs/checkout/integration-builder?server=python there is following code given for implementation code for react App.js import React, { useState, useEffect } from "react"; import "./App.css"; const ProductDisplay = () => ( <section> <div className="product"> <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> <div className="description"> <h3>Stubborn Attachments</h3> <h5>$20.00</h5> </div> </div> <form action="/create-checkout-session" method="POST"> <button type="submit"> Checkout </button> </form> </section> ); const Message = ({ message }) => ( <section> <p>{message}</p> </section> ); export default function App() { const [message, setMessage] = useState(""); useEffect(() => { // Check to see if this is a redirect back from Checkout const query = new URLSearchParams(window.location.search); if (query.get("success")) { setMessage("Order placed! You will receive an email confirmation."); } if (query.get("canceled")) { setMessage( "Order canceled -- continue to shop around and checkout when you're ready." ); } }, []); return message ? ( <Message message={message} /> ) : ( <ProductDisplay /> ); } code for python server.py """ server.py Stripe Sample. Python 3.6 or newer required. """ import os from flask import Flask, redirect, request import … -
In Django 3.2, how do I intialize my ManyToMany field in my consturctor with values from an array?
I'm using Python 3.9 and Django 3.2. I have this model with a ManyToMany field ... class Account(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) active = models.BooleanField(default=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) vendor = models.ForeignKey(Vendor, on_delete=models.DO_NOTHING) crypto_currencies = models.ManyToManyField(CryptoCurrency) def __init__(self, user, vendor, crypto_currencies_arr, max_transactions=DEFAULT_MAX_BUY_TRANSACTIONS): self.crypto_currencies.set( set() ) for cc in crypto_currencies_arr: self.crypto_currencies.add(cc) super().__init__( user=user, vendor=vendor, crypto_currencies=self.crypto_currencies ) I'm having trouble figuring out how to initialize my many-to-many field with an array. The above results in this error >>> account = Account(user=u, vendor=v, crypto_currencies_arr=[c]) Traceback (most recent call last): File "<input>", line 1, in <module> account = Account(user=u, vendor=v, crypto_currencies_arr=[c]) File "/Users/davea/Documents/workspace/cbapp/cbapp/models/account.py", line 47, in __init__ self.crypto_currencies.set( set() ) File "/Users/davea/Documents/workspace/cbapp/venv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py ", line 536, in __get__ return self.related_manager_cls(instance) File "/Users/davea/Documents/workspace/cbapp/venv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py ", line 846, in __init__ self.core_filters[core_filter_key] = getattr(instance, rh_field.attname) File "/Users/davea/Documents/workspace/cbapp/venv/lib/python3.9/site-packages/django/db/models/query_utils.py", line 142, in __get__ val = self._check_parent_chain(instance) File "/Users/davea/Documents/workspace/cbapp/venv/lib/python3.9/site-packages/django/db/models/query_utils.py", line 158, in _check_parent_chain return getattr(instance, link_field.attname) AttributeError: 'NoneType' object has no attribute 'attname' How do I properly set my many-to-many field with the values from my array? -
Django Deployment on PythonAnywhere
I recently want to deploy one of my webapps to PythonAnywhere, but there is some problem I encounter. If I deploy the webapp in a virtualenv. I would not be able to install some critical packages within the virtualenv (especially Pandas). The console will show disk quota exceeded. Now I am trying to deploy the webapp in base environment(I left the Virtualenv part in PythonAnywhere Web tab blank), but the page shows error and after checking log, it says modulenotfound error. But I am sure the module is installed within that environment. BTW, both environment are run under Python 3.8 Page Error ModuleNotFoundError My problem is : Can anyone tell how to either reduce storage space required to install certain huge package like pandas or how do I clean out more space (or any other workable solutions) Can I deploy webapp under base environment? If yes, what is the root cause of the error shown above and solution to it. Here I provide some configuration of my webapp. Code part in Web tab: Source code:/home/myusername/my_project_folder Working directory:/home/myusername/ WSGI configuration file:/var/www/username_pythonanywhere_com_wsgi.py WSGI configuration file(/var/www/username_pythonanywhere_com_wsgi.py): import os import sys path = '/home/myusername/my_project_folder' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings' from … -
Check for password before accessing content in django
I am trying to build a functionality where users have to enter the passcode to access the site. If you go to this site it will ask for a password (123) before showing you the content: https://www.protectedtext.com/djangoproj I want to do it without forms.py. URL OF THE PAGE --> TEMPLATE --> ASK FOR PASSCODE --> SHOW CONTENT IF PASSCODE MATCHES models.py from django.db import models # Create your models here. class Text(models.Model): text = models.TextField(blank=True) slug = models.SlugField(unique=True) password = models.CharField(max_length=50) def __str__(self): return self.slug views.py from django.shortcuts import render from .models import Text import django.contrib.auth # Create your views here. def textview(request, slug): obj= Text.objects.get(slug=slug) return render(request, 'text/textpage.html', {'obj' : obj}) def home(request): return render(request, 'text/index.html', {}) I have tried creating a new template for password but I am still not getting that functionality. Thanks in advance -
How do i extend Django's auth user manager to add a method of my own?
I'm using Python 3.9 and Django 3.2. I want to use Django's auth module for basic user management and have added this in my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cbapp', ] However, I woudl like to change the primary key of its user table to be a UUID and then add my own method, so I created this file at models/custom_user.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomeUserManager(models.Manager): def get_active_users(self): qset = CustomUser.objects.filter( is_active=True ) return list(qset) class CustomUser(AbstractUser): pass uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) objects = CustomeUserManager() I would still like to have access to Django's original auth methods though, but it seems like I can't access them anymore, for example "create_user" ... >>> user = CustomUser.objects.create_user('Dave', 'myemail@test.com', 'johnpassword') Traceback (most recent call last): File "<input>", line 1, in <module> user = CustomUser.objects.create_user('Dave', 'myemail@test.com', 'johnpassword') AttributeError: 'CustomeUserManager' object has no attribute 'create_user' What's the proper way to extend Django's auth user methods while adding some of my own? -
Django rendering <a> tag with double underline
I am finishing my first project using Django (a blog). I first made the front-end using HTML and CSS and everything was smooth. I used an identical copy of the CSS file. When rendering the same HTML template using Django, it shows double underline animation under the tag. The code used: <div> <ul id="underline"> <li class="nav-items-lis"><a href="#" class="nav-items">Posts</a></li> <li class="nav-items-lis"><a href="#" class="nav-items">About</a></li> <li class="nav-items-lis"><a href="#" class="nav-items">Blog</a></li> <li class="nav-items-lis"><a href="#" class="nav-items">Contact</a></li> </ul> </div> The Django template: <div> ... </div> <div> <ul id="underline"> <li class="nav-items-lis"><a href="#" class="nav-items">Posts</a></li> <li class="nav-items-lis"><a href="#" class="nav-items">About</a></li> <li class="nav-items-lis"><a href="#" class="nav-items">Blog</a></li> <li class="nav-items-lis"><a href="#" class="nav-items">Contact</a></li> </ul> </div> <div class="container"> <div class="card-wrapper"> {% block body %} {% endblock %} </div> The code related to tags is the same in both (the HTML code and the Django template). Any hints on how to solve this issue? -
Django error when running migrate - id null
I am trying to make new migration for my django project after adding and removing some columns in table called payment. When running python manage.py makemigrations, everything working fine, and it results in new migration file 0002_auto_20211107_1714.py. Next, I try to run python manage.py migrate and it result in this error File "/home/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, payment, 0002_auto_20211107_1714, 2021-11-07 17:14:11.036703+00). Anyone ever faced this problem? -
What's the proper way to check in a Model's save() method if a FileField was committed in Django?
In Django, if you are overriding the save method of a model with a FileField, you can do something like this: class MyModel(models.Model): my_file = models.FileField() def save(self, *args, **kwargs): if self.my_file and not self.my_file._committed: # The file changed This lets you detect anytime a new file is uploaded. This can either happen if a new instance of MyModel is being created, or one is being modified, and a new file is replacing an old file (or no file). This is very convenient for cases where you need to read the file, and do something, but only if the file changed. This works, but the slight problem is that the my_file._committed attribute starts with an underscore, indicating that it's not meant to be used outside of the class it's defined in. Is there a proper way to detect if the file in the FileField changed during the current save() operation without using the private _.committed attribute? -
first_name is added to the tuple
Im using django-allauth. I added more fields in form (firstn_name and last_name) in form: myapp/forms.py class CustomSignupForm(forms.Form): first_name = forms.CharField(max_length=30, label="first_name", strip=True, widget=forms.TextInput(attrs={'placeholder': "name", })) last_name = forms.CharField(max_length=30, label='last_name', strip=True, widget=forms.TextInput(attrs={'placeholder': 'last_name',})) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'], user.last_name = self.cleaned_data['last_name'] user.save() return user after which I specified a link to this form in the settings. When registering, these two fields appeared, but: Now, when registering, my first_name is in the tuple. I output in the template: {{user.first_name}} Last name is displayed normally. What can be done so that the first name is not in a tuple, but just a string? -
Pagination codes is not working with annotate
I wanted to display a table by filtering records from the database. Therefore I filtered the records and assigned them to a 'qc3_table_data'. Also, I needed 'first_name' from the USER table. I used ANNOTATE and added 'qc2_engineer_query' to the 'qc3_table_data'. Everything works well till now. But when I use paginate code, it throws an error. Can anyone help me to fix this issue? views.py def designer_home_view(request): qc3_table_data = cn_data_tables.objects.filter( engineer=request.user).filter(qc3_submit_status=True ) qc3_table_data = qc3_table_data.annotate(qc2_engineer_query=Subquery(User.objects.filter( id=OuterRef( 'qc_engineer_2' ) )[:1].values( 'first_name' ) )) Codes for Pagination page = request.GET.get( 'page', 1 ) paginator = Paginator( qc3_table_data, 2 ) try: qc3_table_data = paginator.page( page ) except PageNotAnInteger: qc3_table_data = paginator.page( 1 ) except EmptyPage: qc3_table_data = paginator.page( paginator.num_pages ) get_dict_copy = request.GET.copy() params = get_dict_copy.pop( 'page', True ) and get_dict_copy.urlencode() return render( request, 'Home_page_designer.html', {'cn_table_data':qc3_table_data, 'qc2_table_data':qc2_table_data, 'my_task':my_task, 'filter':filter1, 'params':params, } ) I am getting following error System check identified no issues (0 silenced). November 07, 2021 - 22:02:29 Django version 2.2.7, using settings 'QC_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. C:\Users\ipcramk\Desktop\Desktop files\pYTHON TRAINING\Django\Quality_Check_UI\QC_project\app1\views.py:242: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'app1.models.cn_data_tables'> QuerySet. paginator = Paginator( qc3_table_data, 2 ) Internal Server Error: /cn_entry/designer_home Traceback (most recent … -
Referring to a relationship in queryset
I have two models (Event and Deligate) related by foreign keys. I have a link on the delegate’s detail page that queries if the event is paid or not. I can’t seem to get the right query set to use. class Event(models.Model): event_title = models.CharField(max_length=30) about_event = models.TextField() paid_event = models.BooleanField(default=False) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Deligate(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='participating_ event') deligate_name = models.CharField(max_length=10, blank=True, null=True) deligate_bio = models.TextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def event_check_view(request, pk): deli = Deligate.objects.get(pk=pk) & Deligate.objects.get(event = 'participating_ event') if deli. paid_event: do something… else do something else…