Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Capturing the data entered by a user, and displaying it on the same page
As my course project, I am making a supermarket management system. I am using Django with MySQL. I have already connected these two, and I am able to send data to the database and retrieve the same from it just fine. I have a relation in MySQL for PRODUCTS (product_id, product_name, brand_name, price). After the cashier enters the name of the product and the quantity that the customer wishes to purchase, I want the information related to that product along with the quantity to be displayed on the same page. Since a customer can purchase many different products, I want the information to be displayed as and when the cashier enters the names of those products. Then, I want to retrieve the information of all those products that were added by the cashier, and store it in the database in a relation called ORDERED_ITEMS (order_id, product_id, quantity) [order id is a foreign key]. I have no clue as to how to go about doing these things. Any help would be greatly appreciated. transaction.html: <form action="/transaction" method="post"> {% csrf_token %} <label for="order_id">ORDER ID</label> <input type="number" id="order_id" name="order_id" value="{{ next_order_id }}" disabled> <h3>ADD PRODUCTS :</h3> <label for="product_id"> Product ID</label> <select name="product_id" id="product_id"> … -
Could not resolve URL for hyperlinked relationship using view name "conversation-detail"
I'm building an rest api in django rest but I'm getting this and I don't know how to solve it. "ImproperlyConfigured at /conversation/1/ Could not resolve URL for hyperlinked relationship using view name "conversation-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. " models.py class Conversation(models.Model): storeId = models.ForeignKey(Store, on_delete=models.SET_NULL, null=True) operatorId = models.ForeignKey(Operator, on_delete=models.SET_NULL, null=True, related_name='operatorId') clientId = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True) operatorGroup = models.ForeignKey(Operator, to_field='group', on_delete=models.SET_NULL, null=True, related_name='operatorGroup') views.py class ConversationApiView(APIView): def get(self, request, id, *args, **kwargs): conversations = Conversation.objects.filter(id=id) serializer = ConversationSerializer(conversations, context={'request': request}, many=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class ConversationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Conversation fields = ('__all__') ursl.py urlpatterns = [ path('conversation/<int:id>/', ConversationApiView.as_view()), path('chat/<int:id>/', ChatApiView.as_view()), ] root urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('', include('api.urls')), ] THANK YOU in advance! -
How can i set default Username as what in email field in Django?
I want to set a default username when the user is created. I am using Django For example: in Freelancer.com when users signup, their username will be by default @their_email if I register with email -> john123@gmail.com My username will be -> @john123 How can I do it in the Models? My current Models is: from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class User(AbstractUser): """Default user for Mofidon.""" #: First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) class CustomAccountManager(BaseUserManager): def create_user(self, email, name, username, password, **other_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model( email=email, name=name, username=username, **other_fields ) user.set_password(password) user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): name = models.CharField(_("Name of User"), max_length=100) # username = models.CharField(_("Username of User"),max_length=20,unique=True, blank=True, null=True) username = None email = … -
Output PDF from HTML with Django in 2021
What is the best package to create professional report and invoices using Django today? I`ve tried severals of them but I am encountering some issues. Best Regards, -
django-allauth login_redirect page with username as slug
I am using Django 3.2 and django-allauth 0.44 I have set my LOGIN_REDIRECT_URL in settings.py as follows: LOGIN_REDIRECT_URL = 'profile-page' in urls.py, I have the following route defined: path('accounts/profile/slug:username', AccountProfileView.as_view(), name='profile-page'), When I log in, (unsurprisingly), I get the following error message: NoReverseMatch at /accounts/login/ Reverse for 'profile-page' with no arguments not found. 1 pattern(s) tried: ['accounts/profile/(?P[-a-zA-Z0-9_]+)$'] How do I pass (or specify) a parameter of the logged in user's username to the route? -
send emails for newsletter when a row is added in database table through Django Admin
I need to know How to send Emails for Newsletter automatically when a row is Added to a table Through Django Admin Portal -
coverage API in a gunicorn wsgi django server
I am using the coverage 5.5 API to run code coverage on my server. This server is written using Django. I have implemented the solution as per this answer -- https://stackoverflow.com/a/20689873/2996407 When I start up my server on my localhost using manage.py runserver and then shut it after some time, the code coverage report is generated as expected and correctly indicates the code coverage as well. However, on my firm's staging env, the server is run as a docker container wherein 8 gunicorn workers are spawned. 8 individual coverage files are being generated as per the solution above which is expected as well. However, the report doesn't have any coverage. The only coverage that is being done is of empty __init__.py files. The above SO answer suggests using a single gunicorn worker, but I don't have the option to do that. However, it suggests creating coverage files per worker which is happening as expected. But no luck in getting the coverage report from those. -
Django & Tagulous - Displaying Posts from two filters within my queryset
I am wanting to display Posts based on two filters (Date Posted - Which I have already got working) but I wanted to also display posts based on which Tagulous tags are stored as apart of the currently logged in user's meta data. For example, if User A has the tag "Summer" stored as apart of their metadata, the logged in user would only see posts relating to the "Summer" tag and wouldn't see any Posts which have been created under any other tags such as "Autumn, Winter, or Spring." I've made a basic start with implementing in the Tagulous filters, but not too sure which direction to go in from here. class PostListView(LoginRequiredMixin, ListView): model = Post template_name = 'core/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = PAGINATION_COUNT def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) all_users = [] data_counter = Post.objects.values('author')\ .annotate(author_count=Count('author'))\ .order_by('-author_count')[:6] # Tagulous objects getseason = Season.objects.filter(season='winter') user_tag = Season.tag_model.objects.filter(season__owner=request.user) for aux in data_counter: all_users.append(User.objects.filter(pk=aux['author']).first()) data['preference'] = Preference.objects.all() data['all_users'] = all_users print(all_users, file=sys.stderr) return data def get_queryset(self): user = self.request.user qs = Follow.objects.filter(user=user) follows = [user] for obj in qs: follows.append(obj.follow_user) return Post.objects.filter(author__in=follows).order_by('-date_posted') Any assistance or guidance would be most appreciated! :-) -
Django File not uploading inlineformset createview
My UpdateView working but I am not understating why file is not uploading in my CreateView? here is my code: froms.py class BlogForm(ModelForm): class Meta: model = Blog fields = ['title','body'] ImageFormSet = inlineformset_factory(Blog,BlogHeaderImage,fields=('image',),extra=1) views.py class BlogCreate(CreateView): #file is not uploading in create view? model = Blog template_name = 'blog_post.html' form_class = BlogForm def get_context_data(self, **kwargs): kwargs['latest_posts_list'] = Blog.objects.order_by('-id') return super(BlogCreate, self).get_context_data(**kwargs) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["children"] = ImageFormSet(self.request.POST, self.request.FILES) else: data["children"] =ImageFormSet() return data def form_valid(self, form): form.instance.author = self.request.user context = self.get_context_data() children = context["children"] self.object = form.save() if children.is_valid(): children.instance = self.object children.save() return super().form_valid(form) def get_success_url(self): return reverse("blog") class BlogUpdate(UpdateView): # Updateview is working and image file is uploading model = Blog template_name = 'blog_update_post.html' #fields = ['author','title','body'] form_class = BlogForm def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["children"] = ImageFormSet(self.request.POST, self.request.FILES, instance=self.object) else: data["children"] =ImageFormSet(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() children = context["children"] self.object = form.save() if children.is_valid(): children.instance = self.object children.save() return super().form_valid(form) def get_success_url(self): return reverse("blog") I am also not getting any errors. After click on update button I successfully redirected in Blog page without uploading file. -
Django Doc Error in Forms in views: AttributeError: module 'mdntuto.views' has no attribute 'hello'
I had read entire forms on Django documents for 3.2.2 and now I am working on the practical provided in documentation for forms and faced AttributeError: The code copied as it is from Django Docs. Still leaves an error. I have checked 4 times didn't find error Error is: path('hello/', views.hello, name='hello'), AttributeError: module 'mdntuto.views' has no attribute 'hello' Code is as follows forms.py from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) user_name = forms.CharField(label='Last name', max_length=20, required=True) mobile_number = forms.IntegerField(label='Contact No.') email = forms.EmailField(label='Email Address', initial='foo@foo.com', required=True) date_of_birth = forms.DateField(label='Enter DOB', initial='YYYY-MM-DD format') views.py from django.http import HttpResponseRedirect from .forms import NameForm from django.http import HttpResponse from django.shortcuts import render def get_hello(request): # if use def hello(request): it works fine # def get_hello(request) is as per Django Docs. if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = NameForm() return render (request, 'mdntuto/hello.html', {'form': form}) hello.html <form action="/your-name/" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> -
Django sum of time differences from model fields
I'm trying to get the sum of time differences from model fields in Django. I've tried this but I get an empty result with no error: model.py class Project(models.Model): design_start = models.DateField(editable= True, default=datetime.today, blank=True) design_end = models.DateField(editable= True, default=datetime.today, blank=True) class Portfolio(models.Model): projects = models.ManyToManyField(Project) I'm trying to get the total design time of all the projects by subtracting design_start from design_end and then getting the sum of everything views.py class DashView(generic.ListView): context_object_name = 'project_list' template_name = 'index.html' queryset = Project.objects.all() def get_context_data(self, **kwargs): context = super(DashView, self).get_context_data(**kwargs) context['design_time'] = Portfolio.objects.all().annotate( design_time = ExpressionWrapper(Sum(F('projects__design_end') - F('projects__design_start')), output_field=DurationField()), ) return context urls.py urlpatterns = [ path('', views.DashView.as_view(), name='home'), ] index.html <h4>{{ design_time.design_time }}</h4> -
Specify two arguments in URL parameters for path Djano
I've currently got an endpoint that accepts GET requests, to retrieve users within a date range (there's no real need to explain the 'why'). The specific endpoint looks like this: GET /users/?fromdate={yyyy-mm-dd}&todate={yyyy-mm-dd} For example, I can have a request such as: GET /users/?fromdate=2017-01-01&todate=2017-04-01 Without going too much into detail on the urls.py and views.py, I've specified the router register and path to accept requests to this endpoint (which works fine): urls.py: router = routers.DefaultRouter() router.register(r"user", views.UserViewSet, basename='user') urlpatterns = [ path('user/', views.UserViewSet.as_view({'get': 'user'}), name='user') ] I am now trying to run a unit test just to send a request to this endpoint Part of my test_user.py class looks like this: def test_user_list(self): response = self.client.get(reverse('user', kwargs={'fromdate': '2017-01-01', 'todate': '2017-04-01'})), format='json') self.assertEqual(response.status_code, 200) However, when I run the unit test, I get an error: Reverse for 'user' with keyword arguments '{'fromdate': '2017-01-01', 'todate': '2017-04-01'}' not found. 1 pattern(s) tried: ['/user/$'] I think the error is due to the fact that my path (while it works manually through a REST client like Postman) doesn't specify the arguments to expect path('user/', views.UserViewSet.as_view({'get': 'user'}), name='user') So how do I specify the arguments to satisfy a 'fromdate' and 'todate' as above? I have had a … -
How do I resolve fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping in Graphene?
I'm trying to create a person schema in django with graphene using attrs structure and destructure so that my data is inputted into the DB using JSONB. So far this is what I've created: models.py: from django.db import models # Create your models here. class PersonModel(models.Model): data = models.JSONField(null=True) schema.py: # from typing_extensions import Required import graphene import cattr from graphene_django.types import DjangoObjectType from graphene import Mutation, InputObjectType,ObjectType, String, Boolean, Field, Int, List, NonNull, ID, Argument from .models import PersonModel from .person import PersonDataClass class PersonSchema(DjangoObjectType): id = Int, name = String, age = Int, address_one = String, address_two = String class Meta: model = PersonModel class PersonSchemaOutput(PersonSchema, DjangoObjectType): # notice we only need ID in output and not in input of Mutation of Create id = graphene.ID class Meta: model = PersonModel pass class PersonSchemaInputCreate(PersonSchema, InputObjectType): id = graphene.ID class Meta: model = PersonModel pass class PersonSchemaInputUpdate(InputObjectType): # lets say we only allow update of following class Arguments: id = graphene.ID name = String, age = Int, class Meta: model = PersonModel pass class CreatePerson(graphene.Mutation): ok = Boolean() class Arguments: first_name = graphene.String() age = graphene.Int() address_one = graphene.String() address_two = graphene.String() person_data = Argument(PersonSchemaInputCreate()) # output will be … -
save() takes 1 positional argument but 2 were given djnago allauth resetpassword form
I need to add recaptcha field to allauth reset password form , i override the form according to allauth documantion this is resetpassword form in forms.py : class MyCustomResetPasswordForm(ResetPasswordForm): captcha = ReCaptchaField() def save(self): # Ensure you call the parent class's save. # .save() returns a string containing the email address supplied email_address = super(MyCustomResetPasswordForm, self).save(self) # Add your own processing here. # Ensure you return the original result return email_address and in settings.py : ACCOUNT_FORMS = {'reset_password':'user.forms.MyCustomResetPasswordForm'} but i get this error : TypeError at /accounts/password/reset/ save() takes 1 positional argument but 2 were given Traceback Switch to copy-and-paste view /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/generic/base.py, line 70, in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/generic/base.py, line 98, in dispatch return handler(request, *args, **kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/allauth/account/views.py, line 102, in post response = self.form_valid(form) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/allauth/account/views.py, line 690, in form_valid form.save(self.request) … -
ERROR when called from view: You can't execute queries until the end of the 'atomic' block
I'm trying to test a view that imports csv file and creates Product objects. The problem is that it returns this error: line 447, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. The error is caused by this row: Supplier.objects.get_or_create(name__iexact=supplier__name, defaults={'name': supplier__name})[ This is the method: @classmethod def import_csv(cls, filepath: str, created_by: User, delete_file=True) -> int: """imports products SKU already exists ? skip product : add product """ from products.models import Product from products.models import Supplier products_count = 0 EXCLUDED_ATTRS = ['id', 'supplier'] with open(filepath) as f: reader = csv.DictReader(f) for row in reader: if not all([row.get(field, None) is not None for field in ['sku', 'supplier__name']]): continue product = Product() product.created_by = created_by for attr, val in row.items(): if hasattr(product, attr) and attr not in EXCLUDED_ATTRS: if attr == 'title': setattr(product, attr, val[:99]) else: setattr(product, attr, val) supplier__name = row['supplier__name'] if supplier__name: supplier = \ Supplier.objects.get_or_create(name__iexact=supplier__name, defaults={'name': supplier__name})[ 0] product.supplier = supplier try: product.save() except IntegrityError: pass # todo what? else: products_count += 1 if delete_file: os.remove(filepath) return products_count And this is a view action: @action(methods=['post'], detail=False) def import_csv(self, request, pk=None) -> Response: csv_file = … -
Using google geocoding with django
I'm trying to create a web application in django where a user can enter his postal code and then have nearby restaurants displayed. However, i can't figure out a way to get django to collect the json response from the google api call and use on my site. Ive tried looking around online for help but i can't seem to make any of them work. Can anyone see how to improve my views.py or if i need to add something into my urls.py or if there's another method. (I do not intend to store the postal code in my db btw) EXAMPLE OF GEOCODING JSON RESPONSE { "results" : [ { "address_components" : [ { "long_name" : "1600", "short_name" : "1600", "types" : [ "street_number" ] }, { "long_name" : "Amphitheatre Parkway", "short_name" : "Amphitheatre Pkwy", "types" : [ "route" ] }, { "long_name" : "Mountain View", "short_name" : "Mountain View", "types" : [ "locality", "political" ] }, { "long_name" : "Santa Clara County", "short_name" : "Santa Clara County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "California", "short_name" : "CA", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : … -
I am using Python 3.9.4 and Django 3.2 and I made a function and a form that to check if the username or email already exists
I am getting an error tuple indices must be integers or slices, not User also tuple indices must be integers or slices, not NoneType I am checking whether any of these username or email exists or not, also the exists() not working only first() not working note I am using python 3.9.4 if User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists(): error_message = '' email_error = ('', 'Email is taken. ')[User.objects.filter(email=email).exists()] username_error = ('', 'Username is taken. ')[User.objects.filter(username=username).exists()] error_message = email_error + username_error messages.success(request, error_message) return redirect('/register/') -
Django function for views takes too long
I'm currently using a Docker & Django setup. I have to fill a database with data from API requests. I was hoping to do this everytime you went on a certain page (pretty easy: just have your views.py call the function that fills the database and voila). But the problem is, the function takes a long time, several minutes from within django (and about half the time with Spyder). So I usually just get a TimeOut and the page never loads (I admit I have a lot of API requests being made). I've read some stuff on using Celery but am not quite sure how it's supposed to work. Anyone know how I could get around this to be able to load the database? -
Can anybody change below code to djagno orm?
Can anybody change below code to djagno orm? SELECT max(comic_chapter),comic_english_name_id FROM mangazones.mangabank_comic_banks group by comic_english_name_id; -
Google Oauth2 with Django in PCF
I have implemented google OAuth2 in Django-3.2.1 I used default methods for connecting with google OAuth2(haven't written any custom functions - {% url 'social:begin' 'google-oauth2' %}) Now the issue is it works in my local with http, But when I deploy it to a PCF server its been configured with https and the Oauth2 authentications throws an issue like this. Can someone please help on this, I don't know why this issue happens when deployed in PCF server(configured with https) -
SQL error when using format() function with pyodbc in Djano
I want to execute a command using pyodbc in my Django app. When I do simple update with one column it works great: cursor.execute("UPDATE dbo.Table SET attr = 1 WHERE id = {}".format(id)) However when I try to use a string as a column value it throws error: cursor.execute("UPDATE dbo.Table SET attr = 1, user = '{}' WHERE id = {}".format(id, str(request.user.username))) Here's error message: ('42S22', "[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'Admin'. (207) (SQLExecDirectW)") Suprisingly this method works: cursor.execute("UPDATE dbo.Table SET attr = 1, user = 'Admin' WHERE id = {}".format(id)) What seems to be the problem? Why is sql mistaking column value for its name? -
In Python Django I want to run both the statements on if else that is if email is taken show it or if username show it
I have a html form fill sign up page where I am displaying if any username or email exists or not so if it exists then display username is taken and if email exists it will display email is taken but the problem is even if I give email in the email field in the html form it says username is taken but not email I tried else if like statement it didn't worked the username is taken is working perfectly but not email. Here I meant both statements should run individually If anyone knows please help This is my views.py def Register(request): try: if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') try: if User.objects.filter(username = username).first(): messages.success(request, 'Username is taken.') return redirect('/register/') if User.objects.filter(email = email).first(): messages.success(request, 'Email is taken.') return redirect('/register/') user_obj = User(username = username , email = email) user_obj.set_password(password) user_obj.save() profile_obj = Profile.objects.create(user = user_obj ) profile_obj.save() return redirect('/login/') except Exception as e: print(e) except Exception as e: print(e) return render(request , 'register.html') -
Django GraphQL API with JWT authentication implementation still allows for unauthenticated requests from Postman get data. How do I fix this?
I've built a Django API that uses django-graphql-auth and django-graphql-jwt packages to implement authentication. I followed the package's documentation and got everything to work and everything is working from my Angular UI. The only issue is that even requests made from Postman without the Authorization header, are able to fetch the data from the graphql API. This is my Django project's settings.py """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)3@2sm6lgn_p83_t(l-44hd16ou5-qbk=rso!$b1#$fu*n2^rq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] CORS_ORIGIN_ALLOW_ALL = True # Application definition INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'graphene_django', 'graphql_jwt.refresh_token.apps.RefreshTokenConfig', 'graphql_auth', 'rest_framework', 'django_filters' ] GRAPHENE = { 'SCHEMA': 'myproject.schema.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], } GRAPHENE_DJANGO_EXTRAS = { 'DEFAULT_PAGINATION_CLASS': 'graphene_django_extras.paginations.LimitOffsetGraphqlPagination', 'DEFAULT_PAGE_SIZE': 20, 'MAX_PAGE_SIZE': … -
How to use data from one table to set up a second table ith data dependecies
I am currently doing a project with Django. The goal is to implement a model for predicting human intentions. For this I am using the Django framework and the sqlight database. I have the basic models for machines, workers and positions set up. All well and good as far as it goes, but some of the values are interdependent. For example, if the worker position and the machine position are the same, then worker x is at machine y. Since I could not find a reasonable approach, I tried to use a ManyToManyField in the machine model, since several workers can be at one machine at the same time. In addition, I made the available machines known to the workers via a ForeignKey. This works, but then I have to update user on the machine side and machine on the user side. The 1.st picture shows the worker part and the machine a employee is working at The 2.st picture shows the machine part an the workers working at machine x I think there should be a way to link the data fields for machine and worker via the position field, because both classes support position information. I thought about … -
Django Admin model.clean() check properties of an uploaded file
I have a Django model which allows an image to be uploaded, but before saving in the Django Admin, I need to verify that the uploaded image meets specific criteria for its dimensions, and show a validation error if not. What I have so far (not much!)... class CertificateTemplate(models.Model): ... image_file = models.FileField( upload_to="certificate/templates", help_text=_(u"We recommend a .png image of 842px by 595px")) ... def clean(self): print("cleaning") img = Image.open(self.image_file.path) w,h = img.size print(w) print(h) Of course, this throws a FileNotFound error, as I assume the file hasn't actually been saved into the upload_to path at this point in the code. Note that there's no custom form for this, since this will all be managed directly in the Django Admin pages. How can I get the dimensions/properties of an FileField file in the model.clean() method? I presume it will be something along the lines of using TemporaryUploadedFile? Any help much appreciated, and am open to alternative methods/approaches for this. Edit: in case it makes any difference, I'm on Django 2.2