Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'colorama' has no attribute 'init'
i have python version 3.8 and trying to deploy django model to Apache2 server and getting this error. anybody can help me to resolve this? -
no such column: Blog_post.category_id
I’m trying to create a category for each post. I made another class with the same models.py and in the same class Post I made a category = models.ForeignKey But it keeps showing me this error when I run the server: (no such column: Blog_post.category_id) Ps: I did run the makemigrations and the migrate command. The tutorial I followed just added the model as it is in models.py but should I also make a function for the views.py or its just a model problem ? models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default="Some random thing") -
Django : change the id with another field in the views page
my question is: How do I tell to Django to replace the Column type_id to the name field in the views (html page). and here I have foreignkey, it gave me id (type_id), and this screentshot of fabrication class: the column type_id is comming from the composant_type class, models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from CentreCout.models import CentreCoutDB class fiche(models.Model): centre_cout = models.CharField(max_length=150) number = models.CharField(max_length=100) name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class unite(models.Model): name = models.CharField(max_length= 150, unique=True) def __str__(self): return self.name class composant_type(models.Model): name = models.CharField(max_length=150, unique=True ) def __str__(self): return f"({self.name})" class composant_fab(models.Model): type = models.ForeignKey(composant_type, to_field='name', on_delete=models.CASCADE) name = models.CharField(max_length=150, unique=True) def __str__(self): return f"({self.name})" class fabrication(models.Model): grade = models.ForeignKey(fiche, to_field='name',on_delete=models.CASCADE) type = models.ForeignKey(composant_type, on_delete=models.CASCADE, blank=True, null=True) composant = models.ForeignKey(composant_fab , to_field='name', on_delete=models.CASCADE, null=True, blank=True) unite = models.ForeignKey(unite, to_field='name',on_delete=models.CASCADE) composant_value = models.FloatField(blank=True, null=True) def __str__(self): return f"({self.grade}-{self.composant}-{self.composant_value}-{self.unite})" views.py from django.shortcuts import render from django import views from django.http import HttpResponse from .models import * import pandas as pd def fabrications(request): lesfichestab = fiche.objects.all() fabricationtab = fabrication.objects.all().values() df = pd.DataFrame(fabricationtab) context = { 'lesfichestab':lesfichestab, 'fabricationtab':df.to_html() } return render(request,'fabrications/fabricationpage.html', context) note : I use Pandas method, because i have … -
showcasing one attribut of multiple instances from a model django/python
i basically have 2 models with multiple attributes, i would like to showcase a specific attribute which has multiple instances, in another model basically : class Carnet(models.Model): ....multiple attributes class Consultation(models.Model): .... date_cons = models.DateTimeField(default=datetime.now, blank=True) There are multiple instances of date_cons, i would like to showcase the latest one added in an html code the view method i used was this ( probably here is the problem ) def consultation(request, carnet_id): consultation = Consultation.objects.all() context = { 'consultation' : consultation } return render(request, 'carnets/carnet.html',context) tried showcasing that attribute in an html code using this syntaxe {{consultation.date_cons}} but it doesn't showcase anything my question is probably all over the place i'm not very good at computer science nor english, i ask for your help -
Django: pass request and response as view parameters
I have a view which takes two parameters (request, response). But when this view is called i get an error which saying - "figure() missing 1 required positional argument: 'response' " views.py: def figure(request, response): print("request ->", request) figures = add_data_to_class(request) figures_dict = [] for figure in figures: figures_dict.append({ "date":figure.date, "price_new":figure.price_new, "price_used":figure.price_used, }) print(figures_dict) context = {"figures":figures_dict} return render(response, "app1/figure_data_page.html", context, RequestContext(request)) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.figure, name="figure") ] figure_data.html <form action="main\app1\views.py" method="post" id="figure_choice_form"> <label for="id">Enter ID</label> <input type="text" id="id"> </form> -
How to make a select field using Django model forms (using set values)?
I recently switched from using simple forms in Django to model forms. I am now trying to use a select field in my form that has set field names (eg:Europe,North America,South America...) I thought I would just add a select input type to the for fields but it shows up as just a regular text input. The select field is supposed to be "continent". Does anyone know how to to d this?? class TripForm(forms.ModelForm): # city = forms.TextInput() # country = forms.TimeField() # description = forms.Textarea() # photo = forms.ImageField() class Meta: model = Trip fields = ('city', 'country', 'continent', 'description', 'photo') widget = { 'city': forms.TextInput(attrs={'class': 'form-control'}), 'country': forms.TextInput(attrs ={'class': 'form-control'}), 'continent': forms.SelectMultiple(attrs= {'class':'form-control'}), 'description': forms.TextInput(attrs = {'class': 'form-control'}), # 'photo': forms.ImageField(attrs = {'class': 'form-control'}), } [![enter image description here][1]][1] This is the form continent should show as a select. -
How to do Simple Arithmetic validation in template part - django
I want to check total price and receiving price of user input which receiving price shouldn't be more than total price. say example, I do have 3 input box. box a getting value of total price, box b getting value of receiving payment through card and box c getting value of receiving payment by cash. box b + box c should not greater than box a. I need to validate it and stop submitting it. It may very simple, since I am new to django I posting it here. -
How can I query all products with their variation attributes?
I have following database schema: Django models: class Product(models.Model): name = models.CharField(max_length=150) # price and so on class Size(models.Model): value = models.CharField(max_length=20) class Color(models.Model): value = models.CharField(max_length=20) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variations") size = models.ForeignKey(Size, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE, null=True, blank=True) So I can write: product.variations But I also want to be able to write product.sizes product.colors to get all sizes or colors that this product has in variation table The problem that I'm trying to solve: I have product card list. And each card has options of sizes and colors to choose and to add to their cart. I want to show the user sizes and colors that this particular product has in database to not list all the sizes and colors from database. But variations can have duplicates, for example, consider these combinations: size - 40, color - red size - 42, color - green size - 44, color - red (again) size - 42 (again), - color gray I want to show the user sizes: 40, 42, 44 colors: red, green, gray Now I can show all of them with duplicates like sizes: 40, 42, 44, 42 colors: red, green, red, gray It is … -
Getting OperationalError: (2000, 'Unknown MySQL error') when accessing mysql database using celery and django
I am using celery with my django application. My application works fine with mysql database, but I am getting (2000, 'Unknown MySQL error') when celery tries to access the database. This happens only when I run celery in a container, when I run it in my ubuntu machine, it works fine. This is the error that I am getting: [2022-06-18 13:39:33,717: ERROR/ForkPoolWorker-1] Task taskMonitor.tasks.monitor[7e6696aa-d602-4336-a582-4c719f8d72df] raised unexpected: OperationalError(2000, 'Unknown MySQL error') Traceback (most recent call last): File "/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/.venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File "/.venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/.venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/.venv/lib/python3.9/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (2000, 'Unknown MySQL error') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/app/taskMonitor/tasks.py", line 18, in monitor for obj in objs.iterator(): File "/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 401, in _iterator yield from self._iterable_class( File "/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql( File "/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1361, in execute_sql cursor.execute(sql, params) File "/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in … -
ModuleNotFoundError: No module named 'rest_framework.simplejwt'
I'm trying to use simplejwt, but am getting a ModuleNotFoundError. Can you see what I'm doing wrong? requirements.txt algoliasearch-django>=2.0,<3.0 django>=4.0.0,<4.1.0 djangorestframework djangorestframework-simplejwt pyyaml requests django-cors-headers black isort settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # third party api services "algoliasearch_django", # third-party packages "rest_framework", "rest_framework.authtoken", "rest_framework.simplejwt", # internal apps "api", "products", "search", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", "api.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticatedOrReadOnly" ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10} SIMPLE_JWT = { "AUTH_HEADER_TYPES": ["Bearer"], "ACCESS_TOKEN_LIFETIME": datetime.timedelta(seconds=30), "REFRESH_TOKEN_LIFETIME": datetime.timedelta(minutes=1), } Full traceback: python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
How do I get the value of a field of a model instance using the instance's pk?
The following line of code correctly prints the id number of the specific model instance that I'm interested in: views.py print(self.kwargs['pk']) Great. But how do I get the value of a field in that model instance? The following is not working, because I think it's returning the default value listed in the model class and not the value in the model instance: instance_fieldname = self.kwargs.get(ModelName.fieldname) Hoping this is a simple fix. Thank you. -
Where is the Django Migrations model?
I wish to make a custom model, which has a foreign key relationship to the django_migrations table. Can this be done? if so, exactly how do I import the django migrations model? -
UndefinedTable: relation "user" does not exist
I am deploying a fresh new Django app on the server. The problem is when I migrate all the apps in the project. I'm getting UndefinedTable: relation "user" does not exist. Things I have done already: removed all the migrations from all the apps created a new database and new migrations and still getting that error. Weird scenarios: After deployment when I run the Django app locally on the server and hit API locally on the server using curl everything is working fine. like user sign up, but when I try to see in the database it is just empty (refer to the screenshot below). it doesn't even show columns for this user table, but for other tables, I can see columns as well. after migrations I am able to create super user but when I tried to login getting 500 error. and Undefined table relation user does not exit. Expection: AUTH_USER_MODEL = 'registration.User' models.py from django.db import models # Create your models here. import uuid from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils import timezone from .managers import CustomUserManager from rest_framework_simplejwt.tokens import RefreshToken AUTH_PROVIDERS = {'facebook': 'facebook', 'google': 'google', 'twitter': 'twitter', 'email': 'email'} … -
Resolving A Django Error on Form: Object has no attribute
Hi I'm trying to create a form that will when used update one model (Command_Node), and at the same time create an instance of another model (EC_NODE) that has a many to one relationship with the Command_Nodes. However when I go onto the update view and submit the form I'm getting the following error any ideas on how I can resolve this error? Thanks for any help you can offer. AttributeError at /website/update/1 'Beacon' object has no attribute 'EC_Node_set' Request Method: POST Request URL: http://127.0.0.1:8000/website/update/1 Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'Beacon' object has no attribute 'EC_Node_set' This on traceback points to command_form.EC_Node_set.all() # <- not sure with all _ and Maj here Which I can understand. I think my intention here should be clear enough. I want to set an instance of EC_Node to hold the command just put in via the form, and I understand the error. I just don't know how to get around it so that the view/form does what I want. Relevant views.py def update(request, host_id): host_id = Command_Node.objects.get(pk=host_id) form = Command_Form(request.POST or None, instance=host_id) if form.is_valid(): # Original suggestion was command_form = Command_Form.objects.first() command_form = form.cleaned_data['host_id'] command_form.EC_Node_set.all() # <- not sure with … -
While converting html to pdf using xhtml2pdf with django, the page is stuck in loading while I try to return a Http Response, how do I fix it?
While trying to return a named response with the below code so as to generate a pdf file, the browser is stuck loading, any suggestions on how to fix it def GeneratePdf(request): job = Job.objects.get(pk=id) products = Product.objects.all() supplies = job.jobItem.all() template_path = "company/jobDetails.html" context = { "job": job, "status": status, "supplies": supplies, } template = get_template(template_path) html = template.render(context) result = io.BytesIO() #Creating the pdf output = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') #output = pisa.CreatePDF(html, dest=response) if not output.err: pdf = HttpResponse(result.getvalue(), content_type='application/pdf') pdf['Content-Disposition'] = 'filename="products_report.pdf"' return pdf But when removing the part of pdf['Content-Disposition'] = 'filename="products_report.pdf"' as the code below the code works and I get a numbered file. def GeneratePdf(request): job = Job.objects.get(pk=id) products = Product.objects.all() supplies = job.jobItem.all() template_path = "company/jobDetails.html" context = { "job": job, "status": status, "supplies": supplies, } template = get_template(template_path) html = template.render(context) result = io.BytesIO() #Creating the pdf output = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') #output = pisa.CreatePDF(html, dest=response) if not output.err: pdf = HttpResponse(result.getvalue(), content_type='application/pdf') return pdf Any suggestions? -
django authenticate returns none but works fine in shell
def login_page(request): if request.method=='POST': user_name = request.POST.get('username') user_password = request.POST.get('password') user =authenticate(request,username=user_name,password=user_password) print(user) if user is not None: login(request,user) return redirect('/') else: messages.info(request,'Invalid user name or password') return redirect('/login_page') else: return render(request,'account/login_page.html') This is the code I'm using the authenticate function is returning none even for a valid input. I have tried authenticate in shell for same input and it is returning value as expected, so I don't understand ehy it is not working for values from HTML form. this is how i saved the user user = User.objects.create_user(email=email,first_name = firstname,last_name=lastname, username=username,password=password1) user.save() shell command i used (i have saved this user and using same credentials for authenticate) user_name = 'issue' user_password = '1234a' user =authenticate(request,username=user_name,password=user_password) this returns True on user is not None -
Media Streaming Servers for Django
I and my team are starting a project where in we are building a scalable live streaming platform just like Youtube. We are using Django as the backend framework. Which is the best media streaming library/server that can be used to achieve the result(It should work along the django project)? Previous Attempts : We researched about various media streaming servers and shortlisted the following three(based on our requirements that it should be able to scale up to a commercial level): Ngnix RTMP module https://github.com/arut/nginx-rtmp-module/ Node Media Server https://github.com/illuspas/Node-Media-Server Django Channels https://channels.readthedocs.io/en/stable/ We are struggling to decide which one to use for our project. I have seen a lot of people use Django channels with django to deal with such projects. But one of my teammates had a bad experience with django channels while working on a similar project hence he is advising us not to go with it. Ngnix module is attractive and a really good reputation on github but I didn't understand it well. We are very doubtful of Node Media server, no positive reviews nor negative reviews. Can you please suggest a better option maybe among them or a different one? Thank you! Any suggestions are welcome. -
Why python3 manage.py runserver built-in command also runs my custom commands?
app_name is added INSTALLED_APPS = [] and in my path /app_name/management/commands/custom.py from django.core.management.base import BaseCommand import server class Command(BaseCommand): def handle(self, *args, **kwargs): server.start() i runned python3 manage.py custom.py it runned the code in my server file fine but now when i run : python3 manage.py runserver on the console activity i can see that python3 manage.py custom.py is automatically called within runserver command -
How to update the user profile of a different user if you are logged in as the owner?
Currently, I am logged in as an owner and I want to update the fields of customers in the database. But the form does not update or show the details as a placeholder because the user model has extended the customer model and hence, the customer model does not have its own fields. How do I get the instance of the User of the Customer in the UpdateView?/How do I update the customer? views.py class CustomerUpdateView(OwnerAndLoginRequiredMixin, generic.UpdateView): template_name = "customer_update.html" form_class = CustomerModelForm queryset = Customer.objects.all() def get_success_url(self): return "/customers" models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class User(AbstractUser): is_owner = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) forms.py class CustomerModelForm(forms.ModelForm): class Meta: model = User fields = ( 'email', 'username', 'first_name', 'last_name', ) -
Django: Accessing full User information via ManyToMany field
everyone- I'm new to Django and working on my first big project and I'm having trouble with accessing default Django User model information via a ManyToMany relationship. I've spent a great deal of time searching and can't crack it. models.py class Event(models.Model): event_name = models.CharField(max_length=200, null=True, unique=True) #etc... class School(models.Model): user = models.ManyToManyField(User) event = models.ForeignKey(Event, null=True, on_delete=models.PROTECT) #etc... My url contains the id of the Event, so... views.py def schools(request, pk): event = Event.objects.get(id=pk) school = School.objects.filter(event=event) return render(request, 'accounts/schools.html', {'event':event, 'school':school}) template {% for school in school %} <tr> <td>{{school.name}}</td> <td>{{school.user.all}}</td> {% endfor %} On my template, I'm able to use {{school.user.all}} to get me a Queryset displayed with the username of each User, but I want the first_name and last_name and can't see to figure out how to get that.. Thank you for any suggestions. I greatly appreciate your time! -
How to customize the toolbar of Summernote in django admin
I just need the link button of the summernote. How is this toolbar edited? I tried the documentation and felt no proper guiding. -
cant use emojionearea in django
I cant use emojionearea in a simple page in django, i have followed the basics steps, listed in their website: what i have done: 1.downloaded the zip from their github and copied both of these files into css and js folder 2.configure django static settings e.g add to url, add static dir, add url pattern 3.added the script written above. code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TODO</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/emojionearea.min.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> <body> {% include 'navbar.html' %} {% block content %} {% endblock content %} <script> $(document).ready(function() { $("#mytextarea").emojioneArea(); }) </script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="{% static 'js/emojionearea.min.js' %}"></script> </body> </html> and this is the form text area i want to add the emoji to: {% csrf_token %} <div class="form-row"> <div class="col-12"> <label for="inputTask">Tweet:</label> <textarea class="form-control" placeholder="Enter Tweet:" name="tweet" id="mytextarea"></textarea> </div> <div class="col-10"> <label for="inputTime">Image:</label> <input type="file" class="form-control" placeholder="select image:" name="images"> </div> <div class="col-2" style="margin-top: 35px;"> <button type="submit" class="btn btn-outline-primary float-right">Add Tweet</button> </div> </div> </form> i have also tried putting textarea … -
Django: How to unable unlogged user get data other users but enable him have his own data linked to his session
I'm working on simple django project. In this project every reuser has his own data collection as usual we do in our projects but I want to enable unlogged users to have his own data linked with particular session. Off course their data are deleted when session expired but this is the cost of not being registered. I want to block possibility for unlogged user to get data of registered users by typing direct url. All tutorials i have found are obout @login_required decorator but it works only for registered users and doesn't let unlogged users to have his own temporary data. Maybe somebady can help my , give my a hint or suggestion where i can find something useful to solve this problem. Thanks for help -
BaseSerializer.__init__() got multiple values for argument 'instance'
I am new to Django so I have used serializer for the CRUD operations,but this error has come here's my function: def updateemp(request,id): Updateemp = EmpModel.objects.get(id=id) form = CRUDSerializer (request.POST,instance=Updateemp) if form.is_valid(): form.save() messages.success(request,'Record Updated Successfully...!:)') return render(request,'Edit.html',{"EmpModel":Updateemp}) can someone tell me the solution? -
Call ajax of `django-restframework` api from template and the server checks who calls this api
I use google auth login in django project with django-oauth-toolkit What I want to do is Call ajax of django-restframework api from template and the server checks who calls this api. For example, I can get if user is login or not {% if user.is_authenticated %} in template. so, I can call the api with the user information like this. var url = "http://localhost/api/check?id={{user.email}}" $.ajax({ method:"get", url:url .... with id query server can understand who calls this request. However in this method,id is written barely, so you can make the fake request. So, I guess I should make some access token or some other key. Is there any general practice for this purpose???