Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not Found: /build/three.module.js Django and Threejs uploading a OBJ file
i would be very grateful if someone help me, i've traying upload a obj file with Django and threejs but i get this error:enter image description here 1: https://i.stack.imgur.com/ti131.png also i'm uploading images JPG and PNG too and this upload correctly but the obj imge doesn't work in my localhost. then, i don´t know if i'm importinting well the module or if my static files are wrong 'use strict'; import * as THREE from '../build/three.module.js' import { TrackballControls } from "../jsm/controls/TrackballControls.js"; import { MTLLoader } from "../jsm/loaders/MTLLoader.js"; import { OBJLoader2 } from "../jsm/loaders/OBJLoader2.js"; import { MtlObjBridge } from "../jsm/loaders/obj2/bridge/MtlObjBridge.js"; this is a part of my TrackballControls.js import { EventDispatcher, MOUSE, Quaternion, Vector2, Vector3 } from '../build/three.module.js'; {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>three.js webgl - OBJLoader2 basic usage</title> <meta charset="utf-8"> {% load static %} <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/site.css' %}" /> <style> #glFullscreen { width: 100%; height: 100vh; min-width: 640px; min-height: 360px; position: relative; overflow: hidden; z-index: 0; } #example { width: 25%; height: 50%; margin-top: 250px; margin-left: 1010px; background-color: #000000; } #feedback { color: darkorange; } #dat { user-select: none; position: absolute; left: 0; top: 0; z-Index: 200; } … -
Django admin list filter calculated field based on two fields
I have a django model shown here. class Allocation(models.Model): allocated = models.IntegerField(default=5) used = models.IntegerField(default=0) user = models.ForeignKey(to=User, on_delete=models.CASCADE) I use a calculated field as follows. def limit_exceeded(self, obj): return obj.allocated == obj.used I want to use the same logic to use it on the list_filter. But SimpleListFilter only allows one parameter_name and no way to use both fields to check the condition. How can I achieve this? -
Gitlab CI/CD deploy Django Docker container
I have been tring to setup gitlab ci/cd config for a django project which will be deployed as a container. This is what i have tried: CI/CD - image: creatiwww/docker-compose:latest services: - docker:dind stages: - lint - build - deploy variables: TAG_LATEST: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:latest TAG_COMMIT: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:$CI_COMMIT_SHORT_SHA lint: stage: lint image: python:3.8 before_script: - pip install pipenv - pipenv install --dev script: - pipenv run python -m flake8 --exclude=migrations,settings.py backend allow_failure: false build: stage: build script: - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY_IMAGE - echo "IMAGE_APP_TAG=$TAG_LATEST" >> .env - docker-compose build - docker-compose push only: - master deploy-to-prod: stage: deploy script: - eval $(ssh-agent -s) - echo "${ID_RSA}" | tr -d '\r' | ssh-add - > /dev/null - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY_IMAGE - echo "IMAGE_APP_TAG=$TAG_LATEST" >> .env - echo "SECRET_KEY=$SECRET_KEY" >> .env - docker-compose -H "ssh://$SERVER_USER@$SERVER_IP" down --remove-orphans - docker-compose -H "ssh://$SERVER_USER@$SERVER_IP" pull - docker-compose -H "ssh://$SERVER_USER@$SERVER_IP" up -d only: - master when: manual The pipeline succeds but while checking the log of container i get following output- python: can't open file 'manage.py': [Errno 2] No such file or directory also my image field in docker ps is emoty. Please help -
Django, guidelines for writing a clean method for a ModelChoiceField
I have read the docs and I can only find guidelines on how to write a clean method for a field within a form: https://docs.djangoproject.com/en/3.1/ref/forms/validation/#cleaning-a-specific-field-attribute However I have created a field which inherits from ModelChoiceField. I wish to add some custom validation and cleaning, attached to the field and not the form, because the field is used in multiple forms, hence keeping it DRY. I can take a stab at creating a clean method, but eactly what args are passed in, and what should be returned seems to be lacking in the documentation, or I can't find it. Here my field that I wish to add custom cleaning and validation to: class FooChoiceField(forms.ModelChoiceField): def __init__(self, required=True): queryset = Foo.objects.filter(enabled=True).order_by('name') super().__init__( widget=forms.RadioSelect, queryset=queryset, to_field_name='id', # The radio button value field required=required, empty_label=None, ) self.error_messages = { 'required': "Please select a Foo.", 'invalid_choice': "Invalid Foo selected, please try again.", } # Pass the whole DB object into the template so one can access all fields def label_from_instance(self, obj): return obj Heres a guess at it? Is it good, bad? How about validation? def clean(self, value): if value != 'correct': raise ValidationError('Value is challenged in it's correctness') return value -
RuntimeWarning: DateTimeField received a naive datetime, with correct timezone and settings
I am receiving this error message: RuntimeWarning: DateTimeField Z.data_zal received a naive datetime (2020-11-05 07:13:24) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" At this step of creating my models instance: views.py from django.utils import timezone t = Z(data_z=timezone.now().strftime('%Y-%m-%d %H:%M:%S'), data_r=data_r, author=request.user) try: t.save() So as far as I know this error occurs when using datetime module instead of timezone. Sometimes the problem lies in wrong settings.py but I am running: TIME_ZONE = 'Europe/Warsaw' USE_TZ = True What seems to be the issue? -
Datatables Pagination Does Not Show
What I'm trying to do is set up a table just like this: https://datatables.net/examples/basic_init/alt_pagination.html Copied the code but then no success. I've tried so many different variables and removing all but the necessary code and I'm at a loss for what the issue may be. I've gone through several other similar SOF questions and some mentioned "sDom" could be the case so I tried a few variations I've found online but no luck yet. table.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} {% block styles %} <script type="text/javascript" href="https://code.jquery.com/jquery-3.5.1.js"></script> <script type="text/javascript" href="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script> <link rel="stylesheet" type="text/css" src="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"> {% endblock styles %} <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2> <a role="button" class="btn btn-success" href="{% url 'import' %}"><i class="fas fa-plus-circle"></i> Import New Entires</a> </div> <!-- Content Row --> <div class="row"> <div class="col-md-12"> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior … -
View uploaded files for specific object in django
I want to upload files to a client. So when I check the client they all show the same uploaded files. How do I filter through the files to show only for the specific clients who have files added to them? Model: class Document(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='docs') title = models.CharField(max_length=50) docs = models.FileField() Views.py: def fileDetails(request,pk): files = UploadFile.objects.all() client = Client.objects.all() notes = Note.objects.all() docs = Document.objects.all() context = {'files':files,'client':client,'notes':notes,'docs':docs} return render(request, 'clients/file_detail.html',context) Forms.py: class DocumentForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) I tried using a filter but nothing shows on any of my queries. I just would like to see the docs updated on a client and not see the same for all. Might be something I missed or I'm overthinking this query. -
Get_Absolute_URL Reverse Slugs By Many To Many Field From Another Model in Django
I use Slugs to address the URL. It all works but when I want to show product details. I don't know how can I get two slugs from another model and put it beside the details slug. (the category is in the main URL) (show me all products Samsung mobile) Works: site.com/category/mobile/samsung/ (I want when I want to click one of them, show me the details, but it doesn't work) Doesn't Work: site.com/category/mobile/samsung/s10 Model: from Django.db import models from Django.shortcuts import reverse class Category(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) child_category = models.ForeignKey('self', max_length=150, null=True, blank=True, on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def get_absolute_url(self): return reverse('shop:brands', args=[self.slug]) def get_absolute_url_product(self): return reverse('shop:products', args=[self.child_category.slug, self.slug]) class Product(models.Model): category = models.ManyToManyField(to=Category, related_name='products') name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) description = models.TextField() # Here I did what I knew, but It didn't work. =============================================== def get_absolute_url_details(self): return reverse('shop:product_details', self.category.model.slug, self.category.model.child_category.slug, self.slug) When I use this reverse way, it gives me this Error: 'ForwardManyToOneDescriptor' object has no attribute 'slug' URL: from Django.urls import path from Shop import views app_name = 'shop' urlpatterns = [ path('<slug:brands_slug>/', views.brands, name='brands'), path('<slug:brands_slug>/<slug:product_slug>/', views.products, name='products'), path('<slug:brands_slug>/<slug:product_slug>/<slug:product_details>/', views.details_products, name='product_details'), ] View: def products(request, brands_slug, product_slug): product = Product.objects.filter(category__slug=product_slug, category__child_category__slug=brands_slug) context = … -
Django: how to change the width of AdminDateWidget?
In admin page, I am trying to customise the width of DateField by tweaking attrs of AdminDateWidget in formfield_overrides as below formfield_overrides = { models.DateField: { 'widget': admin.widgets.AdminDateWidget(attrs={'size': '8', 'style': 'width:8ch !important;'}), } } Either changing the size nor style works. What should I do to change the width? Thank you! -
calculate numbers of anuual leave for employees every month
I have Django program for calculating salary of every employee and detect leave days that taken in this month from salary ,the problem that some of employee they apply for leave before like one or to month and program start detecting from salary in month that they apply , so can I write code that can detect from salary only if leave date in the current month. -
Is there any method of integrating ReactJS and Django without implementing Django Restful API?
Guys as you may know when using Vanilla JS you can just deliver html files to Django and just code between the lines in Python language in order to create the functionalities that you need in your backend side of your web application. However this is not the case when we use React JS. Is there any similar way(as vanilla JS and html files)for integrating REACT.JS and Django(except for using rest api endpoints)? -
Django python ValueError: not enough values to unpack (expected 2, got 1)
I have this code to in my views.py that will export to excel, i combined two query in 1 loop but i receive this error ValueError: not enough values to unpack (expected 2, got 1) reports = TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')).order_by('-inputdate') daily = FmCustomerEmployeeSupplier.objects.filter(id__in=reports.values_list('fmCustomerEmployeeSupplierID')) pairs = [reports, daily] for report, day in pairs: writer.writerow( [ smart_str(report.id), smart_str(report.dateSubmitted), smart_str(report.fmCustomerEmployeeSupplierID), # smart_str(report.fmCustomerEmployeeSupplierID.lastname), # smart_str(report.fmCustomerEmployeeSupplierID.middleInitial), smart_str(day.fmCustomerLocationID), smart_str(day.contact_number), smart_str(day.fmCustomerSectionID), smart_str(day.bodyTemperature), smart_str(report.q1Answer), smart_str(report.q2Answer), ] ) return response -
perform_create function in the django view. How it is different from create function?
I am new to django rest api. I need to create a comment api which is posted in database for a particular blogdetail page. But I dont understand this perform_create function? What does this method does and how it is different in create function?? class CommentCreateAPIView(CreateAPIView): permission_classes= [IsAuthenticated] queryset = Comment.objects.all() serializer_class = CommentListSerializer def perform_create(self, serializer): # user = self.request.user blog = get_object_or_404(BlogPost, pk= self.kwargs['pk']) serializer.save(blog=blog) class BlogPostDetailSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api-blog-post_details', read_only=True) comments= CommentListSerializer (many=True) class Meta: model = BlogPost fields = ['id', 'url', 'image', 'categories', 'description', 'content', 'tags', 'date_created', 'comments'] # fields = '__all__' class Comment(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=255) email = models.EmailField() subject = models.CharField(max_length=255) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: ordering = ('created_at',) Also, when I used 'user' in that perform_create function inside serializer.save, it generates error. what is the issue? -
How to use Django db.sqlite3 database with React?
I want to use Django as backed with react and I have already integrated Django with react app. And my react app(blog in my case) is up and running with Django. I have made following changes to do so. Dir for templates inside settings.py: Dir for Static Files inside settings.py: In urls.py rendered template without using views.py: But now I want to use the Django's db.sqlite3 as my database for react app. Please tell me how to configure it ? What additional settings I need to configure to fetch data from db.sqlite3 database inside react app ? If more information about the settings are required then tell me I will edit my question accordingly. -
NoReverseMatch at /add_post Reverse for 'article-details' with arguments '('4', '0')' not found. 1 pattern(s) tried: ['blogpost/(?P<pk>[^/]+)$']
Getting this issue in my django blog project. Everything is specified neatly but I don't understand why it is crashing. urls.py : from django.urls import path from .views import Homeview, ArticleDetailView, AddPostView urlpatterns = [ path('', Homeview.as_view() , name="home"), path('blogpost/<str:pk>', ArticleDetailView.as_view(), name='article-details'), path('add_post', AddPostView.as_view( ), name="add_posts") ] models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse ''' class Post(models.Model): blog_title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(default="") def __str__(self): return self.blog_title + '|' + str(self.author) def get_absolute_url(self): return reverse('article-details', args = str(self.id)) articledetails.html* {% extends 'home/base.html' %} {% block content %} <h1>{{post.blog_title}}</h1> </br> {{post.body}} {% endblock %} -
Error in Models raise TypeError('on_delete must be callable.')
when i run following command python manage.py makemigrations I have this error enter code here File "C:\Users\pc\Desktop\django\Chocolate\shop\migrations\0002_product.py", line 21, in Migration ('p_cat', models.ForeignKey(blank=True, null=True, on_delete='models.CASECADE', to='shop.category')), File "C:\Users\pc\Envs\test\lib\site-packages\django\db\models\fields\related.py", line 813, in __init__ raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable``` [1]: https://i.stack.imgur.com/ujUkQ.png -
Why is my API data nt showing up on my django html page?
I am fairly new to coding in general so apologies for my dumb question. I created an API in Node. I put some filler data in the DB and tested the API. Works fine. I created a Django app that attempts to access the data in the API. I am using a CORS module so I can access the API on my local machine. When I load the home page, a GET request is sent to the API, and I can see that the API receives the request. I don't know if any data is being sent back. Nothing shows up in the table on the home page. -API routes- (all routes are starting with /questions) router.get('/', queryQuestions); router.post('/', addQuestion); router.delete('/:uid', deleteQuestion); router.get('/:uid', queryQuestion); router.patch('/:uid', updateQuestion); -Django view- from django.shortcuts import render from django.shortcuts import redirect from django.contrib import messages def home(request): import json import requests api_request = requests.get("http://localhost:3000/questions") try: api = json.loads(api_request.content) except Exception as e: api = "Error..." return render(request, 'frontend/home.html', {'api': api}) Django template 'home' (sample) <table class="table table-striped table-bordered table-hover"> <thead class="thead-dark"> <tr> <th scope="col">ID</th> <th scope="col">Question</th> <th scope="col">Category</th> </tr> </thead> <tbody> {% if api %} {% for list_item in api %} <tr> <td>{{ list_item.uid }}</td> … -
Send mail different email id's when user click Button in Django?
I make real-estate system project, i am try to when user see property and they interested so click "interested" Button then send email to seller register email id and message is " someone(interested email id) is interested in your property id. How to do this if you know so plz know me -
I am trying to convert a python project into exe file however I am getting an 'unexpected EOF while parsing' error
I am using Auto-py-to-exe to convert the python project to an executable file. I am trying to export a Django project to production. I need help to convert the project into exe for commercial use. I am currently stuck. I keep getting this error whenever I try to convert the project using Auto-py-to-exe. Here is the full error An error occurred while packaging Traceback (most recent call last): File "d:\anaconda\envs\deepface\lib\site-packages\auto_py_to_exe\packaging.py", line 131, in package run_pyinstaller() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\__main__.py", line 114, in run run_build(pyi_config, spec_file, **vars(args)) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\__main__.py", line 65, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\build_main.py", line 720, in main build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build')) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\build_main.py", line 667, in build exec(code, spec_namespace) File "C:\Users\ASUSVI~1\AppData\Local\Temp\tmpk_w1xzg6\mask_detection.spec", line 17, in <module> noarchive=False) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\build_main.py", line 242, in __init__ self.__postinit__() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\datastruct.py", line 160, in __postinit__ self.assemble() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\build_main.py", line 419, in assemble self.graph.process_post_graph_hooks() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\depend\analysis.py", line 365, in process_post_graph_hooks module_hook.post_graph() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\depend\imphook.py", line 440, in post_graph self._load_hook_module() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\depend\imphook.py", line 407, in _load_hook_module self.hook_module_name, self.hook_filename) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\compat.py", line 588, in importlib_load_source return mod_loader.load_module() File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper File "<frozen importlib._bootstrap_external>", line 823, in load_module File "<frozen importlib._bootstrap_external>", line 682, in load_module File "<frozen importlib._bootstrap>", line 265, in _load_module_shim File "<frozen importlib._bootstrap>", … -
how to start celery periodic task at 9:30 to 12:30 every 30 seconds?
I want to run a celery task in Django from 09:30 to 12:30 for every 30 seconds. Is it possible to turn the interval on for 30 seconds and turn on the interval schedule only for a certain period of the day? -
Django Project and .net project with same database (Postgresql)
I have two project which is Django Project and .net Project with the same database (Postgres). what is the recommended way for them not to have a conflict? because there is a problem when I call a certain field of a table using foreignkey just like this in my views.py reports = TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')).order_by('-inputdate') for report in reports: writer.writerow([ smart_str(report.fmCustomerEmployeeSupplierID.lastname), smart_str(report.fmCustomerEmployeeSupplierID.firstname), smart_str(report.fmCustomerEmployeeSupplierID.middleInitial), ]) return response this is my models.py class TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords(models.Model): fmCustomerEmployeeSupplierID = models.ForeignKey('FmCustomerEmployeeSupplier', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerEmployeeSupplier") class FmCustomerEmployeeSupplier(models.Model): dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) lastname = models.CharField(max_length=500, blank=True, null=True) firstname = models.CharField(max_length=500, blank=True, null=True) middleInitial = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField(blank=True, null=True) def __str__(self): suser = '{0.lastname} {0.firstname} {0.middleInitial}' return suser.format(self) @property def is_past_due(self): return date.today() > self.modifyDate class Meta: verbose_name_plural = "50. Customer's List of Employees, Suppliers and visitors" -
Django run a function while exiting a view or navigating to a different URL from the current URL
In my django application, when I visit a particular URL ex:enter_database, a view function is called that adds database entries. Now when I visit a different URL, I want to clear the database entries. My question, is it possible to call a method while leaving a view/URL. Note: I can clear the entries by adding the logic in every other view, which is not the approach I want to do. I am looking for a way to call a method while exiting the current displayed view. -
Django profile image is incorrectly displaying the logged in user's image (on every profile)
Any assistance in this would be much appreciated. Problem: Logged in user image is displaying on every user's profile in Django 3.1 I extended the Django User model with a OneToOne relationship to another model called UserProfile, which contains an ImageField called profile_pic. Settings for root media folder are setup correctly in settings.py and referred to in root urls.py. Something is incorrect with the class-based view, a generic ListView to display a user's product posts, or I'm incorrectly referring to the profile_pic in the template. Any ideas on how to display each user's profile image on their associated userprofile? Currently, when a user is logged in, his/her image is displaying on every profile. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default_profile_pic.jpg', upload_to='profile_pics') class Meta: verbose_name_plural = "User Profiles" def __str__(self): return f'{self.user.username} UserProfile' def save(self, *args, **kwargs): super().save(*args, **kwargs) views.py class ProfileListView(ListView): model = Product template_name = 'users/profile.html' context_object_name = 'products' paginate_by = 12 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) # userprofile = UserProfile.objects.filter(user_id=userprofile) return Product.objects.filter(user=user).order_by('-creation_date') profile.html {% if user.userprofile.profile_pic %} <img class="rounded-circle" src="{{ user.userprofile.profile_pic.url }}" alt=""> {% else %} <img class="rounded-circle" src="media/default_profile_pic.jpg" alt=""> {% endif %} -
Limit Foreign Key Options in Django Select
I have a model for Supplier and another model for Product. Each Product must have a Supplier instance associated to it. Later on, in a separate model form for the Proforma model, the user has to select a Supplier and then a Product. What I'd like to see happen is the Product select options filter down to Products where the Supplier = the Supplier the user has selected. I am not finding much on how to handle this use case...could anyone point me in the right direction? Will this require the use of JS or can I do something to set this in the form directly? Or maybe pass a queryset from the view to this field? Anything even some resource on this would be helpful. models.py class Supplier(models.Model): supplierName = models.CharField(max_length=100) class Product(models.Model): code = models.CharField(max_length=100) supplier = models.ForeignKey(Supplier, null=False, blank=False) class Proforma(models.Model): ... supplier = models.ForeignKey(Supplier, null=False, blank=False, on_delete=models.CASCADE) code = models.ForeignKey(Product, null=True, blank=True, on_delete=models.CASCADE) -
Uploading image into ModelForm in Django?
I am having trouble uploading an image into with a form through Django. The file does not appear in my `templates/auctions' directory, nor does it render in my template (probably because it never uploaded). In my views.py: @login_required(login_url="login") def createListing(request): if request.method == "POST": filled_form = CreateListing(request.POST, request.FILES) if filled_form.is_valid(): user = User.objects.get(username=request.user) new_listing = filled_form.save(commit=False) new_listing.listed_by = user new_listing.save() return HttpResponseRedirect(reverse("index")) else: context = { "createlistingform": filled_form } else: context = { "createlistingform": CreateListing() } return render(request, "auctions/createlisting.html", context) I tried to replicate the approach in "Handing uploads with a file" and it's still not working. My AuctionListing model in models.py has this field: image = models.ImageField(blank=True, upload_to="images/") and my project file settings.py has this configuration: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Is my commit=False in the views.py creating an issue?