Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django wizard form goes to the prev step instead of next step
I have a 3 step form. So when I'm at the second step and hit enter, it goes to the prev step instead of next step. This is my set up: forms.py class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) class ContactForm2(forms.Form): sender = forms.CharField(max_length=100) class ContactForm3(forms.Form): message = forms.CharField(widget=forms.Textarea) views.py class Prueba(SessionWizardView): template_name = 'start.html' form_list = [ContactForm1, ContactForm2, ContactForm3] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) urls.py urlpatterns = [ path('prueba', Prueba.as_view(), name='prueba') ] start.html <form action="" method="post"> {% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form.as_table }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input id='btncont' type="submit" value="Continuar"/> </form> I've use this jquery code but doesn't work because when I press enter, goes to the prev step. $(document).ready(function(){ $('#id_1-sender').keypress(function(e){ if(e.keyCode==13) $('#btncont').click(); }); }); -
How to iterate javascript function in rows?
I created a search and highlight field for my model objects. The page takes a text input and filtering the objects like Documents.objects.filter(content) I'm using read more and highlight functions to highlight the input word and show the a part of the long content. But I can't click some read mores on the row. For example I can't click 1st and 3rd row (it returns javascriot:void(0) but there is no action) but I can click the other rows. I couldn't find why? <td> <div id="highlights" > <div class="row"> <div class="col-md-12" > <div class="box"> <p class="countParawords-{{ forloop.counter }}" id="paragraph-{{ forloop.counter }}"> {{ document.content }} </p> </div> </div> <input id="typed-text-{{ forloop.counter }}" type="text" class="hidden_input" placeholder="Type text" value="{{ key_word }}"> </div> </div> </td> <script> {% for doc in documents %} var opar = document.getElementById('paragraph-{{ forloop.counter }}').innerHTML; $(document).ready(function() { var maxLength = 300; var moretxt = "...Read More"; var lesstxt = "...Read Less"; $(".countParawords-{{ forloop.counter }}").each(function() { if(opar) { var paragraph = (document.getElementById('paragraph-{{ forloop.counter }}')); var search = document.getElementById('typed-text-{{ forloop.counter }}').value; search = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); var re = new RegExp(search, 'g'); if (search.length > 0) paragraph.innerHTML = opar.replace(re, `<span style="background: #cead00">$&</span>`); } else{ console.log("No data") } var myStr = paragraph.innerHTML if ($.trim(myStr).length > maxLength) … -
Having trouble accessing a Django database from a Python project
I’m trying to do a rudimentary connect to a database I created in a Django project (in PyCharm) from another (new) Python project in PyCharm and struggling to even get a list of tables displaying from Python. Could anyone advise on what I might be doing wrong, am I setting the name of the database incorrectly or do I need to do some step before this to connect a name to the database? I have the following connection (right panel): And my code is as follows (copied from an example): import sqlite3 try: # Making a connection between sqlite3 # database and Python Program sqliteConnection = sqlite3.connect('identifier.sqlite') # If sqlite3 makes a connection with python # program then it will print "Connected to SQLite" # Otherwise it will show errors print("Connected to SQLite") # Getting all tables from sqlite_master sql_query = """SELECT name FROM sqlite_master WHERE type='table';""" # Creating cursor object using connection object cursor = sqliteConnection.cursor() # executing our sql query cursor.execute(sql_query) print("List of tables\n") # printing all tables list print(cursor.fetchall()) except sqlite3.Error as error: print("Failed to execute the above query", error) finally: # Inside Finally Block, If connection is # open, we need to close it if sqliteConnection: … -
Cannot create URL for blob! error in react native
I am trying to send a formdata consisting of image to backend server. However I am getting cannot create url for blob error This is my code for selecting file: const selectFile = async () => { // Opening Document Picker to select one file try { const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.allFiles], }); console.log('res simple', res); console.log('res : ' + JSON.stringify(res)); //fetch uri from the response const fileUri = res.uri; console.log('res : ' + fileUri); setSingleFile(res); // handleAcceptedFiles(res); } catch (err) { setSingleFile(null); if (DocumentPicker.isCancel(err)) { ToastAndroid.show('Canceled', ToastAndroid.SHORT); } else { alert('Unknown Error: ' + JSON.stringify(err)); throw err; } } }; And this for getting the blob: useEffect(() => { if (singleFile != null) { getData(); } }, [singleFile]); const getData = async () => { console.log('inside getData'); // console.log("singleFile",singleFile) console.log('singlefile', singleFile.uri); const response= await fetch(singleFile.uri) const blob = await response.blob() console.log('blob', typeof(blob)); const ur= URL.createObjectURL(blob) console.log('ur', ur); setBlob(blob); } -
Template error iterating through dict in jinja template
Here's my code {% for key, value in dictionary.items() %} <a class="dropdown-item" id={{key}}>{{value}}</a> {% endfor %} This is my dictionary dictionary ={"A":"A tab", "B":"B tab","C":"C tab"} I'm using python3 with jinja templates, here's the error I'm facing Django Version: 3.2.12 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '()' from 'dictionary.items()' -
Filling the database table at the expense of the other two Django
I have 3 models based on which I want to build my forms on the site: class Fields(models.Model): shortName = models.CharField(max_length=40) fullName = models.CharField(max_length=40) type = models.CharField(max_length=40) created_at = models.DateTimeField(default=datetime.utcnow()) modified_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Field' verbose_name_plural = 'Fields' class Forms(models.Model): name = models.CharField(max_length=40) created_at = models.DateTimeField(default=datetime.utcnow()) modified_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Form' verbose_name_plural = 'Forms' class FormFields(models.Model): formID = models.IntegerField() fieldID = models.IntegerField() class Meta: verbose_name = 'FormField' verbose_name_plural = 'FormFields' The editing of the form is planned only through the admin panel, in fields I will store all possible fields, and in forms the forms are available for use, in ormfields I want to attach fields to forms Is there any way for me when creating a record in the forms to immediately select the fields there and have it automatically added to the formfields? I tried to implement it through a filter-horizontal, but it didn't work, maybe I specified something wrong: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import * class FormsInline(admin.StackedInline): model = Forms filter_horizontal = ('Fields',) class CustomFields(UserAdmin): save_on_top = True list_display = ('shortName') inlines = [FormsInline] admin.site.register(Fields) admin.site.register(Forms, CustomFields) admin.site.register(FormFields) -
Creating a desktop app with plotly-python
I have been researching for a way to create a desktop app with plotly dynamic graphs. I have been thinking about these following options: using django, and creating the desktop app with electron.js creating an embebbed browser with PyQt5 and running the graphs from it I would like to know if one of these options is possible, or another way of running plotly in a desktop app. -
JQuery / AJAX - Async view - eventlisteners not responding and .remove() is not respecting the selection
it is my first time writing JQuery/AJAX and (silly me) I'm tryng to do something quite complex actually (or at least it is for me lol). Basically I am making an infinte carousel. I am sending the paginated data through a Django view, and I am using JQuery to load it asycronously (so to not refresh the page continuously and lose the previous content). This is the relevant code (I am not including any django related code, because everything there is working just fine, the issue is in the HTML/JS. However if you want to take a look at it, just let me know) HTML <main> <div id="outside-container"> <div id="inside-container" class="infinite-container"> {% for city in cities %} {% get_weather city.name 'metric' 'it' as weather_info %} <div class="items"> <div class="data-div"> <ul> <li><b>{% destructure weather_info 'location' 'city' %}</b> </li> <li class="weather">{% destructure weather_info 'weather' 'description' %}</li> <img src="{% destructure weather_info 'weather' 'icon' %}"> <li>{% destructure weather_info 'main' 'temperature' %}</li> <li>{% destructure weather_info 'location' 'time'%}</li> </ul> </div> <img loading="lazy" class="carousel-img" src="{{city.image.url}}"> </div> {% endfor %} </div> </div> <div id="directions"> <a id="right-button">Right</a> <a id="next-slide" href="?page=2">Next</a> </div> </main> CSS body { margin: 0; padding: 0; background: linear-gradient(-45deg, #4699f8, #fff2f7, #23a6d5, #1779e9); background-size: 400% 400%; animation: … -
Django give a Like Button using JS and DOM result ->404
I got problem with 'live' like unlike button in Django and JavaScript DOM after button is clicked I got an error POST http://127.0.0.1:8000/like/24 404 (Not Found) likePost @ javascripts.js:24 (anonymous) @ javascripts.js:40 javascripts.js:7 I don't know if the problem is in the 'await fetch' function or maybe I used the wrong class or id somewhere. Where to start? javascript.js const reloadPostHTML = async (postId) => { const homePageResponse = await fetch(window.location.href); const newHTML = await homePageResponse.text(); const newDocument = new DOMParser().parseFromString(newHTML, "text/html"); console.log(newDocument) const newPostElem = newDocument .querySelector(`[data-post-id='${postId}']`) .closest(".post"); const oldPostElem = document .querySelector(`[data-post-id='${postId}']`) .closest(".post"); oldPostElem.innerHTML = newPostElem.innerHTML; makeLikeButton(oldPostElem.querySelector(".like-button-wrapper")); }; const likePost = async (postId, csrfToken) => { await fetch(`/like/${postId}`, { method: 'POST', credentials: 'include', headers: { "X-CSRFToken": csrfToken } }); reloadPostHTML(postId); }; const makeLikeButton = (elem) => { elem.querySelector('button').addEventListener("click", (event) => { event.preventDefault(); const postId = elem.dataset.postId; const csrfToken = elem.dataset.csrfToken; likePost(postId, csrfToken); }); }; const makeLikeButtons = () => { for (let elem of document.getElementsByClassName("like-button-wrapper")) { makeLikeButton(elem); } }; makeLikeButtons(); urls.py path( 'article_detail/<int:pk>/', login_required( ArticleDetail.as_view(template_name = "web/article_detail_view.html") ), name='article_detail' ), path('like/<int:pk>', views.like, name='like'), -
'ConnectionHandler' object has no attribute cursor
I'm trying to execute a store procedure from django After searching I found using 'connection.cursor' can do that But djagno give me the error 'ConnectionHandler' object has no attribute cursor Can someone tell me why My code: def newproduct(request): if(request.method == 'POST'): data = NewProductForm(request.POST) if(data.is_valid()): p_data = data.cleaned_data with connections.cursor() as cursor: query = 'EXEC product.newproduct @product_id={0}, @product_name={1}, @product_desc={2}, @price={3},@amount={4}, @category_id={5}, @admin_id={6},@product_img={7}'.format(p_data['product_id'], p_data['product_name'], p_data['product_desc'], p_data['price'],p_data['amount'], p_data['category_id'], p_data['admin_id'], p_data['product_img'] cursor.execute(query) return HttpResponse('ok') else: return HttpResponse('Notvalid') I cannot find any solution about this problem -
Django sharing a lock between workers gunicorn
I am trying to loop inside a view function and I don’t want another worker to run the same loop. For which i am using Lock() but i am unable to achieve this. from multiprocessing import Lock import time lock = Lock() def loop_func(request): lock.acquire() # loop start for i in range(0,100): print ("did work ", i) time.sleep(1) finally: lock.release() can someone help me if there is a way where i can make the shared lock for all workers so that lock will wait till the other worker to finish and enter the loop -
Automate update of models based on conditions
I have a model class Session(models.Model): name = models.CharField(max_length=12) active = models.BooleanField(default=False) date = models.DateField() startTime = models.TimeField() The active field is set based on the date and start time. For eg - Suppose during the creation of an object, the date is for tomorrow, and let there be any time, I want to know the process and not the code on how and what to study to make this object active on that particular date and time. BY default the active field is False, or should I change the way I'm thinking to implement it? Thanks -
Postgres not using trgm index with Concat
I created a trigram index on full name where full_name = first_name || ' ' || last_name. CREATE INDEX "user_full_name_trgm" ON "user" using gin (upper(first_name || ' ' || last_name) gin_trgm_ops); I am using django queryset to filter over fullname. queryset = queryset.annotate(full_name=Concat("first_name", Value(" "), "last_name")) queryset = queryset.filter(full_name__istartswith=full_name) which generates WHERE clause as WHERE (UPPER(CONCAT("user"."first_name", CONCAT(' ', "user"."last_name"))::text) LIKE UPPER('mike%') The explain analyse shows that its not using user_full_name_trgm index. However when I use pipe to join the strings, the index is being used. WHERE (UPPER(first_name || ' ' || last_name) LIKE UPPER('mike%') How can I make django query to use the index? Can I modify query.annotate in such a way that it creates sql query without Concat? Or can I create index in such a way that it is used even with concat? -
call a property decorator through value in django module
I am having issue for the property decorator throug values from the models, The models is class Bills(models.Model): salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) @property def balance(self): return 0 if self.cash == True else self.totalAmount - self.advance i am working on the union method, to display credit bills and any paid transaction are there i am calling the method as bill_trans = Bills.objects.filter(purchasedPerson__id__contains = pk, cash = False).values( 'purchasedPerson__name', 'cash', 'totalAmount', 'remarks', 'created') in the place of total amount i needed balance property is that possible or there is there any other method to make union for the class MemberTrans(models.Model): purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) paid = models.BooleanField(default=False) amount = models.IntegerField() remarks = models.CharField(max_length = 200) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) mem_trans = MemberTrans.objects.filter(purchasedPerson__id__contains = pk).values( 'purchasedPerson__name', 'paid', 'amount', 'remarks', 'created' ) Bill_trans should union with mem_trans -
django.db.utils.operationalerror unable to open database file
I have been struggling finding a solution to my issue "django.db.utils.operationalerror unable to open database file ". I have changed permissions and set my path to an absolute one yet still have the same error. this is my settings.py file """ Django settings for bastionblog project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os from main import constants # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIRS = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = constants.SECRET_KEY # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['77.68.125.183'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bastionblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_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', ], }, }, ] WSGI_APPLICATION = 'bastionblog.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES … -
How to validate Child model (StackedInline) fields based on a value of Parent model's field in Django?
I have following structure. models.py class Parent(models.Model): PROVIDER1 = "Provider1" PROVIDER2= "Provider2" PROVIDERS= ( (PROVIDER1, "Test Provider One"), (PROVIDER2, "Test Provider Two"), ) provider = models.CharField( choices=PROVIDERS, max_length=255, default=PROVIDER1, ) # Few more parent fields will be here class Child(models.Model): some_field= models.CharField(max_length=255) # Few more fields will be here parent = models.ForeignKey( Parent, on_delete=models.CASCADE ) admin.py class ChildFormset(BaseInlineFormSet): def clean(self): super().clean() for form in self.forms: if not form.is_valid(): return # errors exist, so return class ChildInline(admin.StackedInline): model = Child formset = ChildFormset extra = 1 min_num = 1 validate_min = True max_num = 1 can_delete = False @admin.register(Parent) class Parent(admin.ModelAdmin): form = ParentForm inlines = [ ChildInline, ] forms.py class ParentForm(forms.ModelForm): class Meta: model = Parent fields = "__all__" def clean(self): cleaned_data = super().clean() # How to access Child model's fields values here to validate them? class Media: # Custom JS to show/hide provider specific fields/divs js = ("js/mycustom.js",) Requirement: When user choose Provider 1 in the Parent I would like to do following Display Child Model's fields (Inline). Validate Child model's fields on submit. I was able to use custom JavaScript for first requirement (hiding and showing fields). But for second requirement I am not able to get the … -
reasons for serializer not validating data DRF
I am sending the data through postman as follows my model.py is as follows def get_upload_path(instance, filename): model = instance._meta name = model.verbose_name_plural.replace(' ', '_') return f'{name}/images/{filename}' class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Photo(models.Model): name = models.CharField(max_length=255, null=True, blank=True) photo = models.ImageField(upload_to=get_upload_path, null=True, blank=True) default = models.BooleanField(default=False, null=True, blank=True) width = models.FloatField(default=100, null=True, blank=True) length = models.FloatField(default=100, null=True, blank=True) description = models.CharField(max_length=2000, null=True, blank=True) latitude = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) longitude = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) album = models.ForeignKey(ImageAlbum, related_name='album_data', on_delete=models.CASCADE, null=True, blank=True) my view.py is as follows class ImageAlbumListApiView(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser, ] def get(self, request): image_album = ImageAlbum.objects.all() serializer = ImageAlbumSerializer(image_album, many=True) return Response(serializer.data) def post(self, request): serializer = ImageAlbumSerializer(data=request.data) print(request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) My serializer.py is as follows class PhotoSerializer(serializers.ModelSerializer): class Meta: model = models.Photo fields = '__all__' class ImageAlbumSerializer(serializers.ModelSerializer): album_data = PhotoSerializer(many=True, read_only=True) file = serializers.ListField( child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False, write_only = True), write_only=True) class Meta: ###Test### model = models.ImageAlbum fields = ['id', 'album_data', 'file'] read_only_fields = ['id'] def create(self, validated_data): #album_data = validated_data.get('album_data') print(validated_data) uploaded_files = validated_data.get('file') #image_info = validated_data.pop('images') album = models.ImageAlbum.objects.create() … -
Django ORM for fetching latest record for specific ID
How do I write a django ORM to fetch the most recent records from the table for a specific id. Example: I have table(tr_data) data like: id trs(foreign key) status last_updated 1 301 3 2022-11-28 06:14:28 2 301 4 2022-11-28 06:15:28 3 302 3 2022-11-28 06:14:28 4 302 4 2022-11-28 06:15:28 5 302 2 2022-11-28 06:16:28 I want to have a queryset values that gives me trs id with its latest status.I have tried with aggragate and MAX but not getting the desired result. Expecting ouput as : [{"trs":301, "status":4},"trs":302,"status":2}] -
How to get an records with each month in a date range of two fields?
I have a study year model which has a start and end date. class StudyYear(models.Model): date_begin = models.DateField(...) date_end = models.DateField(...) I need a Queryset in which there are records for each study year with a month in its date range (start_date:end_date) Example: For the study year (09/01/2022:01/02/2023), qs should contain records: ... (code=9_2022, name='September 2022'), (code=10_2022, name='November 2022'), (code=11_2022, name='October 2022'), (code=12_2022, name='December 2022'), (code=1_2023, name='January 2023'), (code=2_2023, name='February 2023'), ... Honestly, I have no idea how to solve this problem, I really hope for your help! -
how to compare dictionaries and color the different key, value
I have a django application. And I have two texboxes where data is coming from two different functions. So the data is displayed in the texboxes. But the key,value has to be marked red when there is a difference in the two dictionaries. So in this example it is ananas that has the difference. So I have the TestFile with the data: class TestFile: def __init__(self) -> None: pass def data_compare2(self): fruits2 = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 30, } set2 = set([(k, v) for k, v in fruits2.items()]) return set2 def data_compare(self): fruits = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 24, } set1 = set([(k, v) for k, v in fruits.items()]) return set1 def compare_dic(self): set1 = self.data_compare() set2 = self.data_compare2() diff_set = list(set1 - set2) + list(set2 - set1) return diff_set the views.py: from .test_file import TestFile def data_compare(request): test_file = TestFile() content_excel = "" content = "" content = test_file.data_compare() content_excel = test_file.data_compare2() diff_set =test_file.compare_dic() context = {"content": content, "content_excel": content_excel, "diff_set": diff_set} return render(request, "main/data_compare.html", context) and the template: {% extends 'base.html' %} {% load static %} {% block content %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div … -
Django Rest Framework's API for Razorpay Callback couldn't be authenticated
@api_view(['POST']) @permission_classes([]) #@permission_classes([IsNormalUser])# cant use, JWT misses @authentication_classes([]) def verifyRazorPay(request): if success: return Response(success) else: return Response(failure) As you can see in the code this is a callback API for Razorpay. But I couldn't make this secure by any of the permission_classes, authentication_classes because Razorpay doesnt use any of JWT tokens for headers that I use in my website application. How to secure this in any manner by authorizing .. that anonymous users cant throttle it. -
How to save a resized image Django?
I try to save both, an original and a resized image and can't understand on what step Django will understand from WHICH FIELD it will take the image to resize and then save. MODELS.PY: from django.db import models from django_resized import ResizedImageField class Post(models.Model): thumbnail = models.ImageField(upload_to ='uploads/posts/large/') thumbnail_small = ResizedImageField(size=[100, 100], upload_to='uploads/posts/small/') FORMS.PY class PostForm(forms.ModelForm): class Meta: model = Post fields = ['thumbnail','thumbnail_small'] HTML: <form method = "POST" action = "{% url 'adminpanel' %}" enctype = "multipart/form-data"> {% csrf_token %} <input type = "file" id = "file" name = "thumbnail" accept = "image/png, image/jpeg"> <button type = "submit" class = "btn" name = "apost">Add Post</button> </form> So, the question is, where will Django understand that it has to save image directly from the <input name = "thumbnail"> directly to thumbnail = models.ImageField(upload_to ='uploads/posts/large/') and also to thumbnail_small = ResizedImageField(size=[100, 100], upload_to='uploads/posts/small/')? Thanks in advance. -
django serializer error: images_data = self.context['request'].FILES KeyError: 'request'
models.py ` # from django.db import models from user.models import User from chat.models import TradeChatRoom, AuctionChatRoom class Goods(models.Model): class Meta: db_table = 'Goods' ordering = ['-created_at'] # 일단 추가해뒀습니다 seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sell_goods') buyer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='buy_goods', null=True) trade_room = models.ForeignKey(TradeChatRoom, on_delete=models.CASCADE) auction_room = models.ForeignKey(AuctionChatRoom, on_delete=models.CASCADE) title = models.CharField(max_length=256) content = models.TextField() category = models.CharField(max_length=32) status = models.BooleanField(null=True) predict_price = models.IntegerField() start_price = models.IntegerField() high_price = models.IntegerField(null=True) start_date = models.DateField(null = True) start_time = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User, related_name='like_goods', null=True) class GoodsImage(models.Model): class Meta: db_table = "GoodsImage" goods = models.ForeignKey(Goods, on_delete=models.CASCADE) image = models.ImageField(upload_to='goods/') ` serializer.py from rest_framework import serializers from .models import Goods,GoodsImage class GoodImageSerializer(serializers.ModelSerializer): image = serializers.ImageField(use_url=True) def get_image(self, obj): image = obj.goods_set.all() return GoodsPostSerializer(instance=image, many = True, context = self.context) class Meta: model = GoodsImage field =('image',) class GoodsPostSerializer(serializers.ModelSerializer): image = GoodImageSerializer(many=True, read_only = True) class Meta: model = Goods fields = ( 'seller', 'buyer','auction_room','title','content', 'category','status','predict_price','start_price','high_price', 'trade_room','start_date','start_time','created_at','like','image', ) read_only_fields = ("seller",) def create(self, validated_data): goods = Goods.objects.create(**validated_data) images_data = self.context['request'].FILES for image_date in images_data.getlist('image'): GoodsImage.objects.create(goods = goods, image = image_date) return goods error images_data = self.context['request'].FILES KeyError: 'request' I want to save multiple images, but I keep getting an error. I don't … -
What is right order for defining django view decorators
I want to set more than one decorator for my django function view. The problem is that I can't figure out how should be the order of decorators. For example this is the view I have: @permission_classes([IsAuthenticated]) @api_view(["POST"]) def logout(request): pass In this case, first decorator never applies! neither when request is POST nor when it's GET! When I change the order, to this: @api_view(["POST"]) @permission_classes([IsAuthenticated]) def logout(request): pass the last decorator applies before the first one, which is not the order that I want. I want the decorator @api_view(["POST"]) to be applied first, and then @permission_classes([IsAuthenticated]). How should I do that? -
Mysterious Issues uploading images Django
I hope someone can help me out here, something strange and mysterious is happening with my code. I have a project which was working normally, but suddenly the images stopped to get uplodad. I was working on an update method in the viewset when I realized that. even more awkward is that I have two apps on my application one uploads the images normally and other doesn't. I have tried to change the upload_to direction on the field which is not been uploaded and noticed that the new direction hasn't been applied, the destination folder is saved in the database with a previous direction (even though the picture never gets uploaded) below you have the codes: first the result of an update: notice the address { "profile": 4, "card": "teste2", "points": 0, "created": "2022-11-29T16:05:33.502027Z", "updated": "2022-11-30T10:26:15.063888Z", "code": "673476", **"image": "http://127.0.0.1:7000/medias/media/app_user/img_DENklQy.jpg"** } now the models, notice the upload_to: class MyCards(models.Model): profile = models.ForeignKey(AppUserProfile, on_delete=models.CASCADE) card = models.ForeignKey(Cards, on_delete=models.CASCADE) points = models.IntegerField(default=0) **image = models.ImageField(upload_to='mycards', blank=True)** created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) code = models.CharField(max_length=6, blank=True, null=True) my settings: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = '/medias/' MEDIA_ROOT = os.path.join(BASE_DIR, 'medias' ) viewset, I have removed the update overriding method, to check if was …