Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image file cannot be found when using URL loader of webpack with React & Django
I am struggling with loading images using the img-tag within a React component. Basically I am using webpack's url loader to load the images and add a hash (to avoid later caching issues). When running "npm run dev" the bundle is created and the image file gets created in the specified subfolder "images". However, Chrome cannot find the image and gives me the following error: GET http://localhost:8000/images/49b281dc3f9e139385f943c7e3f918b1-git.jpeg 404 (Not Found) More specific: The bundle "main.js" is created in the frontend folder (as given in the index.html) and has a subfolder "images" with the file created by the URL loader: 49b281dc3f9e139385f943c7e3f918b1-git.jpeg I tried loading the image with css, which works (i.e. is shown in the browser), however the url-loader seems not to be used in this case as the hash does not get added and the file is loaded from the original location and not the place of the bundle. I saw another thread about the topic (How to load image files with webpack file-loader) but cannot see how publicpath should be of help for my case. The problem might also be related with my setup with Django: I have put a frontend app into the Django project, where all the … -
Django how to sum the scores of single user for different activities and display in front end only total score
i am posting my models.py from django.db import models from django.contrib.auth.models import User class Activity(models.Model): activity = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) score = models.IntegerField(default=0) def __str__(self): return self.activity class Name(models.Model): name = models.CharField(max_length=30) designation = models.CharField(max_length=100) score = models.IntegerField(default=0) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) def __str__(self): return self.name posting views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from .models import Name #from .models import Score from .models import Activity from django.db.models import Sum #from .models import Justification # Create your views here. def home(request): boards = Name.objects.all() return render(request, 'home.html', {'boards': boards}) def Score(request): boards = Score.objects.all() return render(request, 'home.html', {'boards': boards}) def Activity(request): boards = Activity.objects.all() return render(request, 'home.html', {'boards': boards}) Posting html template {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Score Board</title> <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> <li class="breadcrumb-item active">Score Board</li> </ol> <table class="table table-striped table-bordered table-sm" cellspacing="0" width="100%"> <thead class="thead-dark"> <tr> <th class="th-sm">Name <i class="fa fa-sort float-right" aria-hidden="true"></i> </th> <th class="th-sm">Score <i class="fa fa-sort float-right" aria-hidden="true"></i> </th> <th class="th-sm">Activity <i class="fa fa-sort float-right" aria-hidden="true"></i> … -
for quiz app how to write a function in django
in quiz app user should take the test and if the answer is less than the 70% of total answer the should take retestbor else proceed to thank you page models class Quiz(models.Model): question = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return self.question class Options(models.Model): question = models.ForeignKey(Quiz,on_delete=models.CASCADE) option1 = models.CharField(max_length=20, blank=True, null=True) option2 = models.CharField(max_length=20, blank=True, null=True) option3 = models.CharField(max_length=20, blank=True, null=True) option4 = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return self.option1 class Check(models.Model): question = models.ForeignKey(Quiz,on_delete=models.CASCADE) answer = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return "{0}".format(self.question) class QuestionForm(ModelForm): class Meta: model = Options fields = ['option1', 'option2', 'option3', 'option4'] views class QuestionView(View): template_name = 'training/questions.html' def get(self, request): form = QuestionForm() option = Options.objects.all() return render(request, self.template_name, {'form':form, 'q': option,}) def post(self, request): abc=0 form = QuestionForm(request.POST) if form.is_valid(): abc = form.cleaned_data['answer'] return render(request, self.template_name, {'form':form, 'abc':abc}) forms from django import forms from .models import Options class QuestionForm(forms.Form): options = forms.ModelMultipleChoiceField(queryset=Options.objects.all()) html {% extends 'training/home.html' %} {% load static %} {% block content %} <div class="main-question"> <div class="question"> <form method="post"> <section> {%csrf_token%} {% for ques in q %} {{ forloop.counter }}) {{ ques.question }} <div class="options"> <input type="radio" name="{{ ques.id }}" value={{ ques.option1 }} id="q1a"> a. {{ ques.option1 }}<br><br> <input type="radio" … -
Django: can't iterate over and access a simple queryset
For my API, I have to find out to what projects a user has access to, and return them. I try to do this like so: def get_queryset(self): user = self.request.user allow_all = user.is_superuser or user.is_staff or settings.API_UNSAFE if self.action == 'list' and not allow_all: projects = Project.objects.all() user_projects = Project.objects.none() for project in projects: permission = Permission.objects.filter(user=user.user, table_name='Project', fk=project.id) if permission.count() > 0: user_projects = user_projects | project return user_projects return Project.objects.all() Which results in: 'Project' object is not iterable So I used values() instead of all(). But when you use .values it's no longer possible to concat the instance with a queryset. Meaning I have to query the same project twice, resulting in this hacky approach: projects = Project.objects.values() user_projects = Project.objects.none() for project in projects: permission = Permission.objects.filter(user=user.user, table_name='Project', fk=project['id']) if permission.count() > 0: # Wanted to use .get() here, but that threw the same error user_project = Project.objects.filter(id=project['id']) user_projects |= user_project return user_projects Surely there is a better way, what am I doing wrong? -
how to handle Django nested template tags
How to handle the variable inside the template tag {% %},I need to give arguments to my function send_mail_view() urls.py urlpatterns = [ path('send_mail_view/<sender_email>/<receiver_email>/<doc>',views.send_mail_view, name='send_mail_view'), ] mailing_app/views.py def send_mail_view(request,sender_email,receiver_email,doc): email=EmailMessage( 'i want to hire you Nitish ', 'please provide your resume', sender_email, [receiver_email] ) email.attach_file('mailing_app/179.pdf') res=email.send(fail_silently=False) success_msg="mail sent success fully" return render(request,'mailing_app/success.html',{'success_msg':success_msg}) student_app/views.py def student_main_view(request,username): user_obj=User.objects.filter(username=username) pdf_student_model_obj=pdf_student_model.objects.filter(username__in=user_obj) pdf_list=[] for p in pdf_student_model_obj: print("nikseva",type(p.pdf_id)) pdf_indexing_model_obj=pdf_indexing_model.objects.filter(pdf_id=str(p.pdf_id)) for x in pdf_indexing_model_obj: pdf_list.append({'pdf_id':x.pdf_id,'pdf_title':x.pdf_title,'pdf_abstract':x.pdf_abstract,'pdf_path':x.pdf_path,'sender_email':"n@gmail.com",'receiver_email':username,}) print("pdf_list",pdf_list) return render(request,'rnd_app/student_mainpage.html',{'pdf_list':pdf_list}) templates/mail.html {% for z in pdf_list %} pdf_title :{{z.pdf_title}} pdf_abstract:{{z.pdf_abstract}}<br> pdf_path:{{z.pdf_path}} <a href="{% url 'mailing_app:send_mail_view' {{request.user.username}} {{z.receiver_email}} {{z.pdf_path}} %}" class="btn1 ">Send Email</a> {% endfor %} -
Static files not found with Django/React app on AWS
I am trying to deploy a Django/React app to AWS. I have an issue where the server isn't picking up the static files. I think I have configured everything correctly but doesn't show anything. I am not sure if I am missing a step because it seems to work correctly on PythonAnywhere but not AWS. Here is my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') I ran python manage.py collectstatic which generated my files to the root directory. It outputs static files copied to '/home/ubuntu/test/test/static'. The error I get in the console is as follows GET http://ec2-18-217-253-182.us-east-2.compute.amazonaws.com:5000/static/assets/vendor/bootstrap/css/bootstrap.min.css net::ERR_ABORTED 404 (Not Found) I am hoping someone has had this same issue because the several other solutions on SO haven't solved the problem. This is the file structure currently test/ ├── test/ ├── frontend/ └── static/ -
Using Django REST JWT auth with standard views
I'm new to Python in general and Django in particular. I'm building a project using the Django REST framework with JWT auth (http://getblimp.github.io/django-rest-framework-jwt) My views that are built on REST framework viewsets work perfectly. However, I need to expose an endpoint that will call an upstream API and return the result. If I do not use the REST framework then Django routes are not protected. If I use the REST framework then the viewset expects a standard database query. How do I either: Use JWT auth on a standard Django route Use a standard view class with REST framework -
Python manage.py migrate error when changing database from sqlite to mysql
I just started learning django. I change the following settings from setting.py because I want to use mysql not sqlite: DATABASES = { 'default' : { 'ENGINE' : 'django.db.backend.mysql', 'NAME' : 'newprj', 'USER' : 'root', 'PASSWORD' : 'abcd', 'HOST' : 'localhost', 'PORT' : '' } } then when I try this code python manage.py migrate on cmd. It throws an big error, I can't understand what is the problem, please help me solve it. This is the error: -
Is it possible to add a calculated hyperlink in a django REST serializer?
I have this serializer that represents content abstract where I would like to add an hyperlink field that is not in the model, but calculated by the framework linked to the ContentsSerializer. class ContentsAbstractSerializer(serializers.HyperlinkedModelSerializer): content_url = ??? class Meta: model = Contents fields = ('content_url','content_id','content_title', 'content_abstract','start_date','stop_date','last_date','content_status','version') class ContentsSerializer(serializers.HyperlinkedModelSerializer): categories = CategoriesContentsSerializer(read_only=True, many=True) class Meta: model = Contents fields = ('content_id','content_title', 'content_abstract', 'content_body','start_date','stop_date','last_date','content_status','version','sections', 'images','attaches','categories') I would like to have a result like this: { "content_url":"http://mysite/Content/125", "content_id": 125, "content_title": "this is the title", "content_abstract": "This is the abstract", "start_date": "2005-01-12", "stop_date": "3000-01-12", "last_date": "2019-02-27T09:40:38Z", "content_status": "PUBLISHED", "version": 0 }, -
Django Rest Framework: How to associate the object with the user when posting the object
I'm new to creating REST API so I might misunderstand something. I'm creating REST API using Django Rest Framework. And I'm trying to create an object and send it from my mobile app. However, API returns 400. I think it still cannot associate the object with the request user and I'm wondering how to do it. models.py class Item(models.Model): item_name = models.CharField() created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE) serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('item_name', 'created_by') and views.py class ListItems(generics.ListCreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer What I want to know is how to associate the object with the request user when posting the object like as we do like if form.is_valid(): item = form.save(commit=False) item.created_by = request.user item.save() -
Loading related primary keys without PrimaryKeyRelatedField loads too long
To load related primary keys with a serializer it is possible to: use serializers.PrimaryKeyRelatedField(many=True, read_only=True) not define a related Serializer Why does it take more than 20 seconds to load 6 records if I don't define a related serializer? AltSchool/dynamic-rest is used together with djangorestframework==3.7.7 Thanks for any conceptual explanation. -
Unable to import module in django
I'm trying to import module in django but it returns 'import' is not recognized as an internal or external command, operable program or batch file. Any suggestions ? -
Django 2.1- Django Builtin Admin not working with using Jinja2
I m trying to open Django default Admin, but is always giving error ("Encountered unknown tag 'load'.",) While i setup Template 'env' for both. When in swap with each-other, django-admin start working but jinja stops. my setting.py for templates TEMPLATES = [ { #'BACKEND': 'django.template.backends.jinja2.Jinja2', 'BACKEND': 'config.jinja2_environment.CustomJinja2', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'config.jinja2_environment.environment', 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ] }, }, # This template will work as fallback as the django default admin doesn't have jinja2 { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, } ] my custom jinja2 env file that is parallel to setting.py in config project from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from jinja2 import Environment from django.template.backends.jinja2 import Jinja2 from django.utils.timezone import now class CustomJinja2(Jinja2): app_dirname = 'templates' def environment(**options): env = Environment(**options, extensions=[]) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, "now": now }) return env -
Convert a Django application to Meteor
I have developed a Django application and now i want to move it to meteor framework. I do not want to change the backend to any other but use python and MongoDB. Use an API to call my pythons scripts. My scripts are in python and using MongoDB. And front end html files with few java scripts and Highcharts library. I do not want to change the backend to any other but use python and MongoDB. But i want to use React as the templating component. How do i integrate React with highchart ? Any step by step procedure to follow ? That would be really helpful. -
How can I see Mysql raw query in django? not result of query
I just want to check raw query in my Django project my logging setting is 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, } 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console'], } } enter image description here and when i run project, console show a result of query. I don't know what's matter... please solve this problem! thanks! -
No debug information upon exception in Django custom field
I created a custom ImageField in Django 1.11, sub-classing the native ImageFieldFile: class ImageWithThumbsFieldFile(models.fields.files.ImageFieldFile): def __init__(self, *args, **kwargs): super(ImageWithThumbsFieldFile, self).__init__(*args, **kwargs) ... def save(self, name, content, save=True): ... The whole thing works well, however, when I do have any sort of bug within the save method, Django doesn't return a proper exception page. I only see a server error 500 - no debug information at all. Is this normal behavior for errors within a sub-classed field method? Is there a way to get debug info in case of an error? Thanks! -
Autofill form with data from html and views
I am trying to fill up an order form on another page based on a forecast created by the system with the following code: form.py: class SupplierPOForm(ModelForm): class Meta: model = SupplierPO fields = ('delivery_date', 'supplier') widgets = { 'delivery_date': DateInput() } supplier = forms.CharField(max_length=200, label = 'supplier', widget = forms.Select(attrs={'id':'supplier'})) views.py: def inventory_forecast_details(request, id): item = Inventory.objects.get(id=id) ... context = { 'item': item, 'i': i, 'forecast_1': forecast_1, 'forecast_2': forecast_2, 'forecast_3': forecast_3, 'forecast_4': forecast_4, } return render(request, 'inventory/inventory_forecast_details.html', context) Ideally, what happens is when the user presses the 'order' button, they will be redirected to the PO form page with the data from the forecast in the views automatically inputted in the fields of said form page. What is the best way to go about this? -
Tried so manty things but still I can,t fix this error?
Hey guys I have ran into an error with migrations from past two days.I added a new field into a model and then I tried to run migratons It worked fine but when I tried to migrate then I got a datetime error.Scratched my head an dfinally deleted my database.And than It worked fine but when I try to migrate It now shows me return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: app_upload Even though I have a Upload model here,s the models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from tinymce import HTMLField from datetime import datetime class Category(models.Model): title = models.CharField(max_length = 20) def __str__(self): return self.title class Post(models.Model): image = models.ImageField() title = models.CharField(max_length = 100) body = HTMLField() published_date = models.DateTimeField(auto_now_add = True) categories = models.ManyToManyField(Category) featured = models.BooleanField(default = False) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog',kwargs = { 'pk':self.pk }) @property def get_comments(self): return self.comments.all() class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments") name = models.CharField(max_length = 200) body = models.TextField(default = True) parent = models.ForeignKey("self",on_delete = models.CASCADE) pub_date = models.DateTimeField(auto_now_add = True) class Meta: ordering = ['-pub_date'] def __str__(self): return self.name def children(self): return Comment.objects.filter(parent = self) @property … -
MultiValueDictKeyError while uploading a media file(.mp4) through Django REST API POST Call
I am new to Django REST Framework. I have created an API which takes a MP4 file as an input, processes it and gives a response. I am able to upload file through API browser page and get the result. However, when i am trying to call the API through a local python file i get the following error: MultiValueDictKeyError at /api/ 'file' Request Method: POST API call: import requests import json url = 'http://182.xx.xx.xx:8000/api/' video_file = '/home/lueinuser/Downloads/original.mp4' # 30 MB file in my Local system payload = {'file' : video_file} r = requests.post(url=url,data=payload) print(r.text) Views.py class ApiCallingListView(generics.ListCreateAPIView): queryset = ApiCallingModel.objects.all() serializer_class = ApiCallingSerializer parser_classes = (MultiPartParser, FormParser) def post(self, request, format=None, *args, **kwargs): file_serializer = ApiCallingSerializer(data=request.data) file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(file.name, file) uploaded_file_url = settings.MEDIA_ROOT + '/' + str(filename) data_dict = {'video_file': request.FILES} request.data['response']= api_wrapper(uploaded_file_url) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Models.py class ApiCallingModel(models.Model): file = models.FileField(blank=False, null=False) user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) response = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) -
Django: running migrate command shows a "SECRET_KEY setting must not be empty" error
When I run the python manage.py migrate command, I get the The "SECRET_KEY setting must not be empty" error with the following stacktrace. i however have the SECRET_KEY set in my settings\local.py file and i am using the py manage.py runserver --insecure --settings=locallibrary.settings.local command to run the django application. What am I missing(hopefully this is not a newbie mistake)? Traceback (most recent call last): File "manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\core\management\__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\core\management\__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\AjitGoel\Envs\my_django_environment\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\core\management\commands\makemigrations.py", line 12, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\db\migrations\autodetector.py", line 11, in <module> from django.db.migrations.questioner import MigrationQuestioner File "C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\db\migrations\questioner.py", line 9, in <module> from .loader import MigrationLoader File "C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\db\migrations\loader.py", line 8, in <module> from django.db.migrations.recorder import MigrationRecorder File … -
for loop not working in unit testing in django
I am running a Simple Django Unit test of my model(User) to check the type of attribute of my model. I have a username attribute which is of CharField. When I am running the below code it showing my test case passed with no errors and also the username is not getting printed, which is inside the for loop. class UserModelTest(TestCase): def test_fields(self): ob=User.objects.all() for object in ob: print(object.username) self.assertIsInstance(object.username,int) I think the output should be an error since I am checking with an Integer type and the usernames should get printed. Can anyone please tell me where I am doing wrong. -
Problem while executing "python manage.py runserver" in django
I have been using django (2.1.5) with mysql-connector(2.1.6). Suddenly it has stopped working and giving below error when i do "python manage.py runserver". I have been trying to understand the solution through other question on same issue but it doesn't seem to help.Can somebody please help. (ApiEnv) E:\Aabha\ApiEnv\adventureworks>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000000F2445DE9D8> Traceback (most recent call last): File "E:\Aabha\ApiEnv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "E:\Aabha\ApiEnv\lib\site-packages\django\core\management\commands\runser ver.py", line 109, in inner_run autoreload.raise_last_exception() File "E:\Aabha\ApiEnv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "E:\Aabha\ApiEnv\lib\site-packages\django\core\management\__init__.py", l ine 337, in execute autoreload.check_errors(django.setup)() File "E:\Aabha\ApiEnv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "E:\Aabha\ApiEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\Aabha\ApiEnv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "E:\Aabha\ApiEnv\lib\site-packages\django\apps\config.py", line 198, in i mport_models self.models_module = import_module(models_module_name) File "E:\Aabha\ApiEnv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\Aabha\ApiEnv\lib\site-packages\django\contrib\auth\models.py", line 2 , in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "E:\Aabha\ApiEnv\lib\site-packages\django\contrib\auth\base_user.py", lin e 47, in <module> … -
The ImageField attribute has no file associated with it, can't figure out why
So I am trying to generate a QR code on creation of the Device Model and save it to the device model, for some reason even though I can generate the image, I can't save it to the model. I've tried saving with a filebuffer instead, that gave me an error, I just don't know what else to try. The error is The 'qrcode' attribute has no file associated with it. def Device(models.Model): qrcode = models.ImageField(blank=True, upload_to="qrcode") def save(self, *args, **kwargs) self.generate_qrcode() super(Device, self).save(*args, **kwargs) def generate_qrcode(self): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=6, border=0, ) qr.add_data("http://localhost/ims/device/" + str(self.id)) qr.make(fit=True) img = qr.make_image() filename = str(self.id) + '.jpg' img.save(filename) -
Using images in 2 different django models
I have a retail site selling multiple brands. Each brand has its logo on their own page. The logo images are in their own model. How do I use the same logo for a different model on the index page? I'd like to use the same logos while highlighting some store coupons in the sidebar. Currently I have a Foreign Key to the store in the IMG model. current code: Models class Logo(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="storelogo") image = models.ImageField(upload_to=get_image_path) Views: def show_store(request, slug): store = Store.objects.get(slug=slug) uploads = store.storelogo.all() return render(request, 'store.html', { 'store': store, 'products': products, 'coupons': coupons, 'uploads': uploads, }) HTML: <div class="store-logo"> {% for logo in store.storelogo.all %} <img src="{{ logo.image.url }}"> {% endfor %} </div> The logo shows fine on the store page but I can't get it to show in a For loop on the index page. Is it possible? I could add another image model and add the exact same logo images for the coupons but it seems to be totally against DRY principles. Are there template tags I can use on index page or is it best to create another model? Let me know if I left anything out. Thanks! -
How do you pass additional URL values to Django generic DeleteView?
Suppose I have models.py: class Parent(nodels.Model): name = models.CharField(max_length=20) class child(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) Now in the Detail View of a Parent I list out the children that belong to the parent. The urls.py for this would look like path('parents/<int:pk>/, views.ParentDetailView.as_view(), name='parent-detail') And I'd use a django DetailView in my views.py like this class ParentDetailView(DetailView): model = Parent Now in this detail view I list out the children of the parent with something like parent_detail.html in my templates {{parent}} {% for child in parent.child_set.all %} {{ child.name }} {% endfor %} But I'd like to be able to delete the child from the database from here on this page, so I'd add something like {{parent}} {% for child in parent.child_set.all %} {{ child.name }} <a href="{% url 'myapp:parent-delete-child" parent.pk child.pk %}">Delete child</a> {% endfor %} Here's where I'm stuck! I would love to have something like this in my urls.py path('parents/<int:pk>/', views.ParentDetailView.as_view(), name='parent-detail'), path('parents/<int:pk>/delete_child/<int:child_pk>/', views.ParentDeleteChildView.as_view(), name='parent-delte-child') But I have no idea how to send the pk and the child_pk to the generic django DeleteView?!?!?! class ParentDeleteChildView(DeleteView): model = Child success_url = reverse_lazy('myapp:parent-detail' kwargs={'pk':pk}) After deleting I want to go back to the parent detail page. But …