Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Specify method at as_view in Django urls. (GET, POST etc)
I have some classes with (APIView) and obviously I include them in my urls.py. Question is, if there is a way, to specify method, when I use construction like that: path('mods/mix', MixCUD.as_view()), path('mods/mix/update/<int:mixId>', MixCUD.as_view()), path('mods/mix/delete/<int:mixId>', MixCUD.as_view()), Because, if I understand correctly, I can call delete method of a MixCUD from mods/mix/update/int:mixId address. So I need something like that: path('mods/mix', MixCUD.as_view([POST])), path('mods/mix/update/<int:mixId>', MixCUD.as_view([UPDATE])), path('mods/mix/delete/<int:mixId>', MixCUD.as_view([DELETE])), I can't change them all to a single address, so I have to manage this somehow. -
uwsgi not loading webpacks bundle files (.js)
I'm having a hard time with uwsgi. What happens is (I assume) uwsgi fails to attach main.js in index.html which Django routes. main.js is a webpack bundle from npm run build. My application runs in docker and in it I specified /vol/web/static/frontend directory to include main.js and it is there. curl 127.0.0.1:8000 gives me html (as expected), but in Mozilla, on same socket I get a blank page (with 200 OK http request and response of below html). At 127.0.0.1:8000/static/main.js I receive this main.js file. Why do I get a blank page ? Any clues ? My effort on this is I've reworked my whole static files rooting and directories in Django, tried a 1000 different flags on uwsgi cmd and different static files directories and paths to load from. None of this worked for now. Response html <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Label It</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </head> <body style="margin: 0"> <div id="main"> <div id="app"> </div> </div> <scipt type="application/javascript" src="/static/main.js"></scipt> </body> </html> I've set up my uwsgi connection to: uwsgi --http 0.0.0.0:8000 \ --master \ --module label_it.wsgi \ --processes 2 \ --static-map /static=/vol/web/static/frontend \ --static-map /static/main.js=/vol/web/static/frontend/main.js \ --check-static /vol/web/static/ … -
Django Admin: Give initial data to form field
I need to manually add an entry to the database via the admin panel, but the admin should not be able to set all the values: #models.py class Product(models.Model): price = models.DecimalField("price") status = models.PositiveIntegerField("status") name = models.CharField("name", max_length=31, unique=True) ## tried: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initial['status'] = 2 #admin.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ["price", "name",] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): form = ProductForm ## tried: def get_changeform_initial_data(self, request): return {'status': 99} Admin should be able to create a Product and give it a name and price, but the status value should be set to 0. I already tried this approach and this, but no success. I tried: Using an __init__ method to add initial values get_changeform_initial_data() method to add a status. I always end up with sqlite3.IntegrityError: NOT NULL constraint failed: _TEST_Product.status -
Django - How to do complex query with left join and coalesce?
Scenario: Showing all voucher that a user can apply. I have 2 tables Voucher (with all information of a voucher) and VoucherCustomer (listing number of vouchers that a user has used) A validation voucher that can show to user on the application should be Within use-able duration Do not exceed number of times used within a day Do not exceed number of times used per user Do not exceed number of times used for a voucher Must active Here is my model: class Voucher(models.Model): code = models.ForeignKey('VoucherCustomer', related_name= 'voucher_code', on_delete = models.CASCADE) (1) start_at = models.DateTimeField() (2) end_at = models.DateTimeField() (3) usage_limit_per_customer = models.BigIntegerField() (4) times_used = models.BigIntegerField() (5) usage_limit_daily = models.BigIntegerField() (6) times_used_daily = models.BigIntegerField() (7) is_global = models.BooleanField(blank=True, null=True) (8) is_active = models.BooleanField() (9) class VoucherCustomer(models.Model): voucher_code = models.CharField(max_length = 255, primary_key=True) (1) customer_id = models.IntegerField() (2) times_used = models.BigIntegerField(blank=True, null=True) (3) created_at = models.DateTimeField(blank=True, null=True) (4) updated_at = models.DateTimeField(blank=True, null=True) (5) Here is the sample data: +++++++ Voucher ++++++++ (1) (2) (3) (4) (5) (6) (7) (8) (9) TEST01 | 2020-11-30 17:00:00 | 2021-03-01 16:59:59 | 100 | 1124 | 5000 | 6 | true | true +++++++ VoucherCustomer ++++++++ (1) (2) (3) (4) (5) TEST01 10878 … -
Extended User Model not updating
Hii I'am new to Django rest frame work and was preparing API's So this is my models.py class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class User_log(models.Model): user = models.OneToOneField(auth.models.User,on_delete=models.CASCADE,related_name='user_logs') fullname=models.CharField(max_length=255) fb_login=models.BooleanField(default=False) def __str__(self): return self.fullname serializers.py class userSerializers(serializers.ModelSerializer): fullname=serializers.StringRelatedField(source='user_logs.fullname',read_only=False) fb=serializers.BooleanField(source='user_logs.fb_login') class Meta: model = User fields=('id','username','email','fullname','fb') related_fields = ['user_logs'] def update(self, instance, validated_data): # Handle related objects for related_obj_name in self.Meta.related_fields: print('exe') print(instance,validated_data) # Validated data will show the nested structure data = validated_data.pop(related_obj_name) related_instance = getattr(instance, related_obj_name) # Same as default update implementation for attr_name, value in data.items(): setattr(related_instance, attr_name, value) related_instance.save() return super(userSerializers,self).update(instance, validated_data) viewset.py class Userview(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class=userSerializers Now the problem: whenever i try to update fullname column through json request { "id": 2,"username": "karam","email": "karam@83ideas.com","fullname": "karm","fb": true } i am getting this error "POST /accounts/accounts/2/ HTTP/1.1" 405 41 and as in serializers.py update method i have printed the validated data instead of this karam {'username': 'karam', 'email': 'karam@83ideas.com', 'user_logs': {'fullname':'karam','fb_login': True}} i am getting this karam {'username': 'karam', 'email': 'karam@83ideas.com', 'user_logs': {'fb_login': True}} SO any idea how to resolve it? -
Some question about django restful summary
I have a table namely my_activity the models is: class myActivity(models.Model): ac_date=models.DateField(auto_now=True) user = models.ForeignKey(User,verbose_name='使用者',on_delete=models.CASCADE,related_name='my_activity') title = models.ForeignKey(Activity,verbose_name='活動名稱',default='',on_delete=models.CASCADE,related_name='activity') point = models.IntegerField(default=0,verbose_name='點數') I want to write a restful api to summary the point by use_id,like [{'user': 1, 'score': 9}, {'user': 2, 'score': 9}]。 I write the urls.py router.register(r'Score',ScoreSet) In the views.py , I add class ScoreSet(viewsets.ModelViewSet): queryset = myActivity.objects.values('user').annotate(score=Sum('point')) serializer_class = ScoreSerializers and in serializers.py ,I add class ScoreSerializers(serializers.ModelSerializer): class Meta: model = myActivity fields = ('user','point') When I execute the api,I get the error。How can I finish this code? Your help is appreciate. AttributeError at /api/Score/ 'int' object has no attribute 'pk' Request Method: GET Request URL: http://127.0.0.1:8000/api/Score/ Django Version: 3.1.3 Exception Type: AttributeError Exception Value: 'int' object has no attribute 'pk' Exception Location: D:\Program\Workspace\Python\envs\DjangoEnv\lib\site-packages\rest_framework\relations.py, line 271, in to_representation Python Executable: D:\Program\Workspace\Python\envs\DjangoEnv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['D:\\Program\\Workspace\\Python\\usr', 'D:\\Program\\Workspace\\Python\\usr', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.2.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32', 'D:\\Program\\Workspace\\Python\\envs\\DjangoEnv', 'D:\\Program\\Workspace\\Python\\envs\\DjangoEnv\\lib\\site-packages', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.2.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Thu, 18 Feb 2021 17:42:55 +0800 -
django filter with user and profile model
I'm using the default User model that has a one-to-one relationship to the Profile model I'm using django-filter to search for things, but it only works for the User model and nothing in the profile model works. How can I include the profile model into the search? filters.py: class AdminUserFilters(django_filters.FilterSet): first_name = CharFilter(field_name='first_name', lookup_expr='icontains') last_name = CharFilter(field_name='last_name', lookup_expr='icontains') username = CharFilter(field_name='username', lookup_expr='icontains') email = CharFilter(field_name='email', lookup_expr='icontains') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email',) models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True, blank=False, max_length=8) -
Django form is valid() returns false
I am encountering form.is_valid() returning false. I have tried printing form.erorrs and it gives me the following: <ul class="errorlist"><li>uploaded_images<ul class="errorlist"><li>“b&#x27;\xbd\x06D\xcd3\x91\x85,\xdf\xa5K\n&#x27;” is not a valid value.</li></ul></li></ul> I am not sure how to interpret this general error. Been searching for quite some time but couldn't find an answer. I must be missing something simple but I just can't find it!! Another pair of eyes to help me sieve through would be very appreciated! views.py from django.shortcuts import render,redirect from django.views.generic.edit import FormView from .forms import BRForm from .models import * class BRHomeView(FormView): form_class = BRForm model = TargetImage template_name = 'br/br-home.html' context_object_name = 'bankrecon' def get(self, request): form = BRForm(request.POST, request.FILES) return render(request, self.template_name, {'form': form, 'title': 'Bank Reconcilation'}) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('uploaded_images') print("POST") print(request.POST) print("FILES") print(request.FILES) print(form.errors) if form.is_valid(): form.save() return redirect('br-home') models.py from django.db import models # Create your models here. class UploadedImages(models.Model): image_files = models.ImageField(null=True, blank=True, upload_to='images/') class TargetImage(models.Model): invoice_date = models.DateTimeField() recon_date = models.DateTimeField() uploaded_images = models.ManyToManyField(UploadedImages) def __str__(self): return self.invoice_date forms.py from django import forms from django.core.validators import FileExtensionValidator from .models import * class BRForm(forms.ModelForm): class Meta: model = TargetImage fields = ('invoice_date', 'recon_date', 'uploaded_images') widgets = … -
User to paying registration fee for Django application
I have a Django application with a basic UserRegisterForm and I would like the user to pay the entry fee before the user is created. I am thinking PayPal as it seems the easiest to integrate. Do I direct them to the Paypal payment on submit and then redirect run the buy function in my views within that call to register the data? views.py def buy(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): data = form.cleaned_data email = f"{data['email']}" username = f"{data['username']}" form.instance.username = username form.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'users/buy.html', {'form': form}) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() username = forms.CharField(max_length=20) class Meta: model = User fields = ['email', 'username', 'password1', 'password2'] -
Multiply every form value in Django template
I'm created a form where values are coming from my view and the value is daily basis and I want to give a drop down where user can change it to weekly basis and the values will be multiplied by 7. As you can see in the above picture, I'm giving a drop down option where user can change it to weekly basis and monthly basis and the value inside the form will change as per the selection. But I'm not aware how I can achieve this. My code: return render(request, 'test.html', {'List1': l1, 'List2': l2, 'List3': l3} and my form.html is readonly form which renders these list in order. <form> <div class="form-row"> {% for l in List1 %} <div class="form-group col-md-4"> <label>x</label> <div class="input-group mb-3"> <input type="text" value="{{l}}" readonly> </div> </div> {% endfor %} </div> ........simliary for rest list. </form> I want to multiply every value inside form by 7 when user selects weekly in drop-down. How can I achieve it? -
Django + MQTT how to make request and wait for response in view
I am writing a django application and I need a way how to ask for data on MQTT and wait for response (or timeout). Something like this in view: mqtt.subscribe('response/topic') mqtt.publish('request/topic', '{my json request message}') for m in mqtt.on_message(): if m.payload == '......' # OK I have response, render data from response to page, ... # timeout could be implemented by raising exception in on_message() How can i integrate paho mqtt? Or is there any other way? I need to wait for response on several places in views, one global on_message callback is not really useful. Where should I put mqtt.loop_forever() in django? Thank you -
Django multi-app static files - developing locally and pushing to Elastic Beanstalk server
I have a django project with multiple apps inside it as so: /UserProject /Static /UserApp /UserApp/Static I have my global styling held within the /static/ folder, then individual UserApp styling held within the UserApp static folder. Then, within my settings.py I have: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) This is great for local development - I can run the development server and the site updates as I update the stylesheets within either the root /static or the UserApp /static. However, when I push to my elastic beanstalk instance (depending on my configuration) - I get either (a) only the root /static files loading, (b) no static files loading or (c) an error on deployment You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I have tried using the following in my .ebextensions folder container_commands: 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" But this gives me the staticfiles app error. What is the correct setup in my settings.py to allow local development, and then also allow pushing to the EB instance? -
Authenticate Generated API Key in accessing Django Rest API
I need to let third-party users access some of the REST APIs that I have. I made an APIkey model that will store the generated keys that can be used in accessing the API. I just don't know yet how will I add the API key to the authentication of my app since I already have a BearerTokenAuthentication in my auth.py -
add to favourite list in django
I have added the add to favorites list feature for each product on the product page of my website, and the user can add any product to their favorites list. But if the user already adds this product to the favorites list, I want the word remove to be displayed instead of the word add, so that if he wants, he can remove that product from his favorite list. But the following error occurs: AttributeError: 'QuerySet' object has no attribute 'favourite' # model class Product(models.Model): title = models.CharField(max_length=200) favourite = models.ManyToManyField(User, related_name='user_favourite') # view def product(request): products = Product.objects.all() is_favourite = False if products.favourite.filter(id=request.user.id).exists(): is_favourite = True context = {'products': products, 'is_favourite': is_favourite} #template {% if is_favourite %} <a href="{% url 'home:favourite' product.id %}"> remove </a> {% else %} <a href="{% url 'home:favourite' product.id %}"> add </a> {% endif %} -
how to create ForeignKey for username (not userid) in django models.py
I created the following fieldmodels.py added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and it contained the user Id , but how to make it contain the username instead. -
403 Forbidden request when making an axios call with React (Django backend)
I am trying to authenticate my session on a web application using ReactJS. My backend is setup on Django. When logging in to the application, I do receive the cookies in the header, however I am unable to set the cookies. However, when I try to post the request 'withCredentials: true', it returns me the 403 error. The login call (Where I receive the cookies in response header) let url = `${BASE_URL}/login/`; console.log('params for validateOtp:', params); axios .post(url, params) .then((res) => { console.log('validate otp code res: ', res); resolve(res); }) .catch((err) => { console.log('validate otp code err: ', err); reject(err); }); After seeing the console, it is visible under the 'Network' tab that I do receive cookies from this API. This is the API where I make the authenticated call. let url = `${BASE_URL}/updatemerchant/`; axios .post(url, params, { withCredentials: true } ) .then((res) => { console.log('updateDukaanUserToCloud res : ', res); // resolve(res) if (res.status === 200) { resolve(res); } else { reject('updateDukaanUserToCloud something went wrong'); } }) .catch((err) => { if (err.response && err.response.status === 400) { reject('updateDukaanUserToCloud updating user info failed'); } else { reject('updateDukaanUserToCloud something went wrong'); } }); settings.py CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_NAME = … -
Do not display the product category name on the details page in django
when I want to display the category name of the desired product in the details page, it returns a good value if the brand name of the desired product returns correctly. # model class Product(models.Model): category = models.ManyToManyField(Category, related_name='cat_product') brand = models.ForeignKey('Brand', on_delete=models.CASCADE) # view def product_detail(request,id) products = product.objects.get(id=id) context = {'products': products} return render(request, 'home/detail.html', context) #template <p>category : {{products.category}}</p> <br> <p>category : {{products.brand}}</p> -
Celery only responding Sending due tasks
I followed this instruction on how to implement Celery with Django. However, after everything done, on my terminal it just repeating Sending due tasks "NAME" users.tasks.send_notification Here is what I did: tasks.py from celery import task from celery import shared_task def send_notification(): print("TEST") project's init.py from __future__ import absolute_import, unicode_literals from .celery import celery_app as celery_app __all__ = ('celery_app',) apps' init.py default_app_config = 'users.apps.UsersConfig' settings.py from celery.schedules import crontab BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Tokyo' -
How can I get the current user in models.py?
Hi I am trying to add the User column to know which User added the tool in the tools/model.py page tools_name = models.CharField('Tool\'s Name', max_length=100, unique=True) tools_project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, null=True, blank=True, limit_choices_to=~Q(project_status=2), verbose_name='Project\'s Name') user = models.CharField(max_length=100, editable=False) But I want to know how to save the user that created or updated the tool ? -
Django foreign key: auto-lookup related object when the update record has the key value
I have legacy code which had no foreign keys defined in the schema. The raw data for the row includes the key value of the parent, naturally. My first porting attempt to postgresql just updated the field with the raw value: I did not add foreign keys to Django's models. Now I am trying to add foreign keys to make the schema more informative. When I add a foreign key, django's update requires me to provide an instance of the parent object: I can no longer update by simply providing the key value. But this is onerous because now I need to include in my code knowledge of all the relations to go and fetch related objects, and have specific update calls per model. This seems crazy to me, at least starting from where I am, so I feel like I am really missing something. Currently, the update code just pushes rows in blissful ignorance. The update code is generic for tables, which is easy when there are no relations. Django's model data means that I can find the related object dynamically for any given model, and doing this means I can still keep very abstracted table update logic. So … -
Javascript Error - Uncaught ReferenceError: load_mailbox is not defined at HTMLDocument
I'm working on an app to send email messages using Django and Javascript. I'm getting the error in the Javascript file: Uncaught ReferenceError: load_mailbox is not defined at HTMLDocument. The issue happens at the 13th line which is: load_mailbox('inbox'); I have tried re-writing it many different ways but for some reason cannot figure out how to 'define' this. I'm very new to JS, any help is appreciated. inbox.js: document.addEventListener('DOMContentLoaded', function(e) { // Send the email to server upon clicking on submit document.querySelector('#compose-form').addEventListener('submit', (e) => submit_email(e)); // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', () => compose_email()); // By default, load the inbox load_mailbox('inbox'); }); //Submit email after user composes an email and submits function submit_email(e){ e.preventDefault(); const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body }) }) .then(response => response.json()) .then(result => { console.log("result"); }) .catch(error => { console.log('Error:', error); }); load_mailbox('sent'); }; -
Django file not uploaded using FileField(upload to=)
am very new to concepts of django and it's functionalities so i came across a project which will easily help one to upload a file to a directory using FileField Upload to , but for me it is not working , i tried different ways i modifed it but still i am not sure about the error am getting . So someone please guide me here is my code : Models.py class UploadedFiles(models.Model): files_to_upload = models.FileField(upload_to='uploaded_files/', default=None, validators=[validate_file]) path = models.CharField(max_length=100) server = MultiSelectField(choices=server_list) SalesforceTicket = models.ForeignKey(SalesforceTicket, related_name="files", on_delete=models.CASCADE) def __str__(self): return str(self.SalesforceTicket) forms.py class FilesForm(forms.ModelForm): class Meta: model = UploadedFiles fields = ['files_to_upload', 'path', 'server'] # called on validation of the form def clean(self): # run the standard clean method first cleaned_data = super(FilesForm, self).clean() files_to_upload = cleaned_data.get("files_to_upload") path = cleaned_data.get("path") server = cleaned_data.get("server") # print(files_to_upload) # print(path) # print(server) new_path = path.replace(':', '$', 1) # print(new_path) mode = 0o666 for s in server: s = r'\\' + s unc_path = os.path.join(s, new_path) print("hello"+unc_path) #unc_path = os.mkdir(unc_path, mode) isdir = os.path.isdir(unc_path) if isdir: print("ok") else: unc_path = os.mkdir(unc_path, mode) return cleaned_data Views.py def files(request): num_of_files = 1 filled_multi_file_form = MultipleForm(request.GET) if filled_multi_file_form.is_valid(): num_of_files = filled_multi_file_form.cleaned_data['num_of_files'] FilesFormSet = formset_factory(FilesForm, extra=num_of_files) … -
How to get html form field data in JSON and insert into database with Django?
I have created one project where User Registration functionality is there. Once user fill the form, I'll be getting data in Django using POST and insert into Database. Now I don't want to get data into my code directly from the form. My requirement is: 1. Once User fill the form and submit, then JSON data should be created so that I can give that API to the frontend. 2. I would take that JSON data using API and insert that record into my MySQL database dynamically for different users. Here is my code : models.py from django.db import models class Employee(models.Model): name = models.CharField(max_length=100, blank=False, null=True) username = models.CharField(max_length=100, blank=False, null=True) email = models.EmailField(max_length=200, blank=False, null=True) mobile = models.CharField(max_length=30, blank=False, null=True) def __str__(self): return self.name viewsets.py from rest_framework import viewsets from . import models from . import serializers class EmployeeViewset(viewsets.ModelViewSet): queryset = models.Employee.objects.all() serializer_class = serializers.EmployeeSerializer serializers.py from rest_framework import serializers from employeeapi.models import Employee class EmployeeSerializer(serializers.ModelSerializer): class Meta: model =Employee fields = '__all__' urls.py from django.contrib import admin from django.urls import path, include from .router import router urlpatterns = [ path('admin/', admin.site.urls), path('api/',include(router.urls)) ] router.py from employeeapi.viewsets import EmployeeViewset from rest_framework import routers router = routers.DefaultRouter() router.register('employee',EmployeeViewset) These … -
Check if the wishlist already exist before creating one of the logged in user in django rest framework
I have a create API that creates a wishlist of a user after the user logged in on the frontend. But before creating one I want to check whether the user already has a wishlist before. For that I wrote a validation function but its not working. Error:TypeError: int() argument must be a string, a bytes-like object or a number, not 'collections.OrderedDict My view: class WishListAPIView(ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = WishList.objects.all() serializer_class = WishListSerializer def perform_create(self, serializer): user = self.request.user serializer.save(owner=user) My serializers: class WishListSerializer(serializers.ModelSerializer): def validate(self, owner): abc = WishList.objects.filter(owner=owner).exists() if abc: raise serializers.ValidationError('Wishlist exists.Now add items') return owner class Meta: model = WishList fields = '__all__' depth = 1 My model: class WishList(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) # item = models.ManyToManyField(Product,blank=True, null=True) def __str__(self): return self.owner.email My urls: path('api/createwishlist/<int:pk>', views.WishListAPIView.as_view(), name='api-wishlist'), -
getting 'name' is an invalid keyword argument (using graphene-django)
i am using graphene and getting 'name' is an invalid keyword argument for GuestMutation error what is it related to? //models.py class Guest(models.Model): name = models.CharField(max_length=100) phone = models.IntegerField() def __str__(self): return self.name //schema.py class GuestType(DjangoObjectType): class Meta: model = Guest fields = ('id','name','phone') class GuestMutation (graphene.Mutation): class Arguments: name = graphene.String(required=True) phone = graphene.Int(required=True) guest = graphene.Field(GuestType) @classmethod def mutate(cls, root,info,name,phone): guest = Guest(name=name, phone=phone) guest.save() return GuestMutation(name=name, phone=phone) class Mutation(graphene.ObjectType): add_guest = GuestMutation.Field() error message Traceback (most recent call last): File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/promise/promise.py", line 489, in _resolve_from_executor executor(resolve, reject) File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/promise/promise.py", line 756, in executor return resolve(f(*args, **kwargs)) File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise return next(*args, **kwargs) File "/home/ahmed/Documents/Django/Shalleh/booking/schema.py", line 66, in mutate return GuestMutation(name=name, phone=phone) File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/graphene/types/objecttype.py", line 169, in init raise TypeError( graphql.error.located_error.GraphQLLocatedError: 'name' is an invalid keyword argument for GuestMutation