Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving into through table m2m
I'm trying to save into a table that i created to handle many2many relation. I didn't know why, but my form save into table 'Card', but doesn't save into 'Card_id_user' and i don't get why. This is my code... class New_card_creation_view(CreateView): title = "AGGIUNGI CARD" model = Card template_name = "new_card.html" fields = ['card_title', 'description', 'expiration_date', 'column'] def create_card_view(request): if request.method == 'POST': form = CardCreationForm(request.POST or None) if form.is_valid: form = form.save(commit=False) """nc = Card_id_column(card_id=form.id, column_id=request.column.id) nc.save()""" n_card = Card_id_user(card_id=form.id, user_id=request.user.id) n_card.save() form.save() return render(request, 'board.html') else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) def get_context_data(self, **kwargs): context = super(New_card_creation_view, self).get_context_data(**kwargs) context.update({'title': self.title}) return context def get_success_url(self): return reverse('board_view', args=(self.object.column.board.id,)) models.py class Card(models.Model): card_title = models.CharField(max_length=120, verbose_name='Titolo', error_messages={'unique': 'Titolo della Card già utilizzato. Per favore inseriscine un altro.'}) description = models.TextField(default='Il tuo testo...', max_length=300, verbose_name='Descrizione') expiration_date = models.DateTimeField('data di scadenza') column = models.ForeignKey(Column, on_delete=models.CASCADE, verbose_name= 'colonna di riferimento', null=False) story_points = models.PositiveSmallIntegerField(default=0, help_text='inserisci un valore da 1 a 5',validators=[MinValueValidator(1), MaxValueValidator(5)]) id_user = models.ManyToManyField(User, related_name='user_card', verbose_name='id utente', through='Card_id_user') object = models.Manager() class Card_id_user(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) card = models.ForeignKey(Card, on_delete=models.CASCADE) id = models.IntegerField(primary_key=True) n_card seems to be useless -
How to change my inline styles based on the selected language in Django
I am building a django web application. I wish to change the layout of my website from RTL(right to left) to LTR(left to right). I have implemented the HTML[dir='rtl'] in it. It worked but the main issue is that the layout. I want the layouts to get switched from LTR to RTL whenever the selected language is arabic. views.py def index(request): if not request.session.has_key('currency'): request.session['currency'] = settings.DEFAULT_CURRENCY setting = Setting.objects.get(pk=1) # >>>>>>>>>>>>>>>> M U L T I L A N G U G A E >>>>>> START defaultlang = settings.LANGUAGE_CODE[0:2] currentlang = request.LANGUAGE_CODE[0:2] context={'defaultlang': defaultlang} return render(request,'index.html',context) page.html <div id="top-header"> <div class="container"> <div class="{% if defaultlang == 'en' %}pull-left {% else %} pull-right{% endif %}"> <span>{% trans "Welcome to E-shop!" %}</span> </div> <div class="{% if defaultlang == 'en' %}pull-right {% else %} pull-left{% endif %}"> <span>GoodBye</span> </div> </div> </div> I need a way to ensure that the classes change when the language is Arabic. Please kindly help with any suggestions you have.Thanks -
'<=' not supported between instances of 'float' and 'QuerySet'
I want to make a substraction between total (its in model.py) and account balance. So here I have Order Model.py : class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey( Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) def save(self, *args, **kwargs): self.total = self.quantity * self.price return super().save(self, *args, **kwargs) In this model I have total field so in views.py: def post(self, request, *args, **kwargs): total = Order.objects.filter().only('total') print(total) balance = request.session['customer']['coin'] print(balance) if balance <= total: balance = balance - total print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get( id=request.session['customer']['id']) customer.coin = balance customer.save() request.session['customer']['coin'] = balance return HttpResponse("Remaining balance: " + str(balance)) return HttpResponse("Insufficient Balance") I tried to fetch total field and subtract with balance but its not working and I am getting this error. Another thing is i want to assign total field in a variable after this i want to substract with balance which i showed in views.py Please save me -
How to restrict a custom validator to only pushing errors to field.errors and not django messages?
I am using a custom validator on a model field. Model field: html_content = models.TextField(blank=True, verbose_name=_("HTML content"), validators=[validate_template_syntax]) Validator: def validate_template_syntax(source): try: Template(source) except (TemplateSyntaxError, TemplateDoesNotExist) as err: raise ValidationError(str(err)) However, when the validator error is triggered, it pushes the error to both the django messages framework (messages) and field.errors, so in a template if I am rendering other messages alongside a form the error is displayed twice. How do I restrict the validator to only pushing the error to the field errors context? -
GET products and images from two Django models, by filtering the product name and accessing the database only once
I have two Django models for an eCommerce website: class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Thumnbnail(models.Model): thumnbnail=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) The user will input some keywords, and I filter on the product names with that keyword, and show only those products. With every product, on the results page, I want immediately all its product thumbnails to be loaded and shown as well. How can I retrieve both models in the same viewset and same queryset, in an efficient way? I know I can achieve this with two separate querysets, one being queryset = Product.objects.filter(name__contains="Fanta").all() return queryset and the other viewset for the thumnails queryset = Product.objects.select_related('thumbnail').filter(name__contains="Fanta").all() return queryset # I will create another serializer to only show the thumbnails, for this specific queryset I might not have written the last one most correctly, I am just writing pseudo-code, but I know how to do it. My point is, I need to do the same filtering of the product_names with the input keywords twice, once to retrieve the product names and descriptions, in a ProductViewset, and one more time the same filtering, to get their thumbnails, from a ThumbnailViewset. How do I avoid this, and do the filtering only once? I know … -
How to display saved dynamic images in Django
Hi Im trying to display this image that I am generating in my view file. This image is generated on the basis of a search algorithm. It is saved in this variable "mimg". I don't understand how to display in template. I have tried various methods but nothing is helping. im new to django and don't know how to resolve this issue def match(request): this_file=os.path.abspath(__file__) base_dir=os.path.dirname(this_file) entries = os.listdir('static_in_env/db_images/') entries2= os.listdir('media/images/') list_of_files = glob.glob('media/images/*') latest = max(list_of_files, key=os.path.getctime) img=Image.open(latest) r, g, b = img.split() len(r.histogram()) red=r.histogram() green=g.histogram() blue=b.histogram() mr=max(red) mg=max(green) mb=max(blue) nhr = [i/mr for i in red] nnhr = np.multiply(nhr, 255) nhg = [i/mg for i in green] nnhg = np.multiply(nhg, 255) nhb = [i/mb for i in blue] nnhb = np.multiply(nhb, 255) n=1 p=[fname.rsplit('_', 1)[0] for fname in entries] mylist = list(dict.fromkeys(p))[:-1] for i in range(0, len(mylist)): img1=mylist[i]+'_a.jpg' img2=mylist[i]+'_b.jpg' img3=mylist[i]+'_face.jpg' f1='static_in_env/db_images/'+img1 f2='static_in_env/db_images/'+img2 f3='static_in_env/db_images/'+img3 db_img = Image.open(f1) r1, g1, b1 = db_img.split() red1=r1.histogram() green1=g1.histogram() blue1=b1.histogram() db_img2 = Image.open(f2) r2, g2, b2 = db_img2.split() red2=r2.histogram() green2=g2.histogram() blue2=b2.histogram() db_img3 = Image.open(f3) shr = red1+red2 shg = green1+green2 shb = blue1+blue2 shr1=np.divide(shr, 2) shg1=np.divide(shg, 2) shb1=np.divide(shb, 2) smr=max(shr1) smg = max(shg1) smb = max(shb1) nhr1 = [i/smr for i in shr1] nnhr1 … -
How to Retrieve a specific value of a Tuple from Django database
So here I have a table named Product which contains Food name,Category,Price,Image,Dataset id column so i would like to retrieve the value of Dataset id only ,in Django I would like to put parse dataset_id into recommend function but it doesnt give value of 31 while i select Pizza so i tried just printing it and the output in my console is <django.db.models.query_utils.DeferredAttribute object at 0x03B11CE8> here is my code from views.py from .models import Product def cart(request): if request.user.is_authenticated: print(Product.dataset_id) res=recommend(item_id=31, num=3) customer = request.user.customer order , created = Order.objects.get_or_create(customer = customer , complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items print(res) Here is my code for Products in models.py class Product(models.Model): food_id = models.AutoField food_name = models.CharField(max_length=50, default="") cateory = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) image = models.ImageField(upload_to='menu/images', default="") dataset_id = models.IntegerField(default = 0) -
Django sends it response to browser it gets this error: No 'Access-Control-Allow-Origin' header is present on the requested resource
I am using Django Rest Framework as my backend and ReactJS as my frontend. My DRF files look like this settings.py ALLOWED_HOSTS=['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'ecom', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True backend/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('ecom.urls')), ] ecom/urls.py from django.urls import path from ecom import views urlpatterns = [ path('categories/',views.CategoryList.as_view(), name = 'categories'), path('categories/<int:pk>/',views.CategoryDetail.as_view(), name = 'categories_detail'), path('products/',views.ProductList.as_view(), name = 'products'), path('products/<int:pk>/',views.ProductDetail.as_view(), name = 'products_detail'), ] REACTJS App.js import React , {Fragment, useEffect, useState} from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState({hits: []}); useEffect(async ()=>{ const result = await axios( `http://127.0.0.1:8000/categories/` , ); setData(result.data) }); return( <ul> {data.hits.map(item=>( <li key={item.id} >{item.name}</li> ))} </ul> ) } export default App; Result Access to XMLHttpRequest at 'http://127.0.0.1:8000/categories/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET http://127.0.0.1:8000/categories/ net::ERR_FAILED I tested in Postman, my API response is fine. I can see my API. However, when browser tried to fetch the API, it complains by the CORS (I … -
is there a way that i can connect my app with a gprs tracker?
Car theft becoming a major issue in my country, I am trying to build an app that will communicate with the GPRS tracker, I know there are some apps in the market but I want to add some more enhanced features to the app, how do I go about integrating the app with the GPRS tracker. Thanks! -
Django model ImageField creates a nested folder each time it uploads file
I'm sure I'm missing something silly, but I'm confused. I have the following model for my profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default="default.jpg", upload_to="profile_pics/", validators=[FileExtensionValidator(["jpeg", "jpg", "png"])], ) def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): if self.image: self.image = make_thumbnail(self.image, size=(200, 200)) super().save(*args, **kwargs) else: super().save(*args, **kwargs) But the profile_pics folder keep nesting (I'm not sure what triggers it, I'm not uploading a new avatar). So my folder structure starts to look like this: And I can't login with that user, as I get an error that reads: SuspiciousFileOperation at /login/ Storage can not find an available filename for "profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/1_0hOa7bn.jpg". Please make sure that the corresponding file field allows sufficient "max_length". My variables in settings.py look normal, I believe: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" I'm not sure where to look for the cause of this error. Uploading images to the blog posts work fine, it's just the profile photos behaving like this. Could anyone please help? -
Django queryset renders incorrectly. Just displays <QuerySet [<Modelname: Model object (1)>]>
I'm having a problem with rendering an object from a model. Here is the model. class Quarterback(models.Model): name = models.CharField(max_length=20) When I use a queryset like this... QB = Quarterback.objects.all() It doesn't return the object but this instead. <QuerySet [<Quarterback: Quarterback object (1)>]> The object is being saved by a function inside a form. class PlayerForm(forms.Form): quarterback_name = forms.CharField(label='Quarterback', max_length=100) def save(self): quarterback_name = self.cleaned_data.get('quarterback_name') Quarterback.objects.create(name=quarterback_name) In my admin panel, I can look up this model object and see that it does indeed have the name of a quarterback saved to the table. I'm not sure why my queryset won't return this though. Perhaps it's the save function causing it? -
How to add delete and update functionality to ModelSerializer?
I want to update and delete category instances using api. I have a simple model: class Category(models.Model): name = models.CharField(max_length=80) def __str__(self): return self.name this is my serializer: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["name"] view: class CategorySerializerView(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() def get_permissions(self): if self.request.method == "GET": self.permission_classes = (AllowAny, ) else: self.permission_classes = (IsAdminUser, ) return super(CategorySerializerView, self).get_permissions() urls: router = DefaultRouter() router.register(r'', CategorySerializerView) urlpatterns = [ path("", include(router.urls)) ] -
Why do I get ValidationError on my serializer when I shouldn't be getting one?
So I have this serializer: class MarkReadDeserializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField(queryset=Message.objects.all()) is_read = serializers.BooleanField() And view: class MarkReadView(CreateAPIView): read_serializer_class = MarkReadSerializer write_serializer_class = MarkReadDeserializer def get_write_serializer(self, *args, **kwargs): kwargs['many'] = True return super().get_write_serializer(args, kwargs) Now my view is being POSTed data in the shape of: [{"id": 1, "is_read": true}, {"id": 2, "is_read": false}] When this happens I get this error: rest_framework.exceptions.ValidationError: {'id': [ErrorDetail(string='This field is required.', code='required')], 'is_read': [ErrorDetail(string='This field is required.', code='required')]} I did override my is_valid method in serializer to see the initial data: def is_valid(self, raise_exception=False): print(self.initial_data) And it is printing expected: {'data': [{'id': 123, 'is_read': True}, {'id': 122, 'is_read': True}, {'id': 121, 'is_read': True}, {'id': 120, 'is_read': True}], 'many': True} Why do I get the ValidationError? -
ModelForm is not generating any form
So my problem is that even though I have created the forms from my model and provided my views with those forms, the related template is not displaying any form: The following is my forms.py : from django import forms from django.contrib.auth.models import User from .models import Account class UserUpdateForm(forms.ModelForm): email = forms.EmailField(max_length=100) class Meta: model = User fields = ['username', 'email'] class AccountUpdateForm(forms.ModelForm): class Meta: model= Account fields = ['image'] And the next one is my views.py: from .forms importUserUpdateForm, AccountUpdateForm def account(request): user_update_form = UserUpdateForm() profile_update_form = AccountUpdateForm() return render(request, 'blog/profile.html', { 'user_update_form':user_upate_form, 'profile_update_form':profile_update_form }) But the following template does not show any form {% extends './base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-12 d-flex flex-column justify-content-center align-items-start"> <img src="{{ user.account.image.url }}" alt="" class="user-profile-pic"> <label for="user-profile-pic-input">Choose an image</label> <input type="file" class="form-control-files w-100" id="user-profile-pic-input" name='user-profile-pic-input'> </div> </div> <div class="row"> <div class="col-12"> <form method="POST"> {% csrf_token %} {{ user_update_form }} {{ profile_update_form }} <input type="submit" value="Save changes!" class="btn btn-info btn-block"> </form> </div> </div> {% endblock %} -
Return two different models in the same queryset in django
Let's use these 2 simple models for example. A product can have multiple images. models.py class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Image(models.Model): image=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) In my viewset, in get_queryset(), I am fetching list of all the products, based on some keyword filter on the product's name and all their images, with queryset = Product.objects.select_related('image').filter(name__contains="Fanta").all() To the client, I want to return: JSON, a table, list of all the products (product_id, product_name, product_description) and, Another JSON, another separate table of all the images of all the products. (image_id, image, product_id) One way to do this is to make a combined Serializer, which will give me the fields (image_id, image, product_id, product_name, product_description) But I don't want this, since for every image, the product_description will be repeated, and since that one can be quite large, 10.000 characters, I want to find a more optimal way. I want to get the product_description as well, but only once, there is no need to repeat it in every row, for every image of that product. Another way to do this is to make two separate viewsets, each one with its own get_queryset(). But for the product model, I will have to filter the product_names … -
Dockerfile error - FROM requires either one or three arguments
I'm trying to import a base image into docker, but when I write the following command in my terminal: docker build . I get the following error: failed to solve with frontend dockerfile.v0: failed to create LLB definition: Dockerfile parse error line 2: FROM requires either one or three arguments It is telling me FROM requires one or three arguments (I'm following a book and they wrote it exactly like that) My Dockerfile contains the following: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ I'm running the code while in the same dir as the Dockerfile - The Dockerfile is named 'Dockerfile' Docker version 19.03.13 Any ideas why this is happening? Thank you in advance -
Error encountered while using py decouple
A string is returned in the settings.py file but SPOTIPY_REDIRECT_URI goes unnoticed. .env SPOTIPY_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxx SPOTIPY_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx SPOTIPY_REDIRECT_URI=http://localhost/ settings.py SPOTIPY_CLIENT_ID= config('SPOTIPY_CLIENT_ID') SPOTIPY_CLIENT_SECRET= config('SPOTIPY_CLIENT_SECRET') SPOTIPY_REDIRECT_URI= config('SPOTIPY_REDIRECT_URI') ERROR: decouple.UndefinedValueError: SPOTIPY_REDIRECT_URI not found. Declare it as envvar or define a default value. -
Run Django commands on Elastic Beanstalk SSH -> Missing environment variables
So this has been a long-running problem for me and I'd love to fix it - I also think it will help a lot of others. I'd love to run Django commands after ssh'ing on my Elastic Beanstalk EC2 instance. E. g. python manage.py dumpdata The reason why this is not possible are the missing environment variables. They are present when the server boots up but are unset as soon as the server is running (EB will create a virtual env within the EC2 and delete the variables from there). I've recently figured out that there is a prebuilt script to retrieve the env variables on the EC2 instances: /opt/elasticbeanstalk/bin/get-config environment This will return a stringified object like this: {"AWS_STATIC_ASSETS_SECRET_ACCESS_KEY":"xxx-xxx-xxx","DJANGO_KEY":"xxx-xxx-xxx","DJANGO_SETTINGS_MODULE":"xx.xx.xx","PYTHONPATH":"/var/app/venv/staging-LQM1lest/bin","RDS_DB_NAME":"xxxxxxx":"xxxxxx","RDS_PASSWORD":"xxxxxx"} This is where I'm stuck currently. I think need would need a script, that takes this object parses it and sets the key / values as environment variables. I would need to be able to run this script from the ec2 instance. Or a command to execute from the .ebextensions that would get the variables and sets them. Am I absolutely unsure how to proceed at this point? Am I overlooking something obvious here? Is there someone who has written … -
Django Saving files in database with username
I am getting multiple file entries from the user. And I save all of these in the database in one go. But I don't want these files to get mixed up when multiple users use the system. Therefore, when I save each file, I want the username that uploaded that file to be saved in the database. Models.py class users(models.Model): person_name = models.CharField(max_length=50, null=False, blank=True, verbose_name="name") person_surname = models.CharField(max_length=50, null=False, blank=True, verbose_name="surname") email = models.CharField(max_length=100, null=False, blank=True, verbose_name='email') user_name = models.CharField(max_length=30, null=False, blank=True, verbose_name="username") user_password = models.CharField(max_length=35, null=False, blank=True, verbose_name="password") class files(models.Model): owner= models.OneToOneField(User, unique=True, related_name="owner", on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=True) excelFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) wordFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) txtEmailFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) txtContentFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) attachmentFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,) forms.py class DocumentForm(forms.ModelForm): class Meta: model = files fields = ('description', 'excelFile', 'wordFile', 'txtEmailFile', 'txtContentFile', 'attachmentFile') views.py ( only one func ): @login_required(login_url="login") def sendmail(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sendmail') else: form = DocumentForm() return render(request, 'sendmail.html') I am not adding the html file here because I received multiple file entries from the user and the html file is mixed. Database ( MySql Workbench ): How can I do it ? -
Django Rest Framework Error: JSON parse error - Expecting ':' delimiter: line 4 column 21 (char 103)
I want to save a new user via POST request using the @api_view decorator in DRF but got the following error : { "detail": "JSON parse error - Expecting ':' delimiter: line 4 column 21 (char 103)" } models.py code: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.conf import settings class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'users/default.jpg', upload_to = 'users/profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) views.py code: from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser from .serializers import UserSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_view(['GET', 'POST']) def user_list(request): if request.method == 'GET': users = User.objects.all().order_by('id') serializer = UserSerializer(users, many = True) return Response(serializer.data) elif request.method == 'POST': serializer = UserSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_created) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) serializers.py code: from rest_framework import serializer from django.contrib.auth.models import User from .models import Profile from django.contrib.auth.hashers import make_password class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only = True) … -
NameError: name 'MyModel' is not defined. Why?
I dont really understand what is happening in my code but it says the my Book model is undefined. Below is my code: This is my forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class BooksForm(forms.ModelForm): class Meta: model = Books fields=('book_id',) my models.py class Books(models.Model): book_id = models.CharField(primary_key=True, max_length=50) book_title = models.CharField(max_length = 100) book_author_id = models.ForeignKey(Author, on_delete=models.CASCADE) book_cover = models.ImageField(upload_to='media/') book_file = models.FileField(upload_to='media/') book_year = models.DateField(default = timezone.now) book_tags = models.CharField(max_length = 100) book_summary = models.CharField(max_length = 100) book_category_no = models.ForeignKey(Category, on_delete=models.CASCADE) book_info = models.CharField(max_length = 100, default="") is_bookmarked = models.BooleanField() is_downloaded = models.BooleanField() is_read = models.BooleanField() class Meta: db_table = "Books" -
How to make an API using DRF to accept and verify a JWT?
I need to make an API which can take in a JWT token and an ID parameter and create multiple endpoints which will serve data( like '../api/contact/', '../api/qualifications/', etc). I do not understand how to take in the JWT and the ID parameter. Should I make another API endpoint where the user can POST the data but how do I save it in Django and design a way to serve the other endpoints? This is the first time I'm making any sort of APIs. -
Djongo: objects.all() on model having ArrayReferenceField
I'm using Djongo(a mongo database connector for django). Model.objects.all() causes issues on a model containing ArrayReferenceField (documentation: https://www.djongomapper.com/using-django-with-mongodb-array-reference-field/). The code works as expected when I remove all the ArrayReferenceFields from the model In the code below, Projects.objects.all() gives the error: from_db_value() missing 1 required positional argument: 'context'. However, printing Projects.objects gives database_models.Projects.objects irrespective of whether the model contains an entry. So the error lies in the all() method. Any one of the following will help: Syntax to fetch all records Modification of model such that it supports all functionalities of ArrayReferenceField Any other workaround so I can store and fetch the values Traceback: Traceback (most recent call last): . . . File "Path_to_file_having_method\project.py", line 85, in fetch_projects_of_user print(Projects.objects.all()) File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 276, in __iter__ self._fetch_all() File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "path_to_project_folder\env\lib\site-packages\django\db\models\query.py", line 74, in __iter__ for row in compiler.results_iter(results): File "\env\lib\site-packages\django\db\models\sql\compiler.py", line 1095, in apply_converters value = converter(value, expression, connection) TypeError: from_db_value() missing 1 required positional argument: 'context' My model: from .users import Users from djongo import models class Projects(models.Model): project_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=200) description =models.CharField(max_length=200,default='') mentor = models.CharField(max_length=200,default='') max_members = models.IntegerField() … -
Django Rest Framework - Calling .update() from an overriden .create() method inside ModelViewSet
I'm using Django 2.2.x and djangorestframework 3.11.1. Inside a ModelViewSet I had to override the .create() method to customize the default behavior. Sometimes I need to really create a new model instance upon receiving a POST http request, sometimes I need to .update() an existing instance but all I can receive are POST requests (the source is an external server I don't have control over). I know it's a bad idea to conflate create and update... The problem is that whenever my update-instead-of-create logic kicks in, I get the following error: AssertionError: Expected view EventViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly I tried two other ways to work around this issue: directly call Event.objects.update() but I realized this is a no go for me, since I overrode the get_serializer() method to alter the raw json payload coming from the external server and I don't want to duplicate the customization logic here. calling the django built-in .update_or_create() method but the filtering was a bit too complex and I still have the same problem of the first bullet My view: class EventViewSet(LoggingMixin, viewsets.ModelViewSet): """this is … -
How to deserialize array of objects with no name?
So I have array of object being POSTed to my view with shape like this: [{"id": 5, "is_read": true}, {"id": 6, "is_read": false}] I want to find a way of deserializing that in my DRF serializer. It is possible to have nested serializers when your array has name, that is, is like this: "arrayName": [] instead of just like this: []. With nested serializers I could write something like this: class MarkReadItemDeserializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField(queryset=Message.objects.all()) is_read = serializers.BooleanField() class MarkReadDeserializer(serializers.Serializer): arrayName = MarkReadItemDeserializer(many=True) Now this obviously doesn't work in my case because my array is not named arrayName. Any idea how I could go about this?