Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect User to their corresponding View and Templates in Django
I have 2 different user types at the moment. After a successful login, I want the user to be redirected to its specific dashboard. Depending on the user, it is possible to load in a different template in a generic view Class: if request.user.user_type == 1: # load template A if request.user.user_type == 2: # load template B But I want to have two separate View Classes for each Type. How can I achieve this? -
How to render student tuition fees payment records on template in django
I have some models for student fees payments and would like to render the following based on the models: Classes, No of students in each class, Amount Payable in each class, & Total amount paid in each class My models are as below: for Classroom setup class ClassArmSetup(models.Model): SECTION = ( ('Primary', 'Primary'), ('Secondary', 'Secondary'), ('Creche', 'Creche'), ('Nursery', 'Nursery'), ) id = models.AutoField(primary_key='True') name = models.CharField(max_length=255, unique=True) short_name = models.CharField( 'Classroom Short Form', max_length=20, blank=True ) academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE, null=True) term = models.ForeignKey(TermSetup, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) objects = models.Manager() def classroom_code(self): if not self.code: return "" return self.code class StudentClassRegistration(models.Model): STATUS = [ ('Active', 'Active'), ('Withdrawn', 'Withdrawn'), ('Completed', 'Completed'), ] chosen_class = models.ForeignKey( ClassArmSetup, related_name='admission_students', on_delete=models.CASCADE, blank=True, null=True ) admitted = models.BooleanField(default=False) admission_date = models.DateField(blank=True, null=True) migration_status = models.CharField( max_length=255, blank=True, null=True, default='Active' ) status = models.TextField(choices=STATUS, verbose_name='Status', null=True) rejected = models.BooleanField(default=False) assigned_as_student = models.BooleanField(default=False) academic_year =models.ForeignKey(AcademicYear, on_delete=models.CASCADE, null=True, verbose_name='Session') term =models.ForeignKey(TermSetup, on_delete=models.CASCADE, null=True, verbose_name='Term') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.lastname) + ' ' + str(self.firstname) + ' ' + str(self.othername) class Meta: ordering = ['chosen_class'] class TuitionFeesSetup(models.Model): year= models.ForeignKey(AcademicYear, on_delete=models.CASCADE, null=True, verbose_name="Session") term= models.ForeignKey(TermSetup, on_delete=models.CASCADE, null=True, verbose_name="Term") … -
How can i show multiple tag from tag model in django
I'm beginner in Django/Python and I need to create a multiple select form. I know it's easy but I can't find any example. i use django-taggit.i want to select multiple tag in tag form with search engine . here is my forms.py class QuestionForm(forms.ModelForm): test = Tag.objects.order_by('name') for tag in test: print(tag) tags = forms.ModelMultipleChoiceField(label='Tags', queryset=Tag.objects.order_by('name'),widget=forms.SelectMultiple) class Meta: model = Question fields = ['title', 'content','anonymous',"tags"] widgets = { 'title' : forms.TextInput(attrs={'class':'form-control form-control form-control-lg '}), 'content' : forms.Textarea(attrs={'class':'form-control'}), # 'tags' : forms.Textarea(attrs={'class':'form-control'}), } form.html {{form.tags}} i want this -
Django post_save signal not working properly
In my models.py file, I have a class named OrderPayment, now whenever I create a new object of OrderPayment, I want to also create a Transaction object. Am trying to do this with post_save signal but it not working. Below is how the code looks @receiver(post_save, sender=OrderPayment) def orderpayment_setup(sender, instance, **kwargs): print(instance.order.dispatch_rider.company) print(instance) wt = Transaction.objects.create( wallet=Wallet.objects.get(user=instance.order.dispatch_rider.company), amount=instance.amount, description="Dispatch Order", status='success', transaction_type='deposit' ) print(wt) The orderpayment_setup function gets triggered but the Transaction object is not created. I also sees the first two print statement but I don't see the last one. I don't know what I'm not doing right -
How to load json, pickle and h5 files into views.py file in Python Django?
I am trying to display a chatbot that I created on a django site. So I need to load some training data (json, pickle and h5 files) into views.py file. But when I run the server it says: FileNotFoundError: [Errno 2] No such file or directory: 'mysite/polls/intents.json' even though views.py and intents.json are in the same folder. Do you have any suggestions? Here's the code from views.py: from django.shortcuts import render from django.http import HttpResponse import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() import pickle import numpy as np from keras.models import load_model import json import random intents = json.loads(open('mysite/polls/intents.json').read()) model = load_model('mysite/polls/chatbot_model.h5') words = pickle.load(open('mysite/polls/words.pkl','rb')) classes = pickle.load(open('mysite/polls/classes.pkl','rb')) # Create your views here. def index(request): def clean_up_sentence(sentence): sentence_words = nltk.word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] return sentence_words # return bag of words array: 0 or 1 for each word in the bag that exists in the sentence def bow(sentence, words, show_details=True): # tokenize the pattern sentence_words = clean_up_sentence(sentence) # bag of words - matrix of N words, vocabulary matrix bag = [0]*len(words) for s in sentence_words: for i,w in enumerate(words): if w == s: # assign 1 if current word is in the vocabulary position bag[i] … -
I can't add data to the database using a Django form
If I leave everything as it is, then an error pops up when submitting the form "Select a valid choice. That choice is not one of the available choices." And, for example, if in forms.py I change Product.objects.values_list('product_name') to a class with one field, for example, Category.objects.all(), the form is submitted without errors But I need exactly the first option, where I select a specific class field (product_name), so that there are the necessary options in the form in the select... Who knows how to solve this problem? models.py: class Account(models.Model): uploader_mail = models.EmailField(max_length=254) body = models.CharField(max_length=4096) product = models.ForeignKey('Product', on_delete=models.PROTECT) class Product(models.Model): product_name = models.CharField(max_length=400) description = models.CharField(max_length=4096) price = models.DecimalField(max_digits=8, decimal_places=2) geo = models.CharField(max_length=2) product_logo = models.ImageField(upload_to='img/logos', blank=True) category = models.ForeignKey('Category', on_delete=models.PROTECT) def __str__(self): return self.product_name, self.description, self.geo, class Category(models.Model): category = models.CharField(max_length=100) def __str__(self): return self.category forms.py: class AddForm(forms.Form): uploader_mail = forms.EmailField( label='Owner mail', initial='test@test.test', widget=forms.EmailInput(attrs={'class': 'form-control'})) body = forms.CharField( label='Data line by line', widget=forms.Textarea(attrs={'class': 'form-control','wrap': "off", })) category = forms.ModelChoiceField( queryset=Product.objects.values_list('product_name', flat=True), label='Category', empty_label=None, widget=forms.Select(attrs={'class': 'form-select'})) views.py: def edit(request): if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): print(form.cleaned_data) else: form = AddForm() editable = {'form': form, } return render(request, 'goods_list/edit.html', editable) -
ajax not work when click open in new window after right click in django template
i created a link with ajax this is a html coded: <a id="post_click" href="{{ post.online_url}}" rel="nofollow"> <button class="w-100 " type="button" name="button"> <span class="">link</span> </button> </a> and this is ajax : $(function () { $('#post_click').on('click', function () { var Status = $(this).val(); var id = {{post.id}} $.ajax({ url: "/post-click/" + id, data: { }, dataType : 'json' }); }); }); if i push left click ajax work fine in sever side, but when i push left right click and choose open in new window ajax doesnt work -
Django Problem : I want to see reverse order in django admin many to many field
class Question(models.Model): id = models.AutoField question = models.CharField(max_length=100) answer = models.CharField(max_length=100) class TestSeries(models.Model): id = models.AutoField quiz_name = models.CharField(max_length=100) all_question=models.ManyToManyField(MyQuestion) This is my model.py code when i open my admin panel on test series previous added are shown in order : Oldest first i want to see that in newest first manner . please tell me , how can i do that -
Does anyone know how to deploy Redis as cache along Postgres and Digital Ocean App for Django app?
I deployed Django's app with Digital Ocean App service. This is easy and quick without me having to deal with setting up a Ubuntu Droplet or anything like that for Django. I also got Postgres as the main database for the Django app. The problem is when I also set up Redis Managed Database as a cache server for my app, using VPC network connection such as rediss://private-location-on-digital-ocean:port# (also added the Django App and my own IP address as trusted source) - (also installed django-redis using pip) - to my chagrin I either got Internal Server Error or some vague error said that I have to check the log. By the way I did update the requirements.txt to make sure all packages were installed for Redis to run properly with Django app. Also, I set up the Redis as the CACHE backend in settings.py. The only thing I see is that Postgres is being listed as a component for my Django app and Redis DB is not but it's using the same VPC that my Django app is using. What could be the problem that I missed in order for me to get Redis to act as a cache server … -
What is better ways to store id after successful login?
For my project, I am using Angular + Django Rest Framework. I am storing id in local storage (using Angular). But I want to learn other ways to do it. Can we use (In Django) Session Cache How? -
How to detect enters from text and display on html page using html javascript
I have below data from backend(django) "Innovator in Analytical Process & Environmental Instrumentation\r\nT&C:\r\nPayment: 100% advance against PI prior to Dispatch.\r\nPrices: Ex-works Mumbai.\r\nInstl. and Comm. - Inclusive for Mumbai region. For outstation, Travel, Food\r\nand Lodging charges extra.\r\nFreight: In your scope.\r\nGST: Extra @ 18%.\r\nDelivery: 2-3 weeks after receipt of advance payment.\r\nWarranty: 1 Year from the date of installation.\r\nCustomer's scope:\r\n1. All kinds of Civil/Electrical/Plumbing works.\r\n2. Construction or Modification of the Line.\r\n3. Tubing for Sample inlet and outlet with tapping on the line with PU push\r\nconnector.\r\n4. Electrical, LAN and signal cables - Supply and laying.\r\n5. Online or Offline UPS - 1 KVA.\r\n6. SIM/LAN/Wifi/Dongle for connectivity.\r\n7. DM Water and Sulphuric Acid.\r\n8. Mounting of Flow Meter or 3-way valve.\r\n9. Lab Test Reports." Its have enters in the text I wish to show them on frontend in my this code : my text is getting from {{response.remarks}} <ul class="list list-unstyled mb-0 text-left"> <li><h6 class="my-1">Message Displayed </h6></li> <li>{{response.remarks}}</li> </ul> But its showing me like this But want them with enters how can I do this -
Access Postgres generate_series function via Django model syntax
I need to use Django Models to create roughly the following SQL: SELECT series AT TIME ZONE 'utc' AS forecast_hour, app_forecasts.inventory AS inventory FROM generate_series(DATE_TRUNC('hour', TIMESTAMP '2022-05-01 04:00:00+00:00'), DATE_TRUNC('hour', TIMESTAMP '2022-09-03 03:00:00+00:00'), '1 hour'::interval) series LEFT JOIN app_forecasts ON series = DATE_TRUNC('hour', app_forecasts.forecast_at) AT TIME ZONE 'utc' It would look something like: Forecast.objects.annotate(dates=Func(..., ..., Value('1 day'), function='generate_series')) -
How do i get a success message for a model object in django
I'm trying to create an authentication in my project after signing in. I created my models. I want the user to get an error message if he doesn't get the correct pin in the models and successful if he puts in the right pin. I only get the error message but i don't get the success message class Data(models.Model): name = models.CharField(max_length=100) body = models.CharField(max_length=1000000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) other_name = models.CharField(max_length=200) email = models.EmailField() profile_image = models.ImageField(blank=True) city = models.CharField(max_length= 100) title = models.TextField(null=True, blank=True) middlename = models.TextField(null=True, blank=True) adreess = models.TextField(null=True, blank=True) country = models.TextField(null=True, blank=True) state = models.TextField(blank=True, verbose_name="Biography (Age, Language, Location...)") pin = models.IntegerField() available = models.TextField(null=True, blank=True) checkings = models.TextField(null=True, blank=True) savings = models.TextField(null=True, blank=True) phone_number = models.TextField(null=True, blank=True) first_his = models.TextField(null=True, blank=True) second_history = models.TextField(null=True, blank=True) third_history = models.TextField(null=True, blank=True) last_history = models.TextField(null=True, blank=True) newstate = models.TextField(null=True, blank=True) def __str__(self): return self.first_name This is my view def checkview(request): pin = request.POST['pin'] if Data.objects.filter(name=pin).exists(): messages.success(request, "You have registered successfully") else: messages.error(request, 'Account Suspended, Your Request To Transfer funds Has Been Declined. Contact Support for Help') return redirect('account') This is my Htm file <div class="pagetitle"> <h1>Pin Code Required to Complete Transfer Request</h1> <style> h8{ … -
isort is not sorting as expected
This is my .isort.cfg file: [settings] profile = black group_by_package = true default_section = THIRDPARTY known_first_party = project known_django = django sections = FUTURE,STDLIB,DJANGO,THIRDPARTY,FIRSTPARTY,LOCALFOLDER and this is the import section of my views.py: from random import randint from django.contrib.auth.hashers import check_password, make_password from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Customer from .serializers import GetCustomerSerializer So why isort doesn't allow me to have an empty line between django.contrib.auth.hashers and rest_framework imports? -
djangorestframework does not work when django channel is applied
I am developing a chatting app that allows social login. While developing all restapi functions, including social login functions, and developing chat customers using channel libraries, there was a problem with social login. This code is chatcustomer using websocketcunsumer. import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import * class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name .... this is setting for channel INSTALLED_APPS = [ 'channels', ] ASGI_APPLICATION = 'project.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } routing.py in project root from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() application = get_default_application() routing.py in chatapp from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] this is social login views.py @api_view(['POST']) def authenticate_kakao(request): access_token = request.data["access_token"] code =request.data['code'] """ Email Request """ print("process1") profile_request = requests.get( "https://kapi.kakao.com/v2/user/me", headers={"Authorization": f"Bearer {access_token}"}) print("process2") profile_json = profile_request.json() kakao_account = profile_json.get('kakao_account') email = kakao_account.get('email') profile … -
Django NotEqual custom lookup in exclude method
I registered a custom lookup base on this answer and official documentation. # core/custom_lookup.py from django.db.models import Lookup class NotEqual(Lookup): """Missing != operator.""" lookup_name = 'ne' def as_sql(self, *args): lhs, lhs_params = self.process_lhs(*args) rhs, rhs_params = self.process_rhs(*args) return '{} <> {}'.format(lhs, rhs), lhs_params + rhs_params I registered the custom lookup in my app config. # core/apps.py from django.apps import AppConfig from django.db.models import Field from .custom_lookup import NotEqual class CoreConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'core' def ready(self): Field.register_lookup(NotEqual) Then i use it in the exclude method this way. Customer.objects.all().filter(filter).exclude(private=True, user__ne=info.context.user).order_by('-created') The idea here is to get all the customers where user is info.context.user (with private is False or True) OR user is NOT info.context.user but private is False but exclude customers where user is NOT info.context.user AND private is True But whenever I play the query the error below is thrown Related Field got invalid lookup: ne Am I missing something on the registration of the lookup? -
how can i use scrapy with django?
how can I use Scrapy to grab data from other websites with Django as a backend of my website and react for the front end? I've tried before with Bs4 but it wasn't enough, I think scrapy is better with scrapping multiple URLs. -
TypeError: View.__init__() takes 1 positional argument but 3 were given
when a user is registered he should be directly logged in instead of showing the login page views.py thanks in advance from django.contrib.auth import login from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView,FormView class register(FormView): model=task form_class=UserCreationForm template_name='register.html' success_url=reverse_lazy('all') def form_valid(self, form): user=form.save() if user is not None: login(self.request,user) return super(register,self).form_valid(form) urls.py from.views import display_all,display_detail,insert_detail,update_detail,delete_task,login,register urlpatterns = [ path('',display_all.as_view(),name='all'), path('view_detail/<int:pk>',display_detail.as_view(),name='detail'), path('insert_detail/',insert_detail.as_view(),name='insert'), path('update_detail/<int:pk>',update_detail.as_view(),name='update'), path('delete_detail/<int:pk>',delete_task.as_view(),name='delete'), path('login/',login.as_view(),name='login'), path('logout/',LogoutView.as_view(next_page='all'),name='logout'), path('register/',register.as_view(),name='register') register.html <body> <form action="" method="post"> {{form.as_p}} {% csrf_token %} <input type="submit" value="signup"> </form> -
Django - Not Found The requested resource was not found on this server on Production
I was trying to deploy my Django project on Render . Everything works fine except for the media files. I can't figure out the issue here. I have added the followings into my settings.py: DEBUG=False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', ] 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', "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [ BASE_DIR / "static" ] MEDIA_URL = '/contents/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/contents/') STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage" urls.py from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I have created a Post (using models) before deploying. It had an image located a ./static/contents/Screenshot_334.png After deploying this image is accessible at https://someusername.onrender.com/static/contents/Screenshot_334.png . But if I create a new post from the deployed site I get a 404 error. The site doesn't cause any issue while its in the development mode. Here's a portion of LOGS from Render: https://someusername.onrender.com/static/contents/Screenshot_334.png (created while development) is accessible but https://someusername.onrender.com/static/contents/Screenshot_1.png (created post-production) is inaccessible. Also, static files (css, js) working fine. I also tried switching MEDIA_URL and MEDIA_ROOT to 'contents', 'contents/', 'static/contents/' and all the possible variations. -
How to get all data associate with serializers.PrimaryKeyRelatedField
I am trying to get all the data associated with this interest_category serializer. This is what I am currently getting: { "project_title": "Dogs", "project_description": "and cats", "interest_category": [ 4, 7 ], "created_by": 1, "created_at": "2022-09-17T04:31:40.884357Z", "updated_at": "2022-09-17T04:31:40.884357Z" }, What I am trying to get: { "project_title": "Dogs", "project_description": "and cats", "interest_category": [ { "id": 4, "interest_name": "Test" }, { "id": 7, "interest_name": "Business" } ], "created_by": 1, "created_at": "2022-09-17T04:31:40.884357Z", "updated_at": "2022-09-17T04:31:40.884357Z" }, The issue I am having is if I use the below code, I cannot get the interest_category "interest_name" and only have the IDs displayed in a GET request: class InterestSerializer(serializers.ModelSerializer): interest_name = serializers.CharField() class Meta: model = Interests fields = ('id', 'interest_name') class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.PrimaryKeyRelatedField( many=True, read_only=True ) class Meta: model = Project fields = [ 'project_title', 'project_description', 'interest_category', 'created_by', 'created_at', 'updated_at', ] def create(self, validated_data): project_category = validated_data.pop("interest_category", None) project_create = Project.objects.create(**validated_data) if project_category: project_create.interest_category.set(project_category) return project_create I have tried using this to GET the data and I can, however when I use this code, I cannot write and set the interest_category, it will just be blank: class InterestSerializer(serializers.ModelSerializer): interest_name = serializers.CharField() class Meta: model = Interests fields = ('id', 'interest_name') class ProjectsSerializer(serializers.ModelSerializer): interest_category = … -
record does not exist or has been deleted.\\n(record: account.move.line(5398,), user: 7) in odoo while updating
I'm getting record does not exist or has been deleted.\n(record: account.move.line(5398,), user: 7) error while updating data to odoo. Following is my code can anyone help to solve this problem. import xmlrpc.client endpoint_url = "/api/account.move/" obj = get_object_or_404(OrderItem, order__id=order_id) invoice_date = obj.order.created_on name = obj.product.varient_name price = obj.total quantity = obj.quantity payment_source = obj.order.payment_method payment_reference = obj.order.order_number common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url)) uid = common.authenticate(db, username, password, {}) models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url)) ids = models.execute_kw(db, uid, password, 'account.move', 'search_read', [[['source_document', '=', payment_reference]]], {'fields': ['partner_id', 'id']}) invoice_id = ids[0]['id'] partner_id_ = ids[0]['partner_id'][0] headers = { "access-token":tokens, "Content-type":"application/jsonp", "Cookie":session_id } api_invoice_line_id = [(1, invoice_id,{'name':name, 'price_unit':price, 'quantity':quantity})] data = { "partner_id":partner_id_, "invoice_date":str(invoice_date), "move_type":"out_invoice", "__api__invoice_line_ids":str(api_invoice_line_id), "payment_source":payment_source, "source_document": payment_reference, "rider":rider_name, "ref":"" } datas_ = json.dumps(data, indent=4) req = requests.put(url+endpoint_url+str(invoice_id), headers=headers, data=datas_) if req.status_code == 200: status = "Update Successful" else: status = str(req.text) return status -
In django function base view how to inherit some opertion that are used in all views functions?
I am using django function base views these operation needed in all views. resourceList=resource.objects.all() params={ 'resourcelist':resourceList } return render(request, html file, params) One solution is that I will type in all my views function. Anyone can help me with a suitable answer for this? -
Django custom save model creating duplicate files
I'm trying to get image uploads to also save as thumbnails, which works. The problem was when I did an update the custom method saved the thumbnail again in a different directory. so I modified my save function to look like this. models.py class Photo(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='photos/%Y%m') thumbnail = models.ImageField(blank=True, upload_to='thumbnails/%Y%m') submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) year = models.ForeignKey(Year, blank=True, on_delete=models.CASCADE) people = TaggableManager(through=TaggedPeople, verbose_name='People') tags = TaggableManager(through=TaggedGeneric, verbose_name='Tags') def save(self, *args, **kwargs): try: this = Photo.objects.get(id=self.id) if this.thumbnail != self.thumbnail: this.thumbnail.delete(save=False) except: if self.thumbnail: img = Image.open(BytesIO(self.thumbnail.read())) if hasattr(img, '_getexif'): exif = img._getexif() if exif: for tag, label in ExifTags.TAGS.items(): if label == 'Orientation': orientation = tag break if orientation in exif: if exif[orientation] == 3: img = img.rotate(180, expand=True) elif exif[orientation] == 6: img = img.rotate(270, expand=True) elif exif[orientation] == 8: img = img.rotate(90, expand=True) img.thumbnail((360,360), Image.ANTIALIAS) output = BytesIO() img.save(output, format='JPEG', quality=95) output.seek(0) self.thumbnail = File(output, self.thumbnail.name) return super().save(*args, **kwargs) def __str__(self): return self.title and my views class PhotoCreateView(LoginRequiredMixin, CreateView): model = Photo fields = ['image', 'title', 'description', 'year', 'people', 'tags'] template_name = 'photoapp/create.html' success_url = '/photo/?page=1' extra_context = {'tags':GenericTag.objects.all().order_by('name'),'people':PeopleTag.objects.all().order_by('name'),} def form_valid(self, form): form.instance.thumbnail = self.request.FILES['image'] form.instance.submitter = … -
[{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]}
Trying to post to my DRF API. But I am getting the following error. I am using Vue.js as my front end. I am able to retrieve the data with no issues. I just cannot write or create a new entry. [{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]} Models: class Interests(models.Model): interest_name = models.CharField(max_length=50) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Category name:" + "\n" + self.interest_name + "\n" + "|" + "\n" + "Created By:" + "\n" + self.created_by.username class Project(models.Model): project_title = models.CharField(max_length=255) project_description = models.TextField(max_length=1500) interest_category = models.ManyToManyField(Interests) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Project name:" + "\n" + self.project_title + "\n" + "|" + "\n" + "Created By:" + "\n" + self.created_by.username Views: class ProjectView(generics.RetrieveAPIView): queryset = Project.objects.order_by('-created_at') def get(self, request): queryset = self.get_queryset() serializer = ProjectsSerializer(queryset, many=True) return Response(serializer.data) def post(self, request): if request.method == 'POST': serializer = ProjectsSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) class ProjectCategory(generics.RetrieveAPIView): queryset = Interests.objects.all() def get(self, request): queryset = self.get_queryset() serializer = InterestSerializer(queryset, many=True) return Response(serializer.data) Serializer: class InterestSerializer(serializers.ModelSerializer): class Meta: model = Interests fields = ('id', 'interest_name') class ProjectsSerializer(serializers.ModelSerializer): interest_category = … -
Why do you need to use this "f" with dynamic http responses in django?
For example: from django.shortcuts import render from django.http import HttpResponse def view(request, something): return HttpResponse(f' {something} ') I've found many examples like this one, but no explanation of what the 'f' means in 'HttpResponse(f' {something} '), or why is it necessary. It's not used when you don't utilize a captured value from the url.