Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using file.js in the script of an external html document, which is not on the server
I would like to use a file.js document from my Django-Server as a script of an external html-document, which does not belong to my server. That´s why I tried to implement the file.js as an path and use the link of this path for my html document as a script, but it did not work because the script could not be gotten from the html document. Does anyone has an advice for me what I did wrong? file.js: var test = {“variable“:“test“} test.html: <script href=“https://url_of_my_server/file.js“> </script> -
Celery task (.delay()) causes Django to freeze if I'm using Gunicorn or uWsgi
If I'm using celery with Django (by calling .delay()) while using Gunicorn or uWsgi it causes it to freeze and eventually timeout. I'm guessing it gets stuck trying to send task to broker. This is happening on both developer server and production server, where both are running Ubuntu 20.04. Using built in developer server using python3 manage.py runserver works without any issues. And removing the .delay() also makes it work automatically. Example task: @shared_task def SayHello(): print('Hello!') Celery config in settings.py: CELERY_BROKER_URL = 'redis://:password@ip:6379' CELERY_RESULT_BACKEND = 'redis://:password@ip:6379' CELERY_ACCEPT_CONTENt = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER ='json' init.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py (in project folder with settings.py): import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings') app = Celery('djangoProject') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all … -
I got this Django error MultiValueDictKeyError while clicking on "view" button
I need help I got an error in my project when I click on the "view button" to open the post i get this error : MultiValueDictKeyError at /Post/21 'bid' Request Method: GET Request URL: http://127.0.0.1:8000/Post/21 Django Version: 3.2.8 Exception Type: MultiValueDictKeyError Exception Value: 'bid' I think there is something wrong with my "viewList def" because of the bid: please take a look on my code view.py (form class) class BidForm(ModelForm): class Meta: model = Bid fields = ['bid'] def viewList(request, id): # check for the watchlist listing = Post.objects.get(id=id) user = User.objects.get(username=request.user) if listing.watchers.filter(id=request.user.id).exists(): is_watched = True else: is_watched = False if not listing.activate: if request.POST.get('button') == "Close": listing.activate = True listing.save() else: price = float(request.POST['bid']) bids = listing.bids.all() if user.username != listing.creator.username: if price <= listing.startBid: return render(request, 'auctions/item.html', { "listing": listing, 'form': BidForm(), "message": "Error! Your bid must be largest than the current bid!", }) form = BidForm(request.POST) if form.is_valid(): bid = form.save(commit=False) bid.user = user bid.save() listing.bids.add(bid) listing.bid = price listing.save() else: return render(request, 'auctions/item.html', { "form": BidForm() }) return HttpResponseRedirect(reverse('viewList', args=(listing.id,))) context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'is_watched': is_watched, 'form': BidForm() } return render(request, 'auctions/item.html', context) model.py class Bid(models.Model): user = models.ForeignKey(User, … -
my form.cleaned_data['object'] is printing None
my Django form ''' class servicesform(forms.ModelForm): class Meta: model = services fields = ['supplies', 'airport', 'goods', 'package', 'shipping', 'food', 'drunk', 'animals', 'additional_service', 'price'] widgets = {'supplies': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexCheckDefault'} 'airport': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexCheckDefaultt'} 'goods': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}), 'package': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}) 'shipping': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'} 'food': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}), 'drunk': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}), 'animals': forms.NumberInput(attrs={'class': 'addservices form-control', 'placeholder': '$'}) 'additional_service': forms.TextInput( attrs={'class': 'addservices form-control', 'placeholder': 'additional'}), 'price': forms.NumberInput( attrs={'class': 'addservices form-control timepicker', 'placeholder': '$'})} my views.py file ''' def Signup2(request): form = Registerform2() service_form = servicesform() if request.method == "POST": service_form = servicesform(request.POST) form = Registerform2(request.POST) if form.is_valid(): data = form.save(commit=False) print(data, request.user.id, 'data') data.user = request.user data.save() else: print(form.errors) if service_form.is_valid(): print(service_form) price = service_form.cleaned_data['price'] add_ser = service_form.cleaned_data['additional_service'] print(price, add_ser) services.objects.create(user=request.user, additional_service=add_ser, price=price) service_data = service_form.save(commit=False) service_data.user = request.user service_data.save() else: print(service_form.errors) return redirect('/') ''' here is my models.py file ''' class services(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) supplies = models.BooleanField(default=False) airport = models.BooleanField(default=False) goods = models.IntegerField(null=True, blank=True) package = models.IntegerField(null=True, blank=True) shipping = models.IntegerField(null=True, blank=True) food = models.IntegerField(null=True, blank=True) drunk = models.IntegerField(null=True, blank=True) animals = models.IntegerField(null=True, blank=True) additional_service = models.CharField(max_length=100, null=True, blank=True) price = models.IntegerField(null=True, blank=True) ''' … -
how to complete some part of form in another page?
I made a contact form for the users to complete in their profile. It consists of some simple fields like address and phone number and a location field to choose their coordination on a map. However, I want the location field on another page. for instance, when a user wants to fill this form, they first fill in other fields, then by clicking a button they get redirected to another page to fill the location field and then again return to the form and submit everything. is this even possible? how can I submit part of a form on a page and the rest on another page? -
How are applications (which accepts different types of requests like http and smtp) deployed on different ports on servers?
I'm a beginner in all these http and tcp/ip thing. So there maybe many things in these questions that may not make sense or are totally incorrect. First I will add all the questions I had in mind since, I could not put them on title. I work on django (python framework) for web development. I'm confused as to how servers work. And how is the destination port is decided through the url? MAIN Q : What I have learned so far is that through DNS we get the ip address of the website. And port (Both destination and source) are decided by the TCP. And sent through TCP headers. But how does it decide which port should it go to in a server(i.e. destination port). MY ANS TO ABOVE QUESTION : After spending lots of my time, I have come to know that, http requests default to 80 and https defaults to 443 and similarly other types of requests also defaults to some port. So we can figure out the ip address based on this. But this rises another question in my mind. Another Question : I have also built a simple django website and deployed it on pythonanywhere. … -
Class OfferSerializer missing "Meta.model" attribute
I have been trying to build offer management app in Django rest framework. So i made following serilizer class OfferSerializer(serializers.ModelSerializer): class Meta: fields = { 'id' 'Name' 'valid_from' 'valid_to' 'is_disabled' } fields = '__all__' and when i passed following in jason format { "id":1, "Name" : "Discount Offer", "valid_from":"2021-05-21", "valid_from":"2021-08-21", "is_disabled":1 } But i am getting error :- Class OfferSerializer missing "Meta.model" attribute In above code i have created meta mode; but still why I am getting that error? -
How do I refresh my JWT provided by Django-Rest-Framework, using Apisauce from my React-Native App?
I am building an Application with Django-Rest-Framework backend and using dj-rest-auth for authentication with Simple JWT and for the frontend I am using React-Native and am making my api calls using api-sauce (github link -> API-Sauce). API-Sauce is built on axios This is my basic clientAPI code which hits the Django-Rest-Framework from my React-Native app import { create } from "apisauce"; import authStorage from "../auth/authStorage"; const baseURL = "http://192.168.0.109:8000/api"; const apiClient = create({ baseURL: baseURL, }); apiClient.addAsyncRequestTransform(async (request) => { const authToken = await authStorage.getToken(); if (!authToken) return; request.headers["Authorization"] = "Bearer " + JSON.parse(authToken).access_token; }); export default apiClient; This works perfectly as long as the Token is active. Once the token has expired, to refresh my token I have to do the following Target URL - http://192.168.0.109:8000/api/token/refresh/ Header - "Content-Type" : "application/json" data - {"refresh":"refresh_token"} // refresh_token is obtained from authStorage in the above code-snippet like so //JSON.parse(authToken).refresh_token How can I efficiently add the code which refreshes my token, to my existing code, which makes my API to call refreshes the token automatically? -
Django: Passing variable from view to view via url link
I am learning Django and as part of a project, am trying to reference a topic from view1 called "page" (containing content) to be passed into view2 called "editpage" (where I can edit the respective topic). I believe one way to do this is via sessions, but given I only need to reference the topic a single time when the user wants to edit view1 - is there a way to pass the topic from view1 to view2 without sessions and forget the topic once the edit has been made? From the best answer to the question below, it seems I can do it via redirects? But I cannot find a way to use redirects with url links. Django Passing data between views My attempted approach was to have the editpage url contain the topic from view1, but I do not know how to pass the topic between the two views. Attempted code below for page and editpage in urls.py, views.py, page.html and editpage.html: urls.py from django.urls import path from . import views urlpatterns = [ path("editpage/<str:topic>", views.editpage, name="editpage"), path("<str:topic>", views.page, name="page"), ] views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django import … -
Django: AttributeError: 'function' object has no attribute 'get_extra_actions'
I am getting this error, and it seem to be a problem with the router urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from main import views from django.contrib.auth.views import LoginView router = routers.SimpleRouter() router.register(r'login', LoginView.as_view(), basename='login') urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls())) ] error: extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' here is the full traceback, stackoverflow could not let me post a full trackback because of formatting issue: https://paste.gg/p/anonymous/620b2e1923014f3c8ae2eec788656d7b so I assume the view have no problems (which is Django default view), anyone can help me solve the issue? -
Get backward relationships items for model in Django
I have a pet project with reviews about spare parts for cars. Here is models.py: class CarBrand(models.Model): brand = models.CharField(max_length=40, choices=(), unique=True, verbose_name="Марка") def __str__(self): return self.brand def get_absolute_url(self): return reverse_lazy('car_models_all', kwargs={'car_id': self.pk}) class CarModel(models.Model): model_name = models.CharField(max_length=60, db_index=True, verbose_name="Модель") brand_id = models.SmallIntegerField(verbose_name="ID марки") def __str__(self): return self.model_name def get_absolute_url(self): return reverse_lazy('model_info', kwargs={'model_id': self.pk}) class SparePartCategory(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('spare_parts_category', kwargs={'category_id': self.pk}) class SparePart(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') brand = models.CharField(max_length=255, db_index=True, verbose_name="Производитель") number = models.CharField(max_length=30, db_index=True, verbose_name="Номер (артикул)") category = models.ForeignKey(SparePartCategory, on_delete=models.PROTECT, verbose_name="Категория") def __str__(self): return ' '.join([self.name, self.brand, self.number]) def get_absolute_url(self): return reverse_lazy('get_spare_part', kwargs={'spare_part_id': self.pk}) class Review(models.Model): RATING_VALUES = [ ('1', 'Ужасно'), ('2', 'Плохо'), ('3', 'Сносно'), ('4', 'Хорошо'), ('5', 'Отлично'), ] spare_part = models.ForeignKey(SparePart, on_delete=models.PROTECT, verbose_name="Запчасть") mileage = models.SmallIntegerField(verbose_name="Пробег, тыс.км") car_brand = models.ForeignKey(CarBrand, on_delete=models.PROTECT, verbose_name="Марка авто") car_model = models.ForeignKey(CarModel, on_delete=models.PROTECT, verbose_name="Модель авто") owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Владелец") rating = models.CharField(max_length=1, choices=RATING_VALUES, verbose_name="Рейтинг", default=3) review = models.TextField(max_length=1000, blank=True, verbose_name="Отзыв") def __str__(self): return ' '.join([self.spare_part.name, self.spare_part.brand, self.spare_part.number]) In views.py I get one SparePart def get_spare_part(request, spare_part_id): spare_part = get_object_or_404(SparePart, pk=spare_part_id) installed_on_cars = # here I need to get all CarModel for current SparePart with Review exists context = { 'spare_part': … -
django login invalid form
I did everything right but my login does not work I put 2 input in the login form but the user request sent me 3 fields, 1 of which I did not put and I receive this fields phone-number - login-password - phone-number form* class LoginForm(AuthenticationForm): phone_number = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control mb-3', 'placeholder': 'phone_number', 'id': 'login-phone_number'})) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Password', 'id': 'login-pwd', } )) view* def account_login(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = LoginForm(request.POST) print(form) print(form.is_valid()) => #false if form.is_valid(): phone_number = form.cleaned_data.get('phone_number') password = form.cleaned_data.get('password') user = authenticate(phone_number=phone_number, password=password) print(user) if user is not None: login(request, user) return redirect('/') else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = LoginForm(request.POST) return render(request, "account/login.html", {"form": form}) login.html* {% extends "./sub_base.html" %} {% block title %}Log-in{% endblock %} {% block sub_content %} <form class="account-form" action="{% url 'account:login' %}" method="post"> {% csrf_token %} <h3 class="mb-4">Sign In</h3> {% if form.errors %} <div class="alert alert-primary" role="alert"> Error: Username or Password not correct! </div> {% endif %} <label class="form-label">{{ form.username.label}}</label> {{ form.username}} <label class="form-label">{{ form.password.label}}</label> {{ form.password}} <div class="d-grid gap-2"> <input type="hidden" name="next" value="{{ next }}"> <button class="btn btn-primary py-2 mb-4 mt-5 fw-bold" … -
Django: OR filter on Q object and manytomany values is slow
By doing the following, you can get an object whose title and tag name contain value. However, Q object and .distinct(), the query execution time will be very slow. Model.objects.filter(Q(title__icontains=value) | Q(tags__name__icontains=value)).distinct() In this case, do you recommend creating a field called search in the model and storing the values of title and tags__name in it, separated by spaces? tags = list(Model.tags.values_list('name', flat=True)) Model.search = f"{Model.title} {' '.join(tags)}" Model.save() -
(Exception while fetching data) type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
class Product { int? id; String? title; String? price; String? description; Category? category; bool? favorites; Product( { this.id, this.title, this.price, this.description, this.category, this.favorites}); Product.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; price = json['price']; description = json['description']; category = json['category']; favorites = json['favorites']; category = json['category'] != null ? new Category.fromJson(json['category']) : null; favorites = json['favorites']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['title'] = this.title; data['price'] = this.price; data['description'] = this.description; if (this.category != null) { data['category'] = this.category!.toJson(); } data['favorites'] = this.favorites; return data; } } class Category { int? id; String? categoryName; String? createDate; Category({this.id, this.categoryName, this.createDate}); Category.fromJson(Map<String, dynamic> json) { id = json['id']; categoryName = json['category_name']; createDate = json['create_date']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['category_name'] = this.categoryName; data['create_date'] = this.createDate; return data; } } Flutter is giving the unhandeled exception while fetching the data This is the console output: I/flutter ( 5234): {banners: [{name: New Sale for Diwali, image: /media/banners/b1_1Xc9YP7.jpg, link: /product/24, first: true}, {name: Sale, image: /media/banners/os2.jpg, link: /products?category=Topwear, first: true}], products: [{id: 22, title: Nike Air Force 1, image: https://minimals.cc/static/mock-images/products/product_1.jpg, description: dfmkdgfdkmgnfdgn, … -
I got IntegrityError with Bid system in my project Django
Django Error: IntegrityError at /Post/18/bid NOT NULL constraint failed: auctions_bid.bidWon Request Method: POST Request URL: http://127.0.0.1:8000/Post/18/bid Django Version: 3.2.8 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: auctions_bid.bidWon I am trying to apply this Specification: If the user is signed in and is the one who created the listing, the user should have the ability to “close” the auction from this page, which makes the highest bidder the winner of the auction and makes the listing no longer active. If a user is signed in on a closed listing page, and the user has won that auction, the page should say so. but when I runserver i got this error Please take a look at my code: url.py urlpatterns = [ # bids Close Bid path('Post/<int:id>', views.viewList, name='viewList'), path("Post/<int:id>/bid", views.take_bid, name="take_bid"), path('Post/<int:id>/close', views.closeListing, name="closeListing"), ] model.py # DONE class Post(models.Model): # data fields title = models.CharField(max_length=64) textarea = models.TextField() # bid!!!!!!!!!!! startBid = models.FloatField(default=0) currentBid = models.FloatField(blank=True, null=True) imageurl = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True) creator = models.ForeignKey( User, on_delete=models.PROTECT, related_name="all_creators_listings") watchers = models.ManyToManyField( User, blank=True, related_name='favorite') date = models.DateTimeField(auto_now_add=True) # for activated the Category activate = models.BooleanField(default=True) buyer = models.ForeignKey( … -
After changing a variable in django need to restart the server to update the variable
I'm a beginner in python and django and learned how to send data to the template, but if I'm trying to change the data (variable) while the server is running and reload the page, the data remains old, and to fix that I need to restart the server. Am I missing something? views.py from django.shortcuts import render # Create your views here. def index(request): context = { 'name': 'Nick', 'age': 24 } return render(request, 'index.html', context) index.html <h1>Hi, {{name}}<br>You are {{age}} years old</h1> -
AttributeError at /profile/ 'function' object has no attribute 'object
here is my views.py file but i keep getting this error, what could be the issue here. Profile is a class in the models.py code. if you need another part of my code please ask from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get("username") messages.success(request, f"Your account has been created! You are now able to login!") return redirect("login") else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def Profile(request): profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm( request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f"Your account has been updated!") return redirect("profile") else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.Profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, "users/profile.html", context) AttributeError at /profile/'function' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/profile/ Django Version: 2.2.8 Exception Type: AttributeError Exception Value:'function' object has no attribute 'objects' Exception Location: /Users//Desktop/project/users/views.py in profile, line 20 Python Executable: /Users//.local/share/virtualenvs/project-9FFMjpiO/bin/python -
Django User default permission
I want to add permissions (view, add, change, delete) to every user, so I add this meta class in each Model class Meta: default_permissions = ('add', 'change', 'delete', 'view') but when I log in (with new user) to the Django admin site, the user hasn't got the permission yet. Is my approach wrong? -
It's possible to have relationships between models stored in different databases in Django?
I'm currently working on a project where I handle both public and private information, both stored as different models in a common database. I would like to split this database in two, one with the private model objects and another one with the public ones. The thing is, both this models have a ForeignKey relationship with each other, and I've found conflicting answers over the internet about if this relationships can work even if the models are in two different databases. So, is this possible? Is there a better approach for doing this? Just to clarify why I want to do this, I want the project to be open source, therefore the public database should be public, but the sensitive information (users and passwords) should be kept private. -
How to pass a JSON data from React to Django using POST request?
I have a React frontend which has a state variable that contains an array. I want to pass this state variable onClick to my Django's views.py. What I have so far is something like this: App.js const [dataSource, setDataSource] = useState([]); // Where the data is stored in const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(dataSource), }; const handleSubmit = () => { fetch("http://localhost:8000/insert", requestOptions); }; <Popconfirm onConfirm={handleSubmit}> <Button>Submit</Button> </Popconfirm> views.py def insert(request): if request.method == 'POST': json_data = request.POST.get() # I'm not sure what should I be putting as a parameter for .get() method return render(request, 'frontend/index.html') urls.py ... urlpatterns = [ ... path('insert/', views.insert), ... ] Am I using the right approach? If it's right, what should I be passing as parameters to the get() method? *P.s. I'm not using DRF for this approach and I'm building the app where Django and React is in one app (not separate) where the frontend is an app of Django. -
How to access subset of kwargs.pop or another way of setting different forms based on question type?
I am building a survey app, which has questions with an attribute of type, where it can be of checkbox, textarea or radio. it also has a model of options (which has question as a foreign key) In my answerform i want to pass different types of form based on the type of the question. So far i have: (with all questions and options having radio type form... class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) prompt = models.CharField(max_length=128) class Type(models.TextChoices): YesOrNo = 'YesOrNo' Text = 'Text' MultipleChoice = 'MultipleChoice' CheckBox = 'CheckBox' type = models.CharField(max_length=15, choices=Type.choices, default=None, blank=True, null=True) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=128) And in my Forms I have: class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ["prompt", "type"] class OptionForm(forms.ModelForm): class Meta: model = Option fields = ["text"] class AnswerForm(forms.Form): def __init__(self, *args, **kwargs): options = kwargs.pop("options") choices = {(o.pk, o.text) for o in options} super().__init__(*args, **kwargs) option_field = forms.ChoiceField( choices=choices, widget=forms.RadioSelect, required=True) self.fields["option"] = option_field -
django upload image by Ajax without form
I have an input type="file" element for image upload, I attached ajax in change event listener. and used a form data for transmission. However, I failed to fetch the value in django backend. <input type="file" /> const imageUpload = function( file, success, error, ) { let fd = new FormData(); fd.append('file', file); console.log(fd); console.log(file); $.ajax({ type: "POST", url: "{% url 'image-upload' %}", data: fd, processData: false, contentType: false, success: success, error: error, }) }, @login_required @csrf_exempt def editorImageUploadPost(request): if request.is_ajax and request.method == 'POST': print(request.POST) file = request.POST['file'] portray = Portray(image=file) portray.save() request.user.profile.portrays.add(portray) request.user.profile.save() return JsonResponse({}, status=400) js console: changed FormData: No Properties File: lastModified: 1629099905000 name: "Screen Shot 2021-08-16 at 3.45.01 pm.png" size: 3716526 type: "image/png" webkitRelativePath: " python terminal: <QueryDict: {}> error message: System check identified no issues (0 silenced). November 06, 2021 - 03:28:49 Django version 3.2.8, using settings 'zzd.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [06/Nov/2021 03:28:50] "GET /articles/update/1 HTTP/1.1" 200 10010 <QueryDict: {}> Internal Server Error: /articles/new/post/ajax/upload/image Traceback (most recent call last): File "/Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/django/utils/datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, … -
How to upload and use images on heroku django
so i make this app in which you can make products. And those products have an image that was saved in a file while i was using this app localy. I deployed my app on heroku and ofc since there are no normal files like localy it cant be saved there. How can i save it somewere and use it? I also use postgesql btw to store other data so maybe i can store the image too. class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) price = models.FloatField(max_length=255, blank=True, null=True) description = models.TextField(max_length=255, blank=True, null=True) category = models.ForeignKey(Category, blank=True, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name -
running virtual env and installing packages in aws lightsail
I want to install a package which requires virtual environment before it can be installed properly. I have installed the project and other packages but there is a pakage which is not installing because I am not running my command from inside the virtual environment. Please how can I make use of virtualenv in django aws lightsail. Thanks -
Another "fk_name ' ' not a foreignkey to" problem [Python/Django]
please don't judge with my question. I tried every suggestion here but still no luck. here's my code --- admin.py from django.contrib import admin from .models import candidates_info, address class addressInline(admin.TabularInline): model = address fk_name = 'id' @admin.register(candidates_info) class candidates_infoAdmin(admin.ModelAdmin): fields =['last_name', 'first_name', 'middle_name', 'moniker'] inlines = [addressInline] models.py import datetime from django.db import models from django.utils import timezone class candidates_info (models.Model): last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50) #position = models.ForeignKey('positions', db_column='position_id', on_delete=models.CASCADE, null=False) #birth_date = models.ForeignKey('birthdate', db_column='date_of_birth_id', on_delete=models.CASCADE, null=False) #contact_info = models.ForeignKey('contact_info', db_column='contact_info_id', on_delete=models.CASCADE) addr = models.ForeignKey('address', on_delete=models.SET_NULL, null=True) moniker = models.CharField(max_length=35) #party = models.ForeignKey('political_parties', db_column='political_parties_id', on_delete=models.CASCADE, null=False) registration_dt = models.DateTimeField('date registered') class address(models.Model): lot_no = models.DecimalField(max_digits=5, decimal_places=0) block_no = models.DecimalField(max_digits=5, decimal_places=0) note: the codes commented out (#) are part of my code in models.py which I temporarily disabled as part of my code to see if it's conflicting with the declaration of foreignKey. and another thing, tried declaring and undeclaring fk_name on admin.py but still no luck. Please help guys. Been stock here for a few days now. I can't seem to find the bug. TIA btw.. here's the error from console --- <class 'votenow.admin.addressInline'>: (admin.E202) fk_name 'id' is not a ForeignKey to 'votenow.candidates_info'.