Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert an image to `InMemoryUploadedFile` when an URL of the image is received in DRF?
I have a response where the image URL is displayed, but when I try to send PUT/PATCH request then it raises an error as:- Here's the response:- { "floorplan": { "floor": 32, "image": "http://127.0.0.1:8000/media/floorplans/71d3e751-d38f-416f-ac22-d6ddb3fa3541.jpg" } } When A PUT request is sent:- { "floorplan": { "image": [ "The submitted data was not a file. Check the encoding type on the form." ] } } But when I try to send a request with an actual image uploaded, it works fine. This my serializer:- class NestedFloorplanSerializer(serializers.ModelSerializer): class Meta: model = FloorPlan fields = ( 'floor', 'image', ) I tried override the to_internal_value what is saw was in actual image is uploaded it is of the type:- <InMemoryUploadedFile: floor_1.jpg (image/jpeg)> and when the url is sent than the value I see in the to_internal_value is this http://127.0.0.1:8000/media/floorplans/71d3e751-d38f-416f-ac22-d6ddb3fa3541.jpg What I am trying to do is not do the validation when the the same url of the image is received in the to internal_value or if possible to convert the url to <InMemoryUploadedFile: floor_1.jpg (image/jpeg)> and then return it?? -
Django and postgres timezone converts to UTC
In my app users provide their timezone and saved. So I handle timezone conversion manually local_time = datetime.now(tz=ZoneInfo(self.time_zone)) Yet still when I save into postgres it is converted back to UTC 0. In the settings: # TIME_ZONE = 'UTC' #commented out USE_L10N = False USE_TZ = False That too did not work, so I made a middleware: # CUSTOM TIME ZONE HANDLER class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): time_zone = "US/Pacific" #will be changed to a fn call if time_zone: timezone.activate(pytz.timezone(time_zone)) else: timezone.deactivate() return self.get_response(request) In settings: MIDDLEWARE = [ ... 'time_log_app.utils.TimezoneMiddleware', ] That too is not working!! I'm pretty much out of hope here, what I'm doing wrong?? Or I should use raw sql for this? -
Achievements in Django
I would like to add the achievements to my website. I would like them not to be assigned automatically, but that the user would add which achievements he made. I can't make a view for it. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Achievement(models.Model): title = models.CharField(max_length=200, null=True) grand = models.IntegerField(default=10, null=True) body = models.TextField() class UserAchievement(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) user_achievement = models.ManyToManyField(Achievement, related_name='user_achievement') achievement_get = models.DateTimeField(auto_now_add=True) vievs.py def achievement_view(request): achievement_list = Achievement.objects.order_by() return render(request, 'achievement/achievement.html', { 'achievement_list' : achievement_list, }) def achievement_get(request, achievement_id): achievement_list = get_object_or_404(Achievement, pk=achievement_id) achi = get_object_or_404(Achievement, pk=achievement_id) try: selected_choice = achievement_list.score_set.get(pk=request.POST['choice']) except (KeyError, Score.DoesNotExist): # Redisplay the question voting form. return render(request, 'achievement/adetail.html', { 'achievement_list': achievement_list, 'error_message': "You didn't select a choice.", 'thanks' : "Good", }) else: a1 = get_object_or_404(Achievement, achievement_id) a1.save() a1.user_achievement.add(name=name) return render(request, 'achievement/adetail.html', { 'achievement_list' : achievement_list, }) urls.py app_name = 'achievement' # przestrzeń nazw aplikacji urlpatterns = [ # ex: /polls/ path('achievement', views.achievement_view, name='achievement'), path('<int:achievement_id>/achievement', views.achievement_get, name='achievement_get'), ] achievement.html {% for achievement in achievement_list %} <li>{{ achievement.title }}</li> <li><fieldset><a href="/{{achievement_id}}/achievement/"> {{ achievement.title }} {{ achievement.grand }}</a></fieldset></li> {% endfor %} When I click on the link, the <int: achievement_id> … -
HTML body content is blocking Nav
Currently working on my first webpage with HTML, CSS, Django and maybe Javascript soon :) My issue is that I've added some images into my main content to test all(Wanted to add a sticky nav) but the main content is somehow overlapping my NAV and i'm not able to click the links of the Nav itself anymore. Inspector where we can see clearly the overlap. HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static '/css/design.css' %}" /> </head> <body> <!--NAVBAR--> <div class="navbar"> <div class="navbar-title"> <a href="{% url 'photos:home' %}">site-name</a> </div> <div class="navbar-links"> <a href="{% url 'photos:home' %}">HOME</a> <a href="{% url 'photos:pictures' %}">PICTURES</a> <a href="{% url 'photos:album' %}">ALBUM</a> </div> </div> <div class="main-content"> <img src="{% static '/img/1.jpg' %}"> <img src="{% static '/img/1.jpg' %}"> <img src="{% static '/img/1.jpg' %}"> <img src="{% static '/img/1.jpg' %}"> <img src="{% static '/img/1.jpg' %}"> </div> {% block content %}{% endblock %} </body> </html> CSS: body { background-color: #171717; font-family: Helvetica; } /*------------------NAVBAR------------------*/ .navbar, a { color: #FFF; text-decoration: none; font-size: large; margin: 10px; } .navbar-title { float: left; text-align: center; display: block; position: relative; padding-left: 50px; padding-top: 25px; font-style: italic; } .navbar-links { float: right; text-align: center; display: … -
Django form does not work or CSRF_token aborted
Hello I am making Django App. I have a problem with my login form. Whenever I want to login, form does not do anything or it throws csrf token error. Views: def loginView(request): if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f"You successfully logged in {username}") return redirect('home-page') else: form = AuthenticationForm() return render(request, 'shop/login.html', {'form': form}) HTML TEMPLATE: {% extends 'shop/base.html' %} {% block content %} <div class = "form-container"> <form class="form" method="POST">{% csrf_token %} <label for="username">Email:</label> {{form.username}} <label for="password">Passoword:</label> {{form.password}} <button type="submit">Login</button> </form> </div> {% endblock content %} -
Django request.post only contains csrf field, however my form has two inputs: username and password, therefore i can not authenticate and login a user
I am trying to create a login page for my website,i am using bootstrap as css and here is my template below {% extends 'base_lean.html' %} {% block content %} <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="username">Kullanici Adi</label> <input type="text" class="form-control" id="username" placeholder="Kullanici Adinizi Giriniz"> <small id="username-help" class="form-text text-muted">Siteye kayit olduğunuz kullanici adi ile giriş yapınız</small> </div> <div class="form-group"> <label for="password">Şifre</label> <input type="password" class="form-control" id="password" placeholder="Şifreniz"> </div> <button type="submit" class="btn btn-primary">Giriş Yap</button> </form> {% endblock %} In the login screen im posting some username and password data in the input fields however my request.POST only returns: {'csrfmiddlewaretoken':[blablabla]} Therefore i can not authenticate and login users, what is the reason behind that my request.POST does not have form's username and password fields? -
How to deal with a serializer that needs context
I have a situation here where the serializer needs context, basically the request object. class ProductSerializer(ModelSerializer): distance_away = SerializerMethodField(read_only=True) class Meta: model = Product fields = [ 'pk', 'distance_away', ] def get_distance_away(self, obj): coordinates = self.context["coordinates"] distance_in_km = None if coordinates != 'null' and coordinates is not None: lat = float(tuple(coordinates.split(","))[0]) lng = float(tuple(coordinates.split(","))[1]) .... This means I have to pass a context whenever I use or call the serializer. That's fine for normal drf views. Now I am faced with a situation where I need to use the serializer in a ModelObserver class MarketplaceConsumer(GenericAsyncAPIConsumer): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [HasApiKey] @model_observer(Product) async def marketplace_activity(self, message: ProductSerializer, observer=None, **kwargs): await self.send_json(message) @marketplace_activity.serializer def marketplace_activity(self, instance: Product, action, **kwargs) -> ProductSerializer: '''This will return the product serializer''' return ProductSerializer(instance, context={'request': self.request}).data At this point I will get the following error which makes sense(self.request): 'ModelObserver' object has no attribute 'request' This ModelObserver is for handling channel websocket actions. Is there any way to solve this situation? -
'function' object has no attribute 'objects' in django
i am getting a error: AttributeError at / 'function' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.5 Exception Type: AttributeError Exception Value: 'function' object has no attribute 'objects' Exception Location: G:\PYTHON DJANGO 2021 - COMPLETE COURSE\first_django_project\devsearch\project\views.py, line 27, in projects Python Executable: C:\ProgramData\Anaconda3\envs\djangoenv\python.exe Python Version: 3.9.6 Python Path: ['G:\PYTHON DJANGO 2021 - COMPLETE COURSE\first_django_project\devsearch', 'C:\ProgramData\Anaconda3\envs\djangoenv\python39.zip', 'C:\ProgramData\Anaconda3\envs\djangoenv\DLLs', 'C:\ProgramData\Anaconda3\envs\djangoenv\lib', 'C:\ProgramData\Anaconda3\envs\djangoenv', 'C:\ProgramData\Anaconda3\envs\djangoenv\lib\site-packages'] Server time: Sat, 21 Aug 2021 13:18:04 +0000 # models.py from django.db import models import uuid # Create your models here. class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True,blank=True) demo_link = models.CharField(max_length=2000,null=True,blank=True) source_link = models.CharField(max_length=2000,null=True,blank=True) tag = models.ManyToManyField('Tag',blank=True) vote_total = models.IntegerField(default=0,null=True,blank=True) vote_ratio = models.IntegerField(default=0,null=True,blank=True) created_on = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4,unique=True,primary_key=True,editable=False) def __str__(self): return self.title # views.py from django.shortcuts import render from .models import Project # Create your views here. def projects(requests): projects = Project.objects.all() return render(requests,"project/projects.html", {'projects':projects}) -
Django: can't redirect to home page after Registration
So, there's code: views.py from .forms import RegForm, LogForm from django.contrib.auth import logout, login as auth_login # Create your views here. def reg(request): if request.method == 'POST': regform = RegForm(request.POST) if regform.is_valid(): user = regform.save() regform.save() auth_login(request, user) return redirect('/main') else: regform = RegForm() context = { 'regform': regform } return render (request, "users/registration.html", context) and forms.py from django.contrib.auth import authenticate from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django import forms from django.contrib.auth.models import User class RegForm(UserCreationForm): email = forms.EmailField() last_name = forms.CharField() first_name = forms.CharField() class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'date_joined' ] and from users.views import log, reg, loggout urlpatterns = [ path('registration/', reg, name='registration'), ] It just give error: TypeError at /registration/ getattr(): attribute name must be string Request Method: POST Request URL: http://127.0.0.1:8000/registration/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: getattr(): attribute name must be string Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/fields/files.py, line 453, in update_dimension_fields Python Executable: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 Python Version: 3.9.1 Python Path: ['/Users/sung/Dev/blued', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages'] Server time: Sat, 21 Aug 2021 13:12:27 +0000 /Users/sung/Dev/blued/users/views.py, line 11, in reg user = regform.save() it was working perfectly before, I don't think I changed something, in views.py I also have … -
templatedoesnot exist django
i'm currently taking online course on django, am working right now in part 3 where we deal with template i follow the instructions but everytime i go to mysite/polls i get no template exist error this is my polls/view.py from django.http import HttpResponse from .models import Question from django.shortcuts import render from django.http import Http404 def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def owner(request): return HttpResponse("Hello, world. 9d5a197b is the polls index.") def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) /polls/urls.py from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), path('owner', views.owner, name='owner'), ] mysite/settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in … -
Is there a way to set the id of an existing instance as the value of a nested serializer in DRF?
I'm developing a chat application. I have a serializer like this: class PersonalChatRoomSerializer(serializers.ModelSerializer): class Meta: model = PersonalChatRoom fields = '__all__' user_1 = UserSerializer(read_only=True) user_2 = UserSerializer() the user_1 field is auto-populated but the client should provide the user_2 field in order to create a personal chat room with another user. My problem is, when creating a new chat room, the serializer tries to create a new user object from the input data thus giving me validation errors. What I really want it to do is to accept a user id and set the value of user_2 field to an existing user instance that is currently available in the database and if the user is not found, simply return a validation error. (the exact behavior of PrimaryKeyRelatedField when creating a new object) I want my input data to look like this: { 'user_2': 1 // id of the user } And when I retrieve my PersonalChatRoom object, I want the serialized form of the user object for my user_2 field: { ..., 'user_2': { 'username': ..., 'the_rest_of_the_fields': ... } } How can I achieve this? views.py class GroupChatRoomViewSet(viewsets.ModelViewSet): permission_classes = [IsUserVerified, IsGroupOrIsAdminOrReadOnly] serializer_class = GroupChatRoomSerializer def get_queryset(self): return self.request.user.group_chat_rooms.all() def … -
django context processor not working on mobile device
context processor show numerical value on template, it work fine on dev and desktop production. but in mobile device the value is always 0, no error. the value shows the total amount in CART of the products added. any clue why is not working? -
Django Queryset Postgres
I am writing queryset that will return this type date total_shipping_fee 2021-04-16 5,000 2021-04-17 100,000 where class Payments(models.Model): created = models.DateTimeField() ..... SELECT DATE(created) from payment_payment .... group by 'created' -> outputs a correct query My question is how to query/ or cast Payment.objects.filter(created_range=("2021-05-14", "2021-05-14")).values('created').annotate(total_shipping_fee=Sum('total_shipping_fee')) so that I can have queryset in above raw sql. I think that is my problem to CAST DATE(created) in django queryset. Thanks -
xhtml2pdf using images not working without error
I tried use an image for a signature in xhtml2pdf but it doesn't load the image. I see no error in the console html <img src="{{signature}}" class="signature"> python def generate_pdf(response,property): BASE_DIR = path.dirname(path.dirname(path.abspath(__file__))) URL = "http://127.0.0.1:8000"+'/static'+property.agent.signature.url print(URL) template = get_template("main/pdftabo.html") context = { "address": f'{property.street} {property.building_number} {property.city}', "owners": property.owners.all(), "loan": property.loan, "plot": property.plot, "signature":"http://127.0.0.1:8000"+'/static'+property.agent.signature.url, "date":date.today(), } html = template.render(context) filepath = join('static',f'media/{property.block}{property.lot}.pdf') write_to_file = open(filepath, "w+b") result = pisa.CreatePDF(html,dest=write_to_file) write_to_file.close() with open(join('static',f'media/{property.block}{property.lot}.pdf') , 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') #response = HttpResponse(html) response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response pdf.closed -
Error while runserver in Django: UnicodeDecode: 'utf-8' codec can't decode byte 0-xcf in position 2: invalid continuation byte
screenshot I'm trying to "runserver" for "manage.py' in my virtual environment of Django and I get that exception. Can't type or select in the command window afterwards, so screenshot of the full log added. Windows 7, Django 3.2.5, Python 3.8.9 -
Is there any possible way to create custom text editor
My Goal: is to create a text editor in a website like this. But I really have no idea if its possible and even if it is, how to achieve it. -
How to get name input type submit modelform in Django
I am facing a problem. Please help me templates.html <form action="" method="POST">{% csrf_token %} {{Form.as_p}} <input type="submit" name="Save" value="Save"> <input type="submit" name="Delete" value="Delete"> </form> view.py Class-based views: def post(self,request,text_id): try: text_data = Text.objects.get(pk=text_id) a = FormText(request.POST,instance=text_data) except: a = FormText(request.POST) if request.POST.get('name') =='Delete': a.delete() else: try: a.save() except: return HttpResponse('no ok') -
How to create logout view for djoser with JWT authentication?
I am working Django rest framework with djoser. I can't able to find way to remove the token in JWT(Djoser) and I need to store in old JWT. Can you please help me to logout the user in JWT authentication in Djoser? I want to login by either email or username in Djoser(JWT). Can you please give me solution for that? Answer will be appreciate. -
Integration dropzone.js with django has been an error "status of 405 (Method Not Allowed)"
This project I have been learning from the youtube channel. I watch it carefully and coding at the same instructor but It does not work when dropzone.js integrate with Django. I try to upload files to form but It cost an error "status of 405 (Method Not Allowed)" in the console.log. I can not figure it out. How I can fix it. This is my upload.js const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value Dropzone.autoDiscover = false const myDropzone = new Dropzone('#my-dropzone', { url: '/reports/upload/', init: function(){ this.on('sending', function(file, xhr, formData){ console.log('sending') formData.append('csrfmiddlewaretoken', csrf) console.log(csrf) }) }, maxFiles: 3, maxFilesize: 3, acceptedFiles: '.csv' }) This is my Html file {% block content %} <h5>Upload your sale file</h5> <form id="my-dropzone" class="dropzone dz" > {% csrf_token %} <div class="fallback"> <input name="file" type="file" multiple /> </div> </form> {% endblock content %} This is views.py file def csv_upload_view(request): print("file has been sending") return HttpResponse -
Python or Django library to convert html to an image or pdf
So I have two main issues: Finding a library that can convert an html file to an image and pdf (two separate libraries works too) Perform the conversion without exposing the html template in a URL What I've tried so far: I tried using imgkit but from my research, it's incompatible with my docker image: (python:3.7.11-alpine3.13). This was the error I was getting: OSError: wkhtmltoimage exited with non-zero code -11. error: QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root I tried using django's render_to_string, to generate a string which can be saved as an html file containing the rendered context data. However, for iterations were not rendered in the string output of render_to_string Currently the only way for me to generate a valid html page with all the passed context data is by using render. However this implementation would not work because I can only access the html body via a URL, which in my case is a no-no for security resasons. Any help is greatly appreciated. Thanks! -
How can I know which buildpack is appropriate for my application when deploying to heroku
I have been getting this error: ----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed and when I open the logs I saw this: Build failed -- check your build output: https://dashboard.heroku.com/apps/81b6ebcd-5768-4100-9a51-9fc90a49e4b4/activity/builds/1f1fc4ef-ad12-42d7-bb60-9937f45e0d36 And also when I tried to add the python buildpack directly to my CLI, I go this error: Error: Missing required flag: » -a, --app APP app to run command against » See more help with --help -
Why Django REST Framework (DRF) folder structure is different than Django Turorial?
If you follow the Django Tutorial you'll run theses commands: django-admin startproject mysite # Change into the outer mysite directory cd mysite python manage.py startapp polls and you'll get this folder structure mysite/ ├── manage.py │ ├── mysite/ │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ └── pools/ ├── migrations/ │ └── __init__.py ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py └── views.py But if you follow Django REST Framework and you'll run these commands: Note: I replaced the directory names to match, for better comparison # Create the project directory mkdir mysite cd mysite # Set up a new project with a single application django-admin startproject mysite . # Note the trailing '.' character cd mysite django-admin startapp polls cd .. and you'll get this folder structure mysite/ ├── manage.py │ └── mysite/ ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py ├── wsgi.py │ └── polls/ ├── migrations/ │ └── __init__.py ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py └── views.py This is DFR's explanation: It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with … -
Django view - objects are created but not present in a DB
I have a DRF view that imports Product objects in the database. The problem is that while the transaction is alive, everything looks correct. The objects created have their ids (so they have been stored in a DB). The problem is that after the view returns a response, those objects are not present in the database anymore. get file (binary from request) store it in /tmp/product_imports/ call ImportService.import_csv(new_filepath) the method returns a number of products imported return a response from the view Everything looks good, the view returns a number (2 in my case as 3 from 5 products aren't valid). But when I check the DB, it's not there. @action(methods=['post'], detail=False) def import_csv(self, request, pk=None) -> Response: csv_file = request.FILES['file'] csv_import_files_dir = os.path.join('/tmp/project_imports/') csv_file_path = os.path.join(csv_import_files_dir, str(uuid.uuid4())) os.makedirs(csv_import_files_dir, exist_ok=True) with open(csv_file_path, 'wb') as f: f.write(csv_file.read()) count = product_services.imports.ImportService.import_csv(csv_file_path, request.user) return Response({'imported': count}) Main methods from ImportService @classmethod def import_csv(cls, filepath: str, created_by: User, delete_file=True) -> int: """imports products supplier_sku already exists ? skip product : add product """ cls.validate_csv(filepath) products_count = 0 with open(filepath) as f: reader = csv.DictReader(f) for row in reader: if not all([row.get(field, None) is not None for field in ['title', 'sku']]): continue row['title'] = row['title'][:99] … -
get() returned more than one Designated -- it returned 4
I am a student who is learning Janggo. You tried to insert the designated_code on Views.py, but the following error occurs: I don't know how to solve it at all. How can we solve this? The element.designed_code part of join_create seems to be the problem. I'd be really happy if you could help me solve the problem. I know that there are 4 products in the designated code, but I want to add the designated code that corresponds to the value of the selected value code. Error: get() returned more than one Designated -- it returned 4! Models.py class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = ['value_code'] class Designated(models.Model): designated_code = models.AutoField(primary_key=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') price = models.IntegerField() rep_price = models.BooleanField(default=True) class Meta: ordering = ['designated_code'] def __str__(self): return str(self.designated_code) class Element(models.Model): element_code = models.AutoField(primary_key=True) designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code') value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True) class Meta: ordering = ['element_code'] def __str__(self): return str(self.element_code) class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = models.DateTimeField(auto_now_add=True) def __str__(self): return … -
django user update form not updating
I have a detailed user view that has a button for user update. The user update form is inside a modal, for that I am using a FormView ModelForm and a TbUser. I dont get how the form validation works but the fields are correct. When I update something for a user, I get an error, TbUser with username already exists, which means the code does not update the user but tries to add a new one. Also, I want to redirect to user-detail page after submit. How can I redirect to user-detail if the form is invalid sometimes and not displaying errors? Why the user is not updated? Why the form is invalid? views.py class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, FormView): form_class = UserUpdateForm template_name = 'users/modals/user_update_modal.html' success_message = "User updated successfully." def get_form_kwargs(self): kw = super().get_form_kwargs() kw['request'] = self.request return kw def form_valid(self, form): obj = form.save(commit=False) print(obj.username) print('valid') TbUser.objects.filter(id=self.request.user.id).update(username=obj.username, real_name=obj.real_name, email=obj.email, cellphone=obj.cellphone, department=obj.department, role=obj.role) def form_invalid(self, form): messages.error(self.request, form.errors) # Where to redirect here? I want to def get_success_url(self): return reverse('user-detail', kwargs={'pk': self.formclass}) forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request if request.user.customer: self.fields['department'].queryset = TbDepartment.objects.filter( customer=request.user.customer) self.fields['role'].queryset = TbRole.objects.filter( customer=request.user.customer) class …