Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'LOCATION' expected a number but got <LOCATION: LOCATION object (71)>
I have foreign key LOCATION in LOCATION table to get the Location value in another table, i got the error json_object is my input, item is another table Code=item["LOCATION"]=LOCATION.objects.get(LOCATION = json_object["LOCATION"]) error=Field 'LOCATION' expected a number but got <LOCATION: LOCATION object (71)>. -
Getting (NoReverseMatch at / Reverse for 'chatpage' with no arguments not found. 1 pattern(s) tried: ['ChatView/(?P<uname>[^/]+)\\Z'] after login
I know this question had been asked for more than five times but I had tried many solutions as a noob and still weren't able to find out the solution. I had been following the django-channels documentation and instead of room-name I want to display username in the URL but when I try as per instructions this error occurred. This is the image of error. Image of error when I run it on Mozilla firefox and this is what it is saying in terminal Image of error in terminal and this is the line of chatpage urls.py line which is I am trying to display with username path('ChatView/<str:uname>', login_required(views.ChatView.as_view()), name="chatpage"), and this is the line of views.py for chatpage. class ChatView(View): def get(request, username): uname = User.objects.get(username=username) return render(request, 'chatbot/chatPage.html', { 'uname': uname }, context_instance=RequestContext(request)) and this is the Html code that I use for username input: <input class="w-full text-lg py-2 border-b border-gray-300 focus:outline-none focus:border-indigo-500" type="text" placeholder="Enter Your Username" id="username" name="username" value="{{data.username}}" Required> These are the four links of pastebin for whole code: views.py urls.py chatpage.html signin.html -
Complicated Neted Admin Inline
I have a complicated model, where playlists can be created on two levels: UserGroup and User. Further, these playlists are targeted to a specific weekday. So Users/UserGroups can have separate playlists for each day of the week. To manage the user playlists in the admin, I'm looking to add the User and UserGroup an inline of all weekdays, and under each weekday the inline of all songs (for that weekday). Hopefully the image below will clear this up a bit. To add to the confusion, the songs per a specific weekday should include both User songs and also UserGroup songs. My models: UserGroup name = models.CharField(max_length=255) User name = models.CharField(max_length=255) UserGroupSong file = models.FileField() weekday = models.ForeignKey(Weekday, on_delete=models.PROTECT) user_group = models.ForeignKey(UserGroup, on_delete=models.PROTECT) UserSong file = models.FileField() weekday = models.ForeignKey(Weekday, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) inherit = models.BooleanField(verbose_name='Include songs from user-group for this weekday?') class Weekday(models.Model): day = models.CharField(max_length=255) # Pre-populated with values: Sun, Mon, Tue, Wed, Thu, Fri, Sat Any help will be greatly appreciated. -
How to insert value in a forign key from the csv file
I want to insert the Matches and Delivery table from matches.csv and delivery.csv in the Django database. models.py looks like this: from django.db import models # Create your models here. class Matches(models.Model): id=models.IntegerField(primary_key=True) season = models.IntegerField() city = models.CharField(max_length=200) date = models.DateField(null=True) team1 = models.CharField(max_length=200) team2 = models.CharField(max_length=200) toss_winner = models.CharField(max_length=200,null=True) toss_decision = models.CharField(max_length=200,null=True) result = models.CharField(max_length=200,null=True) dl_applied = models.CharField(max_length=200,null=True) winner = models.CharField(max_length=200,null=True) win_by_runs = models.IntegerField(null=True) win_by_wickets = models.IntegerField(null=True) player_of_match = models.CharField(max_length=200,null=True) venue = models.CharField(max_length=200,null=True) umpire1 = models.CharField(max_length=200,null=True) umpire2 = models.CharField(max_length=200,null=True) umpire3 = models.CharField(max_length=200,null=True) class Deliveries(models.Model): match_id= models.ForeignKey(Matches,on_delete=models.CASCADE) inning = models.IntegerField() batting_team = models.CharField(max_length=100) bowling_team = models.CharField(max_length=100) over = models.IntegerField() ball = models.IntegerField() batsman = models.CharField(max_length=100) non_striker = models.CharField(max_length=100) bowler = models.CharField(max_length=100) is_super_over = models.IntegerField() wide_runs = models.IntegerField() bye_runs = models.IntegerField() legbye_runs = models.IntegerField() noball_runs = models.IntegerField() penalty_runs = models.IntegerField() batsman_runs = models.IntegerField() extra_runs = models.IntegerField() total_runs = models.IntegerField() player_dismissed = models.CharField(max_length=100) dismissal_kind = models.CharField(max_length=100) fielder =models.CharField(max_length=100) I am updating this table using management/commands/updateModels.py and my updateModles.py looks like this:django from django.core.management.base import BaseCommand import csv from match.models import Matches, Deliveries class Command(BaseCommand): help = 'import booms' def add_arguments(self, parser): pass def handle(self, *args, **options): # database connections here with open('matches.csv') as f: match_obj = csv.DictReader(f) for match in match_obj: … -
How to read from Form Data on Django view?
I need to read data from "Form-Data" on Django 3.2, how to do it on a view? Thank you -
Forbidden (CSRF token missing or incorrect.): /api/token/refresh/
When using the @csrf_protect decorator in the view, I encountered the error "Forbidden (CSRF token missing or incorrect): /api/token/refresh/" views.py @api_view(['POST']) @renderer_classes([CustomizeJSONRenderer]) @csrf_protect def refresh_token_view(request): refresh_token = request.COOKIES.get('refreshtoken') # check valid refresh token if refresh_token is None: raise exceptions.AuthenticationFailed('Authentication credentials were not provided, please login.') try: payload = jwt.decode(refresh_token, settings.REFRESH_TOKEN_SECRET, algorithms=['HS256']) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('expired refresh token, please login again.') user = User.objects.filter(id=payload.get('user_id')).first() # check valid user if user is None: raise exceptions.AuthenticationFailed('user not found.') if not user.is_active: raise exceptions.AuthenticationFailed('user is inactive.') access_token = generate_access_token(user) # create new access token return Response({'access_token': access_token}) -
Please help me, I am unable to update my note taking app api using CRUD
This is the tools.py from .models import Note from .serializers import NoteSerializer from rest_framework.response import Response from django.shortcuts import get_object_or_404 def getNoteslist(request): notes=Note.objects.all().order_by('-updated') serializer=NoteSerializer(notes, many=True) return Response(serializer.data) def NoteDetail(request, pk): notedetail=get_object_or_404(Note,id=pk) serializer=NoteSerializer(notedetail, many=False) return Response(serializer.data) def createNote(request): data=request.data note=Note.objects.create( title=data['title'], body=data['body'] ) serializer=NoteSerializer(note, many=False) return Response(serializer.data) def updateNote(request, pk): note=Note.objects.get(id=pk) serializer=NoteSerializer(instance=note, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) def delete(request, pk): note=get_object_or_404(Note,id=pk) note.delete() return Response('Note is deleted!') This is the views.py from .models import Note from .tools import getNoteslist,NoteDetail,updateNote,createNote,delete from rest_framework.decorators import api_view @api_view(['GET']) def getNotes(request): return getNoteslist(request) @api_view(['POST']) def createNotes(request): return createNote(request) @api_view(['GET']) def getNote(request,pk): return NoteDetail(request, pk) @api_view(['POST']) def updateNote(request, pk): return updateNote(request, pk) @api_view(['DELETE']) def delNote(request, pk): return delete(request, pk) This is the urls.py from django.urls import path from . import views from rest_framework.documentation import include_docs_urls from rest_framework_swagger.views import get_swagger_view schema_view=get_swagger_view(title='NOTE TAKING APi') API_TITLE='NOTE TAKING APi' API_DESCRIPTION='A note taking API for creating and editing notes.' urlpatterns=[ path('',views.getNotes,name='Notes'), path('create/',views.createNotes,name='Notes'), path('<int:pk>/',views.getNote,name='note'), path('update/<int:pk>/',views.updateNote,name='note'), path('delete/<int:pk>/',views.delNote,name='note'), path('docs/',include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)), path('swagger-docs/',schema_view) ] here is the error: **Internal Server Error: /Note/update/4/ Traceback (most recent call last): File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
Django: overwriting the method model of the abstract model, from inside the inherited models
I have a problem with re-assigning some var in my model, I have a model like this: class ExpireTime(models.Model): """Expire time fields and methods in abstract mode""" def expire_time(): return create_expire_time(seconds=10) expire = models.DateTimeField(default=expire_time) def is_expired(self) -> bool: return self.expire < timezone.now() class Meta: abstract = True but in the different models that used this abstract model, I need the use different expiration times in the exprie_time: def expire_time(): return create_expire_time(seconds=10) so I am trying to overwrite this method in the model that was inherited from ExpireTime but it has no effect. so how can I solve this situation? Should I not use the abstract model in this situation? -
How to update a users account balance on purchase in a Django View?
For a side project I'm working on creating a simulated cryptocurrency exchange application. For the first part of this I'm just creating a simple page where the users can buy and sell BTC for USD and it will update their respective balances for each one. I have created a form for the 'Trade' and there's two model tables - 'Trade' and 'Portfolio. How do I set this up so when a 'Trade' takes place, it updates the amount of tokens (when buying) or the amount of USD (when selling) in the 'Portfolio', and if it doesn't exist it creates a new entry? models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Trade(models.Model): token_name = models.CharField(max_length=100) token_symbol = models.CharField(max_length=10) date = models.DateTimeField(default=timezone.now) account = models.ForeignKey(User, on_delete=models.CASCADE, related_name='trader') amount = models.FloatField() price = models.FloatField() type = models.CharField(max_length=15, choices=( ("Market Buy", "Market Buy"), ("Market Sell", "Market Sell"))) def id(self): return id(self.id) class Portfolio(models.Model): token_name = models.CharField(max_length=100, unique=True, default="United States Dollar") token_symbol = models.CharField(max_length=10, default="USD") account = models.ForeignKey(User, on_delete=models.CASCADE, related_name='portfolio') amount_holding = models.FloatField(default="100000") def id(self): return id(self.id) Views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Trade from .models import Portfolio from django.contrib import messages from … -
ValueError: Cannot assign "1": "User.jsgGroupName" must be a "JsgGroup" instance
I am getting ValueError: Cannot assign "1": "User.jsgGroupName" must be a "JsgGroup" instance. this error when using a foreign key in a custom user model. I guess there is some problem with the Foreign Key. There is no proper solution for django rest framework based app and I am using drf. models.py from django.db import models from django.contrib.auth.models import User, AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils.translation import gettext_lazy as _ from django.utils import timezone class Region(models.Model): RegionName = models.CharField(max_length=20) numGroups = models.IntegerField(default=0) def __str__(self): return self.RegionName class Group(models.Model): GroupName = models.CharField(max_length=20) id = models.IntegerField(primary_key=True, editable=True) Region = models.ForeignKey( Region, on_delete=models.CASCADE, related_name="groups", null=True, blank=True) def __str__(self): return self.GroupName class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True, editable=False) username = models.CharField( max_length=20, null=True, blank=True, unique=True) email = models.EmailField(_('email address'), unique=True) GroupName = models.ForeignKey( Group, on_delete=models.CASCADE, related_name="groupUser", null=True, blank=True) RegionName = models.ForeignKey( Region, on_delete=models.CASCADE, related_name="regionUser", null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField( auto_now_add=True, null=True, blank=True) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'GroupName','RegionName', ] def __str__(self): return self.username -
Is there something wrong with the installation?
After running the Django server, I created a file 'exo2' importing "ex01" and "exo1". When dragging and dropping the "ex01" into the .config on the left explorer, the message in the image below never pops up: poto>>"Python extensions want to make refactoring changes with this file move." I wantenter image description here this message to appear. Is there something wrong with the installation? -
Uncaught SyntaxError: Identifier 'agregar' has already been declared
I have a question regarding an error occurred when trying to place a script within a for of an html Code form: <form action="{% url 'carts:add' %}" method="post"> {% csrf_token %} <input type="hidden" name="product_id" value="{{ p.idProducto}}"> <div class="" style="text-align: center"> <button type="button" class="btn btn-info d-inline" id="eliminar">-</button> <input type="number" value="1" class="form-control col-sm-1 d-inline" style="width : 60px" id="cantidad" name="cantidad" readonly> <button type="button" class="btn btn-info d-inline" id="agregar">+</button> </div> <div class="mt-2" style="text-align: center"> <button type="submit" class="btn btn-warning">Agregar al carrito</button> </div> </form> <script> const agregar = document.getElementById('agregar') const eliminar = document.getElementById('eliminar') const cantidad = document.getElementById('cantidad') agregar.addEventListener('click', function () { cantidad.value = parseInt(cantidad.value) + 1 }) eliminar.addEventListener('click', function () { value = parseInt(cantidad.value) if(value != 1){ value = value - 1 } cantidad.value = value }) </script> When selecting a product it works, but when I try to add quantity to the second it tells me this error Uncaught SyntaxError: Identifier 'agregar' has already been declared (at (index):210:9) And that error is in the first code I insert but I don't know much about the subject to see that it's wrong -
Cant access models instance from django template
[enter image description here][1] .imgu****strong text**r.com/Icm1u.png -
Updating data in django without Form
I am doing CRUD operation without Form. I want to update my data by its id. My data is updating but getting data in extra backets like this response: {'customer_id': 2, 'customer_name': "('Shweta',)", 'pin': "('400456',)", 'city': "('DSAA',)", 'state': "('Maharashtra',)", 'country': "('India',)", 'customer_address': "('India',)", 'contact_person_name': "('8097998823',)", 'phone': "('7418529634',)", 'email': "('info.technicrafts@gmail.com',)", 'GST': "('741852',)", 'bill_to': "('Thane',)", 'ship_to': "('Thane',)", 'remarks': "('NA',)"} views.py def updateCustomer(request,id): customer=Customer.objects.get(pk=id) response = model_to_dict(customer) print ("response:" , response) if request.method == "POST": # customer_id= request.POST['customer_id'], customer_name= request.POST['customer_name'], pin= request.POST['pin'], city= request.POST['city'], state= request.POST['state'], country= request.POST['country'], customer_address= request.POST['customer_address'], contact_person_name= request.POST['contact_person_name'], phone= request.POST['phone'], email= request.POST['email'], gst= request.POST['GST'], bill_to= request.POST['bill_to'], ship_to= request.POST['ship_to'], remarks= request.POST['remarks'], update_customer=Customer.objects.filter(customer_id=id).update(customer_name=customer_name,pin=pin,city=city,state=state,country=country,customer_address=customer_address,contact_person_name=contact_person_name,phone=phone,email=email,GST=gst,bill_to=bill_to,ship_to=ship_to,remarks=remarks) print("update query set: ",update_customer) return render(request,"customers/update-customer.html",{"customer":response}) urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('view-customers', views.viewCustomers, name="view-customers"), path('add-customers', views.addCustomers, name="customers"), path('get-customers', views.getCustomers, name="get-customers"), # path('update-customers', views.updateCustomer, name="update-customers"), path('delete/<int:id>/',views.deleteCustomer, name="delete-customers"), path('update/<int:id>/',views.updateCustomer, name="update-customers"), ] html <form method="post" > {% csrf_token %} <div class="row pb-2 pt-3"> <div class="col-sm mb-2"> <input type="text" class="form-control" name="customer_id" placeholder="Customer Id" value="{{customer.customer_id}}"> </div> <div class="col-sm mb-2"> <input type="text" class="form-control" name="customer_name" placeholder="Customer Name" value="{{customer.customer_name}}"> </div> <div class="col-sm mb-2"> <input type="text" class="form-control" name="pin" placeholder="Pin" value="{{customer.pin}}"> </div> <div class="col-sm mb-2"> <input type="text" class="form-control" name="state" placeholder="State" value="{{customer.state}}"> </div> </div> <div class="row pb-2"> <div … -
Default value and empty_label=None in ModelChoiceField don't work together (Django)
I have been trying to set a default value on a ModelChoiceField for days and it just will not work (this is a form which the user can edit after creating it).. here is my code: views.py @login_required(login_url='/admin/login') def edit_keydef(request, id): data = {'title': 'View or Edit Key Definition'} template = 'generate_keys/edit_keydef.html' keydef = get_object_or_404(KeyDefinition, pk=id) if request.method == "POST": keydetails_form_instance = KeyDefDetailsForm(request.POST, instance=keydef) if 'Save' in request.POST: # stuff that saves the edited form. if 'Generate' in request.POST: # stuff that generates a key for the user else: keydetails_form_instance = None if not id: keydetails_form_instance = KeyDefDetailsForm() else: # Retrieve a previously saved form. try: keydetails = KeyDefinition.objects.get(pk=id) keydetails_form_instance = KeyDefDetailsForm(keydetails.to_dict(), instance = keydetails) except KeyDefinition.DoesNotExist as e: return redirect('/record_does_not_exist') # Form instance has been saved at this stage so update the variant list. keydetails_form_instance.update_variants(keydef) keydetails_form_instance.update_available_hosts(keydef) data['form'] = keydetails_form_instance data['set_product_options_url'] = reverse_lazy('set_product_options', kwargs={'id':id}) return render(request, template, data) forms.py class KeyDefDetailsForm (ModelForm) : def __init__(self, *args, **kwargs) : super(ModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.fields['version'].widget.attrs['class'] = "major_minor" self.fields['available_hosts'].default = self.fields['host_label'] def update_variants(self, keydef_obj): # some code that updates the feature_variant field def update_available_hosts(self, keydef_obj): print(keydef_obj.host_label) # only show hosts that have been created by this user self.fields.update({ … -
Having trouble with syntax of Serializer in CRUD task with foreign keys
so I am having a CRUD project with categories sub categories color size as foreign keys. where I am unable to see the data that I have attempting to insert. class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) show and insert functions def show(request): showall = Products.objects.filter(isactive=True) print("show all data:",showall) serializer = POLLSerializer(showall,many=True) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.method == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size ') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') print("insert clothes:",insert_clothes) serializer = POLLSerializer(data = insert_clothes) print('form:',serializer.initial_data) if serializer.is_valid(): serializer.save() messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print("invalid") print("error of serializer:",serializer.errors) return redirect('polls:insert') else: print('GET',id) return render(request,'polls/product_insert.html') the error coming is : "{'categories': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]" can someone tell me where I am going wrong in the syntax? -
Setting a FileFIeld to an existing file in media - path error
I have a form in which the user uploads a file, which I save directly to the MEDIA_ROOT and do some transformations on. Afterwards I want to save it to a FileField in a model. Here's the function that handles the file. (it's called from the view that contains the form process(request.FILES['track'])) from .models import Track from django.conf import settings import os def process(f): fname = str(uuid.uuid4())+ '.' + str(f).rsplit('.', 1)[1] fullPath = os.path.join(settings.MEDIA_ROOT, 'tracks', fname) with open(fullPath, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) #PROCESS THE FILE (abridged) instance = Track( title = str(f), ) instance.file.name = f"/tracks/{fname.rsplit('.', 1)[0]}.mp3" instance.save() print("******************") print(instance.file) print(instance.file.url) print(instance.file.storage.location) print(instance.file.path) #print(instance.file.storage.location) return (True, {"trackId" : instance.id}) I am following this answer for setting the name property of the FileField (which is called file), since I already have it ready, I don't really want to read/save it again as the django docs suggest. Now I can mostly use the FileField, but when I try to get the absolute path, it throws an error (here's the output of the print statements) ****************** /tracks/7d90c385-8f74-4b44-a376-5335069372d3.mp3 /media/tracks/7d90c385-8f74-4b44-a376-5335069372d3.mp3 D:\prog\proj\music_web\media The joined path (D:\tracks\7d90c385-8f74-4b44-a376-5335069372d3.mp3) is located outside of the base path component (D:\prog\proj\music_web\media) I checked how the path is supposed … -
Django: How to have a UniqueConstraint across fields in multiple models?
In Django 3.2, can I use the UniqueConstraint feature to enforce uniqueness across multiple models, and can you show me how? I want to add an optional ID field for three models that is unique across all of them. This way, when I get that ID from a URL parameter, I can be sure which model type was requested. For my IDs I have 8 alphanumeric characters to play with. If UniqueConstraints across models is a stupid idea please tell me, because I can just reserve one of my 8 characters for model type identification. -
CSRF verification failed. Request aborted when doing GET
I am doing on Django 3.2 on my template the following <a "href"="https:localhost..."/> to obtain an XML. It retrieves a CSRF error 403 Forbidden, but I don't understand WHY, because I am not doing a POST and I cannot add CSRF_TOKEN on <a "href"..../> how to fix it? thanks in advance. (I cannot deactivate CSRFMiddleware) Regards -
How to translate attached something.inc(php included file) to python?
I got an file which is php included. It needs to be translate to python and how to handle post request on it? -
How do I get an image from user and process it in the backend using django?
Im trying to send the image from the user input to the backend of my app but I don't know how to do it. -
Django Models choices opitions
For example, I have two answer option in the model field: "yes", "no". class Card(models.Model): INSTANCE_CHOICES = ( ('1', 'Yes'), ('2', 'No'), ) instance = models.CharField(max_length=1, choices=INSTANCE_CHOICES, default='DEFAULT VALUE') If in admin area I choose option 1 I will want to continue working with the model "Positive", otherwise I will want to continue my work with model "Negative". How to do it? -
Django Forbidden (403) CSRF verification failed. Request aborted
So I did a deployment to my project and after I got HTTPS to my web, Django shows me this error now: it happens after my login page: login.html {% load i18n static bootstrap4 %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'web_site/css/login.css' %}" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="{% static 'web_site/js/login.js' %}"></script> </head> <body> <div class="wrapper"> <div class="container"> <h1>Welcome</h1> {% if context %} <ul class="messages"> <li class="error">{{ context }}</li> </ul> {% endif %} <form class="form" action="" method="post"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" id="login-button">Login</button> </form> </div> <ul class="bg-bubbles"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body> </html> In my views.py i already have: return render(request, "web_site\my_profile.html", {"cool": p}) and after form tad the csrf_token my views.py: from django import template from django.contrib import messages from django.contrib.auth import authenticate from django.contrib.auth import login as auth_login from django.contrib.auth.decorators import login_required from django.contrib.auth.models import ContentType, Permission, User from django.shortcuts import render from django.urls import resolve from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import FileForm class HomeView(LoginRequiredMixin, TemplateView): template_name = "web_site/home.html" @login_required def profile(request): p = Permission.objects.filter(user=request.user) return render(request, "web_site\my_profile.html", {"cool": p}) def upload_file(request): if request.method == "POST": form = … -
[ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]
I am doing shopping CRUD with model Products with Categories,sub categories,color,size as foreign keys using serializers because I am told to use foreign keys and serailizers.the problem is that the data that I am trying to insert isnt coming in the show page the below error is what comes: "error of serializer: {'categories': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')], 'sub_categories': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')], 'color': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')], 'size': [ErrorDetail(string='This field may not be null.', code='null')]}" below is the model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) show and insert functions def show(request): showall = Products.objects.filter(isactive=True) print("wghj",showall) serializer = POLLSerializer(showall,many=True) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.method == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size ') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') print("insert clothes:",insert_clothes) serializer = POLLSerializer(data = insert_clothes) print('form:',serializer.initial_data) if serializer.is_valid(): serializer.save() messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print("invalid") print("error of serializer:",serializer.errors) return redirect('polls:insert') else: print('GET',id) return render(request,'polls/product_insert.html') show page <td><b>{{result.categories}}</b></td> <td><b>{{result.sub_categories}}</b></td> <td><b>{{result.color}}</b></td> <td><b>{{result.size}}</b></td> … -
Django token not valid
I'm trying to create a process to verify a users email before changing it. However, the token keeps getting invalidated. Any help? The views: def _send_verification_email(user=None,email=None,request=None): current_site = get_current_site(request) message = render_to_string('emails/email_verification.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), 'email':urlsafe_base64_encode(force_bytes(email)), 'email_unencoded':email, }) user.send_email(mail_subject='Verify your email address', message=message) def verify_changed_email(request,uidb64=None,token=None,email=None): try: uid = urlsafe_base64_decode(uidb64).decode() user = Account.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, Account.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): email = urlsafe_base64_decode(email).decode() user.email = email user.save() auth.login(request, user) messages.success(request, 'Your email has been changed.') return redirect('/') else: messages.error(request, 'An error has occurred. This link is not valid.') return redirect('/') Form validation, this works. if form.is_valid() and account_settings_form.is_valid(): self.object = form.save() try: user = Account.objects.get(id=self.request.user.id) if account_settings_form.instance.email != user.email: _send_verification_email(email=account_settings_form.instance.email, user=user, request=self.request) account_settings_form.instance.email = user.email messages.success(self.request,'We sent you an e-mail for further verification!') account_settings_form.save() except ValueError as e: messages.error(self.request, e) return self.render_to_response(self.get_context_data(form=form)) The URL in email, and urlpatterns http://{{domain}}{% url 'accounts:verify_changed_email' uidb64=uid token=token email=email %} path('change-email/<uidb64>/<email>/<token>/',account_views.verify_changed_email,name='verify_changed_email'), It keeps failing this check, the token keeps getting invalidated: if user is not None and default_token_generator.check_token(user, token): Any idea why it keeps failing? What the solution might be?