Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ERROR: there is no unique constraint matching given keys for referenced table
There are many similar questions on Stackoverflow, but none of the answers has helped me. So, when running migrations, Django throws this error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "catalogues_movieslist" I have this BlackWhiteCartoon model I am trying to create with the migration: class BlackWhiteCartoon(BaseMovie, BaseList): authors = JSONField(default=list, blank=True, null=True) publisher = CharField(max_length=250, blank=True) year = PositiveSmallIntegerField(blank=True, null=True) This model inherits from the BaseList model that has only one field, a foreign key: class BaseList(Model): belongs_to_movies_list = ForeignKey(MoviesList, on_delete=CASCADE, null=True) The referenced MoviesList model is the following: class MoviesList(Model): creation_date = DateTimeField(auto_now_add=True) id = AutoField(primary_key=True) uid = UUIDField(default=uuid.uuid4, editable=False) user = ForeignKey(User, on_delete=CASCADE, null=True, blank=True) Also, the BaseMovie model is the following: class BaseMovie(BaseObject): language = CharField(max_length=2, blank=True) note = CharField(max_length=700, blank=True) And the BaseObject model: class BaseObject(Model): id = BigAutoField(primary_key=True) uid = UUIDField(default=uuid.uuid4, editable=False, db_index=True) date_added = DateTimeField(null=True) So, what I have tried: Migrating everything together: this throws the above error. Migrating BlackWhiteCartoon without inheriting BaseList first. This migration applies, but as soon as I add BaseList, it crashes with the same error. Adding unique=True to the id field of MoviesList (both together with all other migrations and before adding BaseList to … -
Specific Fields for Specific User types in Django
I'm trying to come up with a better structure for handling user data in a django app. Currently, There are two kinds of users in the app, individual and organization. There is data specific to an individual and data specific to an organization. For example, an individual can have a first and last name while a organization only has their organization name. This is how the model currently looks class CustomUser(AbstractUser): first_name = models.CharField(_('first name'), max_length=30, blank=True) # from AbstractUser last_name = models.CharField(_('last name'), max_length=150, blank=True) # from AbstractUser organization_name = models.CharField(_('organization name'), max_length=180, blank=True) is_individual = models.BooleanField(default=False) is_organization = models.BooleanField(default=False) Is there a way specific fields can be set up for specific user types? Something like: Individual -- first_name -- last_name # more data concerning individuals Organization -- organization_name # more data concerning organizations -
IsDoctorPermission is not working in this class?
views Is doctor permissions are not working in this cclass ? class CreateEducationView(generics.ListCreateAPIView): serializer_class = EducationSerializer queryset = Education.objects.all() permission_classes = (permissions.IsAuthenticated,IsDoctorPermission) def perform_create(self, serializer): return serializer.save(doc_clinic=self.request.user) def get_queryset(self): return self.queryset.filter(doc_profile=self.request.user) -
Django templates ; Reverse for '' not found. '' is not a valid view function or pattern name
I have this error with templates, I don't understand what's the problem, pls help NoReverseMatch at /login/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:5000/login/ Django Version: 3.1 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Exception Location: /home/daniiar/.local/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /usr/bin/python3 Python Version: 3.8.5 Python Path: ['/home/daniiar/land-gPage', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/daniiar/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 16 Jan 2021 13:39:04 +0600 Error during template rendering In template /home/daniiar/land-gPage/auto/templates/base.html, error at line 14 Reverse for '' not found. '' is not a valid view function or pattern name. 4 <html> 5 <head> 6 <title>{% block title %}{% endblock %}</title> 7 <link href="{% static 'css/base.css' %}" rel="stylesheet"> 8 </head> 9 <body> 10 <div id="header"> 11 <span class="logo">Bookmarks</span> 12 {% if request.user.is_authenticated %} 13 <ul class="menu"> 14 <li {% if section == 'dashboard' %}class="selected"{% endif %}> 15 <a href="{% url 'dashboard' %}">My dashboard</a> 16 </li> 17 <li {% if section == 'images' %}class="selected"{% endif %}> 18 <a href="#">Images</a> 19 </li> 20 <li {% if section == 'people' %}class="selected"{% endif %}> 21 <a href="#">People</a> … -
django return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table:
I have a simple model class as below class Language(models.Model): name= models.CharField(max_length=20) code= models.CharField(max_length=5) status=models.BooleanField() create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) def __str__(self): return self.name and I want to use it like this llist = Language.objects.filter() list1 = [] for rs in llist: list1.append((rs.code,rs.name)) langlist = (list1) but it keeps throwing this error when I try to use llist : return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: home_language I tried to use python manage.py shell to make querries and it's showing the same above error. -
Django: Getting 403(csrf token validation error) If I make POST/PUT request one after other
I have page where I render datatables to display the data with buttons like edit and delete per row,I have also one global button to create new entry. The create button opens a modal form which is standard bootstrap model. I am using this same form to create & update records.So if refresh my page & create one new entry it works but without refresh when click on the edit button then submit the modal form it gives me this error, CSRF verification failed. Request aborted. All this operations are performed using the AJAX request so I am not reloading the page after each request.How can I resolve this? Here is my server side code you want to take a look, class CategoryView(AdminLoginRequiredMixin,View): def post(self, request): form = DownloadableCategoryForm(request.POST) if not form.is_valid(): return JsonResponseBuilder.validation_error(form.errors) form.save() return JsonResponseBuilder.success('Category created succesfully...') # to update category def put(self, request): try: category = DownloadableCategory.objects.get(pk=request.POST.get('id')) except DownloadableCategory.DoesNotExist: return JsonResponseBuilder.error('Category not found!', HTTPStatus.NOT_FOUND.value) form = DownloadableCategoryForm(request.POST,instance=category) if not form.is_valid(): return JsonResponseBuilder.validation_error(form.errors) form.save() return JsonResponseBuilder.success('Category updated succesfully...') -
render_form() missing 1 required positional argument: 'form'
I am getting this error for my code given below. Can someone help me out class CreatePost(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView): fields = ('message','group') model = models.Post def form_valid(self,form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) -
how to dynamically add text input field in model on the basis on no of choice selected in drop down(using easy_select2) in django python
I have created a model in Django which contains a easy-select2 drop down field Vendor : class Offer(models.Model): Offer_Name=models.CharField(max_length=200,blank=False) StartBid=models.CharField(max_length=100,blank=False) JumpBid=models.CharField(max_length=100,blank=False) Vendor=models.ManyToManyField(User,limit_choices_to={'is_vendor': True},help_text = "Please select vendor valid for this offer") LastBid=models.CharField(max_length=100) In this i want to modify LastBid field such that if 3 options are selected in Vendor than 3 Last bid input fields are created dynamically for each option.I'm new to django and tried using dynamic-django-forms 0.1.5 but was unable to implement the same. Please help. -
My code is not working - Form is not getting submitted
<!-- The form markup --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> <div> <h1 class="text-primary fw-bold text-center log-in-title">Log In</h1> </div> <div class="mt-3 text-center"> <!-- The form --> <form class="mod-auth"> <div class="mb-3"> <input id="mod-auth-username" type="text" placeholder="Username" name="username" class="form-control" required> </div> <div class="mb-3"> <input id="mod-auth-password" type="password" placeholder="Password" name="password" class="form-control" required> </div> <div class="d-grid gap-2 mx-auto"> <button class="btn btn-primary" type="button">Log in</button> </div> </form> <hr> <h6>Don't have an account? <a href="/sign-up/?next={{request.path}}">Sign up</a></h6> </div> </div> </div> </div> // AJAX Post request $(document).on('submit', '.mod-auth', (e) => { e.preventDefault(); console.log('hi'); $.ajax({ url: '/log-in/', type: 'POST', data: { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), username: $('#mod-auth-username').val(), password: $('#mod-auth-password').val(), }, success: function() {}, }); }); My code is not working, I have added a jQuery form submit event, which is not working. I am unable to figure out what is the problem. The form is a part of a Modal (Bootstrap), which is fired when a user tries to click a Like button without logging in, the modal contains a form, which has to be filled and submitted, then an AJAX Post request gets executed and the data is sent to the views.py. Thank you. Your help is appreciated. -
Django Rest Framework: use create with primary key in URL
I can't apply the @action decorator to create function within a standard views.Viewset subclass. @action(detail=True) # This fails. def create(self, request, pk=None): return Response(etc...) On other methods, adding that decorator allows me to create URLs easily with <pk> within the URL. For example, I can send a POST request to http://main_url.com/do_something_to_user_with_id/7/, with do_something_to_user_with_id being some random function within the viewset and 7 being the user id/primary key. Is there any way I can do this with create? -
how to inherit slug form one class to other in django models
my models.py file is: class Product(models.Model): title = models.CharField(max_length=110) slug = models.SlugField(blank=True, unique=True) price = models.DecimalField(decimal_places=2, max_digits=6) discount_price=models.FloatField(blank=True, null=True) size = models.CharField(choices=SIZE_CHOICES, max_length=20) color = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(upload_to=upload_image_path) description = models.CharField(max_length=1000) featured = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True) objects=ProductManager() def get_absolute_url(self):#i use this in product_list.html to go to detail page #return "/product/{slug}".format(slug=self.slug) return reverse("products:detail", kwargs={"slug" : self.slug}) def __str__(self): return str(self.title) @property def name(self): #sometime in html i say name istead of title so to make it work i wrote this return self.title def product_pre_save_reciever(sender, instance, *args, **kwargs):#i inherit unique slug generator from utils to here so when i create aa new instance it slug automatically generate. and i i create two t shirts it give a random straing to tshirt 2nd slug if not instance.slug: instance.slug=unique_slug_generator(instance) pre_save.connect(product_pre_save_reciever, sender=Product) class Comment(models.Model): product=models.ForeignKey(Product , related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body=models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s'%(self.product.title, self.name) i want the slug field to inherit it into comments because the comments must me on their specific post . when i run the server and post comment it is posting comment on specific post but gave me the error that Comment has no attribute … -
I can't display data in django template
So, i can't display data from my model in this template. In base.html it works great, but in this template is not working. I see too much posts on this site and i cant solve my problem. I write the render in too many ways but don't work and i'dont understand Stack overflow don't let me send this post because i don't write too much text so the next random text is for fill the post and send it: ldgnsldngasilhhhhhhhhhhhhhhhhhhandñvkjasnaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaarkjasbgkjbdkjgvbsrkhbgusenvgkrhgkuasdngkjasdkudsgnkasduglaiuskgblksadubgaskudgbsakudgbsadkugbksaudgbsakugasiudbgusbdguasidbguksakuksudliuabgkusbligubrsuguraegnfskudhbrsauibgasurghasidongusadghsidlgnsudghsidlgnsdlñailsdgnuahñilnebwureñgbsegbuksdghesngukrsgbs2gbsyiughbsebgruighbesabguiwghndslgksurghsidlngkuwehaneslgbaksugnsdjkbsaekgsuegblseskuegsbgkubue views.py from django.http import HttpResponse from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, PostView, Like, Comment class PostListView(ListView): model = Post class PostDetailView(DetailView): model = Post class PostCreateView(CreateView): model = Post class PostUpdateView(UpdateView): model = Post class PostDeleteView(DeleteView): model = Post def change_view(request): todo = Post.objects.all context = { 'todo': todo } return render(request, "index.html", context) models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.shortcuts import reverse from ckeditor.fields import RichTextField class User(AbstractUser): pass def __str__(self): return self.username class Post (models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) thumbnail = models.ImageField() publish_date = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField() def __str__(self): return self.title return render(request, … -
Why I need Docker Compose? and For what i use it in web development?
I have searched these questions in the internet, unfortunately I am not satisfied with the results. And the last question what is the docker container? -
Import function from another file in same folder
I know this question has been asked many times in other posts, but I can't to solve it with the answers provided. I am creating a Django app in which I have a .py file with some functions that I want to import in another file and use them. This is the code of the function to import (in helpers.py): from requests.exceptions import HTTPError def cargar_api(url): for url in [url]: try: response = requests.get(url) response.raise_for_status() except HTTPError as http_err: print(f"Ocurrió un error HTTP: {http_err}") except Exception as err: print(f"Ocurrió otro error: {err}") else: print("API cargada") data = response.json() return data And this is the code where I want to import it, the file (service.py) is in the same folder and helpers.py: import requests from requests.exceptions import HTTPError import os from .helpers import cargar_api WEATHER_API_KEY = os.environ.get("WEATHER_API_KEY") # funcion que da todos los datos del clima segun las coordenadas # adicionalmente agrega un key "recomendacion" para alertar al usuario de precauciones a tomar antes de salir # informacion de cada dato de la API: https://www.weatherbit.io/api/weather-current # diferentes opciones de descripciones y logos aqui: https://www.weatherbit.io/api/codes def info_clima(latitud, longitud): url_clima = f"https://api.weatherbit.io/v2.0/current?lat={latitud}&lon={longitud}&key={WEATHER_API_KEY}" info_clima = cargar_api(url_clima)["data"][0] descripcion_clima = info_clima["weather"]["description"] if ( "Thunderstorm" in descripcion_clima … -
Profile fails to get created for a New Registered User in Django
I'm working on a new Django project to get students registered and to get a profile created for each student after the registration. I get an error when the user register. ERRO ValueError at /students/register/ Cannot force both insert and updating in model saving. Below are my code snippets: models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='students/profile_pics') bio = models.TextField(null=True, blank=True, verbose_name='biography') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, *kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) views.py def register_student(request): if request.method == 'POST': form = StudentRegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('student_course_list') else: form = StudentRegistrationForm() return render(request, 'students/student/registration.html', {'form': form}) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class StudentRegistrationForm(UserCreationForm): email = forms.EmailField(help_text='Enter a valid email address') class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] urls.py from .views import register_student urlpatterns = [ ### path('register/', register_student, name='student_registration'), ] signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile … -
How do link a file user uploaded to Database?
This is how I was saving user uploaded Files: f = request.FILES[x] s = File(file=f, user=curUser) s.save() This worked great but it took a lot of bandwidth on my server so I decided to use pre-signed urls. Now users upload directly to s3 Bucket, however it's not linked to Database. I tried this which runs after user successfully uploads to S3: f = default_storage.open(userID + "/" + fileName) curUser = User.objects.get(userID=userID) s = File(file=f, user=curUser) s.save() f.close() However, this is just creating a new folder on users directory and uploading it there. my Models: class User(models.Model): userID = models.CharField(max_length=101,primary_key=True) class File(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) file = models.FileField(max_length=255, upload_to=user_directory_path) def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> path = instance.user.userID + "/" + filename return path -
ValueError: source code string cannot contain null bytes django
Whenever I try to run the server these error is popping up. Yesterday it was working fine. Tried for a long but don't get any solution for that. If anybody has any idea regarding this error this, Please let me know. Thankyou in advance, It will be kindful if you could do the needful. -
URL keeps on getting added after editing the form (Django)
I have got a problem while redirecting to the edit form. SO what I am doing is that whenever user clicks on edit button it redirects to "editadmin/{{admin.id}}" using form action = "editadmin/{{admin.id}}" in HTML. URL path is path("editadmin/<int:id>", views.editadmin, name="editadmin") path("updateadmin/<int:id>", views.updateadmin, name="updateadmin") Views.py @csrf_exempt def editadmin(request, id): admin = Admin.objects.get(id=id) return render(request, "editadmin.html", {"admin": admin}) @csrf_exempt def updateadmin(request, id): if request.method == "POST": admin_id = request.POST["admin_id"] admin_id = str(admin_id).strip().upper() name = request.POST["name"] name = str(name).strip() if db_name equals to name: messages.error(request, "Admin name already exists") return redirect("editadmin/" + str(id)) editadmin.html <form method="post" class="post-form" action="/update/{{admin.id}}"> <input type="hidden" name="id" id="id" required maxlength="20" value="{{ admin.id }}"/> {% csrf_token %} <div class="form-group row"> <label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Admin ID : </h4></label> <div class="col-sm-4"> <input type="text" name="admin_id" required style="margin-left:20px; height:38px; width:300px; border-radius: 5px" id="admin_id" value="{{ admin.admin_id }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Name : </h4></label> <div class="col-sm-4"> <input type="text" name="name" style="margin-left:20px; height:38px; border-radius: 5px; width:300px" required id="name" value="{{ admin.name }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <button type="submit" class="btn btn-success" style="margin-left:210px">Submit</button> </div> </div> So what I want is that Whenever user submits invalid name in editadmin.html (URL - editadmin/1 ), it should redirect to the same URL … -
How to display particular stuff of the registered person in profile page - Django
I have a member table, I want to fetch and display some of the fieldsets like fullname , email and phone number in the profile page. i had tried some of the codes using object.all() as well as using primary keys but i don't get the desired output . Thank you in advance i will we kindful if you could do the needful -
Give access to Django Admin (staff status) by adding to Group
To give a user the ability to login to the Django Admin, we set their staff flag. Is there a way to make a "staff" Group where everyone put into it gains access to the admin page without manually setting staff status? -
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration is applied before its dependency accounts.0001_initial on database 'default'
I'm trying to migrate my coustom user model but when i run makemigrations command that makes new models for migration. But when i run migrate command it throws error : django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. traceback Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\commands\migrate.py", line 95, in handle executor.loader.check_consistent_history(connection) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\db\migrations\loader.py", line 302, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. models.py class User(auth.models.AbstractUser): current_balance = models.IntegerField(("current balance"),default=0,blank=True) age = models.IntegerField(("age"),null=True) gender = models.CharField(("gender"), max_length=50,choices=GENDER_CHOICES,null=True) nationality = models.CharField(("nationality"), max_length=50,null=True) def __str__(self): return "@{}".format(self.username) I just mentioned user model in this question but still if more code is require then tell me i'll update my question with that information . Thank you -
ESP8266 with localhost
I have a django server running on localhost (127.0.0.1:8000), and I have trying to post sensor data to this url using ESP8266 but I can't connect with localhost keep getting connection failed message this is the code iam using in arduino #include <ESP8266WiFi.h> //#include <WiFiClient.h> //#include <ESP8266WebServer.h> const char* ssid = "ssid"; const char* password = "password"; const char* host = "127.0.0.1"; //String page = ""; double data; void setup(void){ pinMode(A0, INPUT); delay(1000); Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(""); while (WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to"); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void loop(void){ WiFiClient client; const int httpPort = 8000; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); delay(1000); return; } data = analogRead(A0); Serial.print("Requesting POST: "); // Send request to the server: client.println("POST / HTTP/1.1"); client.println("Host: server_name"); client.println("Accept: */*"); client.println("Content-Type: application/x-www-form-urlencoded"); client.print("Content-Length: "); client.println(String(data).length()); client.println(); client.print(data); delay(500); if (client.connected()){ client.stop(); } Serial.println(); Serial.println("closing connection"); delay(5000); } -
can I use input search in django form as as variable for a regular expression? not working now
def get_search(request,search, list): str1 = " " entries = str1.join(list) pattern = re.compile(r'{}.*.format(search)', re.IGNORECASE) matches = pattern.finditer(entries) -
Authentication problem while login with Custom User Model in Django
I created a custom user Model, that uses the Email field as the username. Also I had to create a Custom backend to validate as Case Insensitive the email field. The Registration page works perfectly fine, but when I try to login with a user that is not created I get this error: Environment: Request Method: POST Request URL: http://localhost:8000/members/login/ Django Version: 3.1.4 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'projects', 'about', 'blog', 'contact', 'members', 'ckeditor', 'django_bleach'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/DeveloperRoad/members/backends.py", line 14, in authenticate user = UserModel._default_manager.get(**{case_insensitive_user_name_field: username}) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/db/models/query.py", line 429, in get raise self.model.DoesNotExist( During handling of the above exception (BlogUser matching query does not exist.), another exception occurred: File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/decorators.py", line … -
Delete User from db Django Rest_framework View function
I am pretty new to the django_restframework. I want to be able to delete users from the database when a DELETE request comes in. Here is my Views: class RetrieveUsersView(generics.ListCreateAPIView): """Retrieves all Users""" serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = get_user_model().objects.all() Here is my Serializer: class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() fields = ('email', 'password', 'name') extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def create(self, validated_data): """Create a new user with encrypted password and return it""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update a user, setting the password correctly and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user Here is my Urls: urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views.ManageUserView.as_view(), name='me'), path('all_users/', views.RetrieveUsersView.as_view(), name='all_users') ] From my understanding Django rest has built in classes that allow DELETE requests. However when I view the api on the local host I am only able to view all the registered users based on my RetrieveUsersView class. I would expect the url to be something like /api/users/all_users/1 Then delete that one. I am bit confused on how to get that functionality.