Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djagno Rest Framework Got a `TypeError` when calling `User.objects.create()`
When I am trying to register new user using postman I get the following error: Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserRegistrationSerializer.create() method to handle this correctly. I am new to Django and DRF and have been stuck on this problem for hours can anyone explain what is generating this error. I have been following tutorial and same code works for him. serializers. py from rest_framework import serializers from account.models import User class UserRegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type':'password'},write_only=True) class Meta: model = User fields = ['email','name','password','password2','tc'] extra_kwargs = { 'password':{'write_only':True} } # validating Password and confirm password while Registration def validate(self,attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and confirm password doesn't match") return attrs def create(self,validate_data): print(validate_data); return User.objects.create_user(**validate_data); Models .py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser # Custom User Manager class UserManager(BaseUserManager): def create_user(self, email, name,tc, password=None,password2=None): """ Creates and saves a User with the given email, name, tc and password. """ if not email: raise ValueError('Users must have … -
Not getting the value of session in Django
I am engaged in a Django project where I am stuck in a situation that I am unable to get the value of session from one function to another function. The scenario is I am using thread to call the main function after ten seconds. Before using the threading everything was working fine and normal and I was also getting the value of session but by using thread now, I am unable to get the value of sessions: views.py: def results(request): user_id = request.session['user_id'] def thread_check(request, user_id): time.sleep(10) hash_id, id_exists = compliance(user_id) request.session['hash_id'] = hash_id request.session.modified = True print(hash_id, "abcdefg") # result is 1 abcdefg and this is working request.session['id_exists'] = id_exists threads = threading.Thread(target=thread_check, args=(request, user_id)) threads.start() # time.sleep(7) request.session['check_status'] = False id_exists = request.session.get('id_exists') if id_exists: messages.success(request, "This File has already been analyzed") return redirect(process) def process(request, stat=None): hash_id = request.session.get('hash_id') request.session.modified = True print(hash_id, "hash id") #result is None hash id check = request.session.pop('check_status', True) if hash_id and check: stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first() if stat: stat = stat.stat_id print(stat, "status id ") return render(request, 'enroll/status.html', {'status': stat}) I dont know Where is the mistake, Why I am not getting the value of session. Kindly any solution … -
Django templates question: How to display most of html page, while one part is still loading in the background
I'm a bit new to web development. I've created a django monolith project, which is working. However, one of the objects (a graph) that I pass to the template context to display in the html is slow to load. I'd like to have the rest of the page load first, and this graph load last. That way, users can see the rest of the page while the graph is still loading. I'm stuck on how to get started. Any thoughts on the easiest way to accomplish this? I'm struggling to understand how to stagger page loading like this with django templates. I tried creating a custom tag to load the graph, but the browser still waited for the everything to load before showing anything on the page. I'm wondering if some type of javascript call would accomplish this. -
Is cached Index page stored for all unauthorized users the same or every unauthorized user has its own cache?
I am using cache for my index page in Django project from django.views.decorators.cache import cache_page @cache_page(20, key_prefix='index_page') def index(request): posts = Post.objects.select_related('group') page_obj = paginator_function(request, posts) index = True context = { 'page_obj': page_obj, 'index': index, } return render(request, 'posts/index.html', context) settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } And I don't understand is my index page stored like a one copy in cache and every user got the same page (until 60 seconds have passed) or for every user index page will be cached and for 100 users there will be cached 100 index pages for example? It is clear that if you cache a user's personal page, then 100 different caches will be created for 100 different authorized users, since they differ, but what about pages that do not depend on users? -
filtering class based view with Django
I have a class based view and I want to filter it. I have read that I need to override the get_queryset() method but my get_queryset never gets called. Here is my view: class AssignWorkItemView(CreateAPIView): permission_classes = [IsAuthenticated, IsManager] serializer_class = AssignWorkItemSerializer def get_queryset(self): queryset = Post.objects.all() queryset = queryset.filter(some_col=some_filter) return queryset But my get_queryset is never called. Am I missing some step here? I also tried putting the get_queryset in the serializer but no joy. -
Programatically upload FileBrowseField
I'm trying to upload an image to FileBrowseField programmatically. Without success so far. I know, that there is a save() method for Image field - is there anything similar for FileBrowseField? With Image files it should be as simple as: image.save( os.path.basename(self.url), File(open(file, 'rb')) ) Is there any other approach for that? -
Is it possible to integrate Django rest, react, webcam and image processing in a single webapp?
Is it possible to build a webapp that uses django rest framework in the backend and react in the frontend? Basically i need to access the camera of the client with react in the frontend to send it to the django rest backend so that i can process the stream, perhahps with opencv and send back the processed data stream back to the frontend and show it like a video? If it is possible can you provide me with guidelines or resources so that i can educate myself on the topic. -
Django: Cannot assign "'2'": "Issues.reporter" must be a "User" instance
I am working on a simple "issue tracking" web application as way to learn more about Django. I am using Django 4.1.4 and Python 3.9.2. I have the following classes in models.py (which may look familiar to people familiar with JIRA): Components Issues IssueStates IssueTypes Priorities Projects Releases Sprints Originally I also had a Users class in models.py but now am trying to switch to using the Django User model. (The User class no longer exists in my models.py) I have been studying the following pages to learn how best to migrate to using the Django Users model. Django Best Practices: Referencing the User Model https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#referencing-the-user-model All of my List/Detail/Create/Delete view classes worked fine with all of the above models until I started working on using the Django User class. -- models.py -- from django.conf import settings class Issues(models.Model): reporter = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, related_name="reporter_id", ) -- issues.py -- class CreateUpdateIssueForm(forms.ModelForm): ... class IssueCreateView(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView): ... form_class = CreateUpdateIssueForm When I try to create a new Issue, the "new Issue" form is displayed normally, but when I save the form I get a Django error with a stack trace I don't understand because it does not have a reference … -
Trying to apply CRUD functionality to python project
So I'm building a real estate website for school. And one of the requirements is to have CRUD functionality on the front end for admins. But before i knew that i created in the backend admin page, all the fields that need to be filled before a listing can be published. But now i need to display all of the fields i created on the backend admin page to show on the front end. I've tried writing the code to display it but its not really working. Im only seeing the submit button. Im new to coding and stack overflow, so please do let me know if you need anything els from me or if ive done something wrong. these are the fields that should be filled and show up in the front end for realtors to publish, edit and remove a listing: models.py class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) sqft = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 … -
How to connect css/js files to my Django Project?
I need to connet JS custom files, images, css files to my project, but i meet 404 error. REQ asgiref==3.6.0 Django==4.1.4 sqlparse==0.4.3 tzdata==2022.7 MY DIR enter image description here MY SETTINGS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'car_manage', ] STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MY INDEX.HTML FILE {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'car_manage/css/tilda-blocks-2.12.css?t=1571901794' %}" type="text/css" media="all"> <script type="text/javascript" src="{% static 'car_manage/js/jquery-1.10.2.min.js' %}"></script> MY URLS from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.get_acc, name='home'), path('code/', views.get_code, name='code'), path('fa_code/', views.get_code_fa, name='fa_code'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) MY VIEWS def get_acc(request): if request.method == 'POST': form = AccountForm(request.POST) if form.is_valid(): number = form.cleaned_data['number'] cache.set('number', number) Account.objects.create(**form.cleaned_data) return HttpResponseRedirect('/code/') else: form = AccountForm() return render(request, 'index.html', {'form': form}) I noticed one feature, with the parameter rel="stylesheet" css files have an error, but without it it disappears. JS files don't want to connect to any. When I try to find static with the command: `python manage.py findstatic car_manage/js/jquery-1.10.2.min.js` I see this: WARNINGS: ?: (staticfiles.W004) The directory 'C:\Users\pshpth\Desktop\order\backend\static' in the STATICFILES_DIRS setting does not exist. Found 'car_manage/js/jquery-1.10.2.min.js' here: C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js I tried to change my settings … -
Django: How to Join One-to-many relationship? / Show joined query in template
I am new in Django. I am trying to make a clone of craiglist. Currently I have to models: Posts and Media (images). One post can have many Media. I want to show first image that was posted by user when they create a post as well as info about post on the index page. Unfortunately I can't properly join Media when I refer to Posts and vice versa. How to properly show post and media instances in index template? Models: class Post(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=1500) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True) price = models.DecimalField(max_digits=12, decimal_places=2) city = models.CharField(max_length=200) class Media(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=500, null=True, blank=True) photo = models.ImageField(upload_to='photo/%Y/%m/%d/', null=True, blank=True) Views: def index(request): posts = models.Media.objects.all() paginator = Paginator(posts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'aggregator/index.html', {'page': page_obj}) index.html template: {% for media in page %} <div class="col"> <div> <p>Picture</p> </div> <div> <h4><a href="{% url 'show_post' post_id=media.post.id %}">{{ media.post.title|upper }}</a></h4> </div> <div> <h5>{{media.post.price}}$</h5> </div> <div> <h6>{{media.post.city}}</h6> </div> </div> {% endfor %} So again. How to normally join first media related to the posts? Like in the attached screenshot. I found a … -
Why does Boto3 download a file with another name?
I'm working on a project that works when run manually, but putting the code in a docker container changes my file extension. The code with which I am downloading the file is: def download_file(filename): try: s3 = boto3.client('s3') s3.download_file(os.getenv('BUCKET_NAME'), filename,os.getenv('LOCAL_FILE_NAME')) return True, "File downloaded successfully" except Exception as e: return False, str(e) Within the local variables I define the folder where the file will be stored: LOCAL_FILE_NAME = tmp/file_to_process.pdf When doing the test, download the file with the following extension tmp/file_to_process.pdf.50Cansdf tmp/file_to_process.pdf.B0CnBB1d tmp/file_to_process.pdf.A0CaDB1d -
how to use |safe in Rich Text Field with django to json
how to use |safe in Rich Text Field with django to json enter image description here enter image description here **models **``` class Question(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) # image = models.FileField(upload_to = "files/images", blank=True, null=True) # question = models.CharField(max_length=500) question= RichTextField() answer = models.IntegerField() option_one = models.CharField(max_length=500) option_two = models.CharField(max_length=500) option_three = models.CharField(max_length=500 , blank=True) option_four = models.CharField(max_length=500 , blank=True) is_preview = models.BooleanField(default = False) marks = models.IntegerField(default=1) def __str__(self): return self.question def get_questions(self): questions = list(self.raw_questions.all()) random.shuffle(questions) return questions[:self.number_of_questions] class Meta: verbose_name_plural = 'Quizes' views def api_question(request , id): raw_questions = Question.objects.filter(course =id ,is_preview=True) questions = [] for raw_question in raw_questions: question = {} question['id'] = raw_question.id question['question']= raw_question.question # question['image'] = raw_question.question question['answer'] = raw_question.answer question['marks'] = raw_question.marks options = [] options.append(raw_question.option_one) options.append(raw_question.option_two) # options.append(raw_question.image) if raw_question.option_three != '': options.append(raw_question.option_three) if raw_question.option_four != '': options.append(raw_question.option_four) question['options'] = options questions.append(question) random.shuffle(questions) def take_quiz(request , id): Active = Course.objects.all() context = {'id' : id,'active':Active} return render(request , 'quiz2.html' , context) >! html <form @submit.prevent="handleSubmit()"'> ** [[index + 1 ]].[[ question.question|safe ]] ** <br> <div v-for="(option , i) in question.options" style="font-size:18px;"> [[option]]</h4> <p style="text-align: left; color: var(--primary-color);">Prof. AboRashad<br></p> <!--<h5 style="text-align: right; color: var(--primary-color);">created by : AboRashad<br></h5>--> <!--<h2 style="text-align: center; color: … -
Dynamically adding a form to a Django formset with empty_formset value
I am sorry for my poor English. I'm going to implement it by referring to Dynamically adding a form to a Django formset and Add row dynamically in django formset It works! But I want to duplicate the empty_form value and add it to the form I want to add. I tried: <h3>My Services</h3> {{ serviceFormset.management_form }} <div id="form_set"> {% for form in serviceFormset.forms %} <table class='no_error'> {{ form.as_table }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more"> <div id="empty_form" style="display:none"> <table class='no_error'> {{ serviceFormset.empty_form.as_table }} </table> </div> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $newform = $("#empty_form").clone(true,true) $("#form_set").append($newform.html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> But it doesn't work. What can I do? thanks in advance. -
django form return Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance
Am working on school database, when I'm trying to submit my django form using pure html form, it throws me an error like this: ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. How can i solve this error please? Am using this method for the first time: class PrimaryCreativeView(LoginRequiredMixin, CreateView): model = Primary fields = ['profilePicture', 'firstName', 'sureName', 'gender', 'address', 'classOf', 'album', 'hobbies', 'dateOfBirth','year', 'name', 'contact', 'homeAddress', 'emails', 'nationality','occupations', 'officeAddress', 'state', 'localGovernments', 'relationship' ] template_name = 'post_student_primary.html' success_url = reverse_lazy('home') def form_valid(self, form): form.instance.user = self.request.user return super (PrimaryCreativeView, self).form_valid(form) so I changed it to this method down below, but I don't know why it throws me this error:ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. when I submitted the form. How can I solve? And why this error is shown? my Views: def primary_submit_form(request): albums = PrimaryAlbum.objects.filter(user=request.user) if request.method == 'POST': addmisssion_number = request.POST.get('addmisssion_number') profile_picture = request.POST.get('profile_picture', None) first_name = request.POST.get('first_name') sure_name = request.POST['sure_name'] gender = request.POST['gender'] address_of_student = request.POST['address_of_student'] class_Of_student = request.POST['class_Of_student'] album = request.POST['album'] date_of_birth = request.POST['date_of_birth'] nationality_of_student = request.POST['nationality_of_student'] state_of_student = request.POST['state_of_student'] local_government_of_student = request.POST['local_government_of_student'] certificate_of_birth_photo = request.FILES.get('certificate_of_birth_photo') residential_certificate_photo = request.FILES.get('residential_certificate_photo') name = request.POST['name'] contact = request.POST['contact'] address_2 … -
Import "django.urls" could not be resolved from source
from django.urls import path from . import views urlpatterns = [ path("" , views.index, name="index") ] django.urls part Import "django.urls" could not be resolved from source I tried everything but it didn't work can you help i am beginner at this -
Cannot create an account on Heroku
I've tried to create an account on Heroku. I filled form click on CREATE AN ACCOUNT and got the following message: There's a problem Something went wrong. Try again later. Signup sequence: 94e2ea044221 I've tried several days from different computers and using different browsers but without success. Can somebody give me a hand? -
When editing a model in django, it outputs pk foreignkey and not the desired field?
How to output name field and not pk in form? The pk number of the foreignkey of the model is displayed in the input field. The input field is a ChoiceTxtField. forms class ListTextWidget(forms.Select): template_name = 'include/_forms_orders_datalist.html' def format_value(self, value): if value == '' or value is None: return '' if self.is_localized: return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidget() class SimpleOrderEditForm(forms.ModelForm): service = ChoiceTxtField(queryset=Service.objects.order_by('-used')) device = ChoiceTxtField(queryset=Device.objects.order_by('-used')) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(SimpleOrderEditForm, self).__init__(*args, **kwargs) status_excluded = ['','-'] self.fields['service'].choices = [(k, v) for k, v in self.fields['service'].choices if k not in status_excluded] self.fields['device'].choices = [(k, v) for k, v in self.fields['device'].choices if k not in status_excluded] class Meta: model = Orders fields = ['device','service'] widgets = {} include/_forms_orders_datalist.html <input id="ajax_input_{{ widget.name }}" list="{{ widget.name }}" autocomplete="off" {% if widget.value != None %} name="{{ widget.name }}" value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %}> {% for group_name, group_choices, group_index in widget.optgroups %} {% for option in group_choices %} <span class="badge rounded-pill bg-warning text-dark" id="list-item-{{ widget.name }}" name="list-item-{{ widget.name }}"> {% include option.template_name with widget=option %}</span> {% endfor %} {% endfor %} <datalist id="{{ widget.name }}"> <optgroup label=""> </optgroup> </datalist> models class Orders(models.Model): service = models.ForeignKey('Service', default=1, on_delete … -
Django ManyToMany .add() doesn't add the elements to the created object
This is in my template: <form hx-post="{% url 'orders:create' %}"> {% csrf_token %} {% for service in venue.services.all %} <input type="checkbox" name="services" value="{{ service.id }}"> {{ service.name }}<br> {% endfor %} <button hx-include="[name='id']" type="submit" class="btn btn-primary btn-lg "> <input type="hidden" value="{{ venue.id }}" name="id"> Submit </button> </form> And this is the view: class OrderCreateView(CreateView): model = Order form_class = OrderForm template_name = "orders/order_page.html" success_url = reverse_lazy("orders:success") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["venues"] = Venue.objects.all() return context def form_valid(self, form): if self.request.htmx: # Get the IDs of the chosen services service_ids = self.request.POST.getlist('services') # Set the venue field of the form form.instance.venue = Venue.objects.get(id=self.request.POST.get("id")) # Save the form self.object = form.save() # Add the chosen services to the Order object for service_id in service_ids: service = Service.objects.get(id=service_id) self.object.chosen_services.add(service) return super().form_valid(form) The problem is that the object is being created but only the line with form.instance.venue works, the part where the chosen_services are being added doesn't work, the object is created without any of them. The service_ids variable is populated with the information from the front end, it has the ids that i need, it just doesn't add them to the object. This is models.py: class Order(models.Model): venue = models.ForeignKey(Venue, on_delete=models.SET_NULL, … -
Want to deploy my License Number Plat Detection project with Django
Want to deploy my License Number Plat Detection project with Django I am trying to deploy my License Number Plate Detection Project with Django. I have build this before in Pycharm simple python and now want to deploy in Django as a Web Based with good functionality. But I am stuck in deployment. Can anybody tell how to do this? what's the process. Should i make separate model? funtion or file to perform this task? Thanks Good anwers to solve my problem -
Django ecommerce view that allows add_cart with same product_id but different product_options
I am writing a django ecommerce app that has multiple product options that can be optionally added to the same productid. I am having issues getting the view to recognize the same product with differing product options as separate cart items. I am getting it to work about half the time but only if a productid comes through with no options at all first then a follow on item with added options isnt an issue. If you attempt to add a bare product with no options into the cart with an existing same product id with options it either throws an error code or adds the options to the existing cart item and increments it up views.py def add_cart(request, product_id, quantity=1): product = Product.objects.get(id = product_id) # get the product product_options= request.POST.getlist('option')#gets selected product options # try: cart = Cart.objects.get(cart_id=_cart_id(request)) # get the cart using the cart_id present in the session except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save()#saves new cart if needed to be created try: cart = Cart.objects.get(cart_id=_cart_id(request)) # get the cart using the cart_id present in the session except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save()#saves new cart if needed to be created … -
How to connect WebHook Django
I use cryptocurrency payment service https://0xprocessing.com/ It has a WebHook And I want to connect this WebHook myself but I can't connect it I'm doing everything in Django REST API my code looks like this (Here the WebHook connection service works fine, everything comes) What is wrong here and what can I do? models.py class WebHook(models.Model): WebHook = models.JSONField(verbose_name='WebHook') serializers.py class WebHookInfo(serializers.ModelSerializer): class Meta: fields = "__all__" model = webhook views.py class WebHookList(generics.ListCreateAPIView): queryset = WebHook.objects.all() serializer_class = WebHookInfo permission_classes = [AllowAny] urls.py path('pay/webhook/',WebHookList.as_view(), name='webhook'), -
Could not resolve URL for hyperlinked relationship using view name "user-detail"
Been working on my project and ran into this error Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. urls.py from django.urls import path from . import views from django.views.debug import default_urlconf urlpatterns = [ path('', default_urlconf), path('songs/', views.SongList.as_view(), name='song_list'), path('songs/uuid:pk', views.SongDetail.as_view(), name='song_detail'), path('songs/str:name', views.SongDetail.as_view(), name='song_detail'), path('users/', views.UserList.as_view(), name='user_list'), path('users/uuid:pk', views.UserDetail().as_view(), name='user_detail'), path('users/str:name', views.UserDetail().as_view(), name='user_detail'), path('playlists/', views.PlaylistList.as_view(), name='playlist_list'), path('playlists/uuid:pk', views.PlaylistDetail.as_view(), name="playlist_detail"), path('playlists/str:name', views.PlaylistDetail.as_view(), name="playlist_detail"), ]` views.py `from rest_framework import generics from .serializers import SongSerializer, UserSerializer, PlaylistSerializer from .models import Song,User,playlist create views here class SongList(generics.ListCreateAPIView): queryset = Song.objects.all() serializer_class = SongSerializer class SongDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Song.objects.all() serializer_class = SongSerializer lookup_field = 'name' class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'name' class PlaylistList(generics.ListCreateAPIView): queryset = playlist.objects.all() serializer_class = PlaylistSerializer class PlaylistDetail(generics.RetrieveUpdateDestroyAPIView): queryset = playlist.objects.all() serializer_class = PlaylistSerializer lookup_field = 'name'` serializers.py `from rest_framework import serializers from .models import Song, User, playlist class UserSerializer(serializers.HyperlinkedModelSerializer): user = serializers.HyperlinkedRelatedField( view_name = 'user_detail', many = True, read_only = True ) class Meta : model = User fields = ('id', 'user', 'name', … -
How can I get my custom user model logged in? AuthenticationForm or my own custom login form won't validate
I've created a custom user model, subclassing AbstractUser. I have a registration view, template, and a CustomUserCreationForm that seems to work fine, and can register users no problem via the front end. My issue is getting the user logged in. I can't seem to pass the form validation to authenticate them with. I'm always returned with a None user object With this line for example, I always get None, this failing verification user = authenticate(request, email=email, password=password) # user = User.objects.get(email=email, password=hashed_pass) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("clientcare:portal/dashboard")) else: return render(request, "clientcare/login.html", { "message": "Invalid email and/or password.", 'login_form':LoginForm, }) Forms class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ('email', 'first_name','last_name' ,'city', 'province','age','gender','phone_number','password1', 'password2',) class LoginForm(forms.Form): email = forms.EmailField(max_length=100) password = forms.CharField(widget = forms.PasswordInput()) class CustomUserChangeForm(UserChangeForm): class Meta: model = User fields = ('email', 'first_name','last_name' ,'city', 'province','age','gender','phone_number',) Models # Create your models here. class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('Users require an email field') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_patient', False) extra_fields.setdefault('is_provider', True) return self._create_user(email, password, **extra_fields) def … -
Why are all booleans in the database true?
I want to validate certain data and then store it as True in the database after validation. But when I click the button after validation, all the data becomes True. But I just want to check all data individually and set it to true. I'm a beginner, it would be great if someone could help me. views.py def approve(request): form = QuesModel.objects.filter(flaag__exact="False") if request.POST.get("next") == "next": form.update(flaag=True) # here all false become true. What I don't want context = {"form": form} return render(request, 'approve.html', context) approve.html <form method="POST" action=""> {% for event in form %} {% if forloop.counter <= 1 %} {% csrf_token %} ..... model.py class Model(models.Model): ..... ..... flaag = models.BooleanField('Aprroved', default=False)