Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
api_view with filter request.user and created_by?
I want to display only the conferences created by the user connected with the get_myconferences function but I don't understand why it doesn't work? do you have any idea please knowing that I have no UserSerializer or class user I used user from the rest framework -
adding attribute on option (django)
could someone help me? I have the following models (simplified): class Glass(models.Model): code = models.CharField() price = models.CharField () class QuoteItem(models.Model): first_glass = models.ForeignKey(Glass,on_delete=models.CASCADE) I need to generate a first_glass select that incorporates the "price" attribute of Glass within each option, but I can't do it, the idea is that it looks like this (eg). <option value="4" price="2000">IN06</option> I tried to incorporate solutions from stackoverflow but I have not been able to add the attributes -
How can i perform join operation in Django?
The project is basically a resume builder wherein user will fill all details in the form and the system will generate a resume . The database structure is somewhat like this:- user table:- for authentication. resumeinfo :- here details like personal info ,education info are stored projectinfo table:- each resume created by user can have 0/1/or multiple projects experienceinfo table:- each resume have have 0/1 or multiple experience info 1 user can create multiple resume. Each resume has a resumeinfo and can have 0 or more projects and experiences. **here are the django models ** class User(models.Model): fname=models.CharField(max_length=20) lname = models.CharField(max_length=20) gender = models.CharField(max_length=20) def __str__(self): return self.fname class Resdata(models.Model): fname=models.CharField(max_length=20) lname = models.CharField(max_length=20) school = models.CharField(max_length=20) resumeno=models.CharField(max_length=20) creatorid=models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.fname class Project(models.Model): ptitle=models.CharField(max_length=20) pdesc=models.CharField(max_length=20) resume=models.ForeignKey(Resdata,on_delete=models.CASCADE) def __str__(self): return self.ptitle class Exp(models.Model): etitle=models.CharField(max_length=20) edesc=models.CharField(max_length=20) resume=models.ForeignKey(Resdata,on_delete=models.CASCADE) def __str__(self): return self.etitle For example there are 2 users registered in user table jack bob jack creates 1 resume by entering all the details ,in this resume jack enters 3 project info and 2 experience info. Now jack creates 2nd resume by entering all the details ,in this resume jack enters only 1 project and has no experience I want to create … -
Django admin TabularInline and unique_together error 'dict' object has no attribute 'is_hidden'
my models: model.py class ModelA(Model): name = models.CharField('Name') class ModelB(Model): model_a = models.ForeignKey( ModelA, on_delete=models.SET_NULL, verbose_name='modelA', ) code = models.CharField('code') class Meta: unique_together = ('code', 'model_a',) In my admin.py: class ModelBInline(admin.TabularInline): model = ModelB fields = ('code', ) @admin.register(ModelA) class ModelAAdmin(admin.ModelAdmin): list_display = ( 'name', ) inlines = (ModelBInline,) If I change the code in TabularInline, and it is not unique, then I get an error: AttributeError at /admin/add/modelA/1/change/ 'dict' object has no attribute 'is_hidden' How to solve this problem? -
User Invitations based on invite links
my scenario is i have a teams model, team leads send out invite links to the team, url schema "domain/{team.id}/{team.name}/" i'm using dj_rest_auth for authentication, these invite links are sent to un-registered users. whne user clicks on url they are redirected to the signup view. now i need to add a user to the team(team id received in url) after they signup, i can't figure out how to pass the team id to user_sign_up post_save signal in allauth, django Sessionstore doesn't work as the key generated is different each time docs here, i'm new to django rest framework. i also looked at django globals, but that didn't help either. any help would be much much appreciated, app.views: from django.contrib.sessions.backends.db import SessionStore def inviteduser(request, pk, name): s = SessionStore() s['team-id'] = pk s.create() print(s.session_key) return redirect('http://localhost:8000/account/registration') accounts.signals: from allauth.account.signals import user_signed_up from django.dispatch import receiver from core.models import TeamMembers from django.contrib.sessions.backends.db import SessionStore @receiver(user_signed_up) def user_signed_up(request, user, **kwargs): s = SessionStore(session_key='gm0p279oeqvu385fy28btbyjzhak8a2j') # if request.session['team-id']: teamid = s['team-id'] # print(teamid) teammember = TeamMembers(member_id=user.id, team_id=teamid) teammember.save() i have a custom user model and a corresponding custom serializer. account.models: from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ … -
Anchor Tag href redirects to an untitled page
I want to use an <a/> tag which redirects to some page. But the problem is that when I click it, it doesn't open, and when I click on open in a new tab, it doesn't load properly. The url is correct but it won't load. You can see that the url is properly loaded, but the page wont load. But when I simply press enter in url, it loads somehow. Here's how I gave the href. <a href="{{HOST_BASE_URL}}art/search/art/all/"> It works if I manually add the value of {{HOSE_BASE_URL}} like this: <a href="http://localhost:8000/art/search/art/all/"> How do I resolve this? -
Getting User DNS Domain - Django/Angular app
Good morning! I have currently a django/angular application where my users use LDAP auth with multiple domains. I would like to get (via server-side or via frontend) the user dns domain, by meaning the equivalent to the environmental variable %USERDNSDOMAIN% in Windows so I can use dinamically this variable inside the server-side instead of having multiple url for each domain so I can have a global LDAP auth. For now I have the user IP, which is obtained directly from the request via django request: request.META.get('REMOTE_ADDR') So far I have tried getting the DNS from the given ip by using python dns library: dns.reversename.from_address("REQUEST_IP") and also using the python sockets library socket.gethostbyaddr('REQUEST_IP') The first one works but does not give the result I am looking for, and the second one does not work properly: ---> 10 socket.gethostbyaddr('REQUEST_IP') herror: [Errno 1] Unknown host Have a good day! -
Login,register and verify OTP API project with Django rest framework
I want to make an API project in which a person can Login, register with a phone number and OTP. What we need to do in this project Login and Register from the same page. Verify OTP from verify image. When user gets register for the first time mobile number, otp, a random username,a random picture from a folder,a random profile id, a name whic is the same as mobile number gets alloted in the database. Here's my code modals.py class User(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) logo = models.FileField(upload_to ='profile/') profile_id = models.CharField(max_length=200) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['mobile'] def create(self, validated_data): instance = self.Meta.model(**validated_data) global totp secret = pyotp.random_base32() totp = pyotp.TOTP(secret, interval=300) otp = totp.now() instance = self.Meta.model.objects.update_or_create(**validated_data, defaults=dict(otp=str(random.randint(1000 , 9999))))[0] instance.save() return instance class VerifyOTPSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['mobile','otp'] def create(self,validated_data): instance = self.Meta.model(**validated_data) mywords = "123456789" res = "expert@" + str(''.join(random.choices(mywords,k = 6))) path = os.path.join(BASE_DIR, 'static') dir_list = os.listdir(path) random_logo = random.choice(dir_list) instance = self.Meta.model.objects.update_or_create(**validated_data, defaults = dict(username = res,name = instance.mobile ,logo = random_logo, profile_id = res))[0] instance.save() return instance views.py def send_otp(mobile,otp): url = "https://www.fast2sms.com/dev/bulkV2" authkey … -
API design to avoid multiple model serializers (DRF)
I'm coding my backend with Django and my API with DjangoRestFramework. The thing is I'm wondering how to handle serializers in order not to have tons of them for a single model. Considering a model that represents, let's say, an InventoryItem (such as a computer). This computer can be linked to a category, a supplier, a company, a contact within that company... That makes relations to be serialized and it brings nested data into the returned Item. While I may need all these fields in a list view, I may not in the form view or in a kanban view. And if I want to, for instance, in the form view of a helpdesk ticket, have an autocomplete input component to link the ticket to that inventory item, I want only to have, let's say, the name of the Inventory Item, so returning a list of items with all the nested data would be a bit overkill since I need only its name. And you could say : Just make different serializers for the scenarios you need. I'd end up with something like : InventoryItemFormSerializer InventoryItemListSerializer InventoryItemInputSerializer (to be used for input components) Also for listing Items i'd use a … -
Same results consecutif
I have a table : output _df (image in the question) . Ienter image description here repetition of the same value for "PCR POS/Neg" consecutive in my "output_df". If i have 3 results identiques consecutifs , more than 3 times in the output_df so i need to give an error message "WARNING" in my index.html How i can do it ? views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict from django.contrib import messages import re import numpy as np def home(request): #upload file and save it in media folder if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls') and uploaded_file2.name.endswith('.txt'): savefile = FileSystemStorage() #save files name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'/media/'+name file_directory2 = d+'/media/'+name2 cwd = os.getcwd() print("Current working directory:", cwd) results,output_df,new =results1(file_directory,file_directory2) return render(request,"results.html",{"results":results,"output_df":output_df,"new":new}) else: messages.warning(request, ' File was not uploaded. Please use the correct type of file') return render(request, "index.html") #read file def readfile(uploaded_file): data = pd.read_excel(uploaded_file, index_col=None) return data def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) headers = ['Vector Name', 'Date and … -
Downside of logging with Email using AbstractUser Not AbstractBaseUser
I am entirely happy with Django default user model and I would like to extend it, AbstractUser seems to describe my situation, If you’re entirely happy with Django’s User model, but you want to add some additional profile information, you could subclass django.contrib.auth.models.AbstractUser and add your custom profile fields But I also learned If you wish to login with Email you should go with AbstractBaseUser, If you want to use an email address as your authentication instead of a username, then it is better to extend AbstractBaseUser My current model uses AbstractUser and not AbstractBaseUser, I can login with email just fine, What is the potential downside of this in the long run? I have plans to allow User login with either Email or Phone In the future, Now just Email, But it seems has something to do with AUTHENTICATION_BACKENDS regardless of which you use, What could potentially go wrong if I go ahead with AbstractUser or Should I be cautious go with AbstractBaseUser? According to Django Docs, It is very troublesome to change default user model to custom user model in mid project, Then how troublesome would it be to change AbstractUser to AbstractBaseUser? from django.db import models from … -
Reverse for 'delete_note' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_note/(?P<id>[0-9]+)/$']
I am facing this error while adding this in my html file <a href="{% url 'delete_note' i.id %}"class="btn btn-outline-danger">Delete</a> -
The admin login form does not allow the superuser to log in
When I try to login to the Django admin panel, I get an error: "This account has been disabled." However, the user status is active. I tried to register a new user through the console, but the error remained. You can enter the administration panel only by logging in to the site itself through the authorization form. I am using a custom user model. Here is my code: settings.py: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'users.backends.AuthBackend', ) users.backends class AuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password): return user def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user users.models class CustomAccountManager(BaseUserManager): def create_user(self, email, full_name, password, **other_fields): if not email: raise ValueError('Enter email') email = self.normalize_email(email) if not full_name: full_name = email.split('@')[0] user = self.model( email=email, full_name=full_name, **other_fields ) user.set_password(password) # other_fields.setdefault('is_active', True) user.save() return user def create_superuser(self, email, full_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) # other_fields.setdefault('is_author', True) other_fields.setdefault('is_active', True) if … -
Django -> ListView -> get_context_data() -> Model.objects.filter(self.object)
How do I grab each model object from a ListView? I have a blog and I'm trying to order each post's comments by the number of comment likes views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, *args, **kwargs): com = Comment.objects.filter(post=self.object?) #<--- WHAT TO INPUT HERE? comment_list = com.annotate(like_count=Count('liked')).order_by('-like_count') #BELOW DOESN'T WORK. EVERY POST HAS THE SAME COMMENT LIST AS THE LATEST POST.. SEE PICTURE BELOW # posts = Post.objects.all() # for post in posts: # com = Comment.objects.filter(post=post) #<--- what to input here # comment_list = com.annotate(like_count=Count('liked')).order_by('-like_count') #BELOW DOESN'T WORK. EVERY POST HAS THE SAME COMMENT LIST AS THE LATEST POST.. SEE PICTURE BELOW # posts = Post.objects.all() # #for post in posts: #comment_list = post.comment_set.all().annotate(like_count=Count('liked')).order_by('-like_count') context = super(PostListView, self).get_context_data(*args, **kwargs) context['cats_menu'] = cats_menu context['c_form'] = c_form context['comment_list'] = comment_list return context img link - latest post img link - all other posts copy the comments on the latest post models.py class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) liked = models.ManyToManyField(Profile, blank=True, related_name='com_likes') def __str__(self): return f"Comment:{self.user}-{self.post}-{self.id}" def post_id(self): return self.post.id def num_likes(self): return self.liked.all().count() … -
how to set disabled=false to all element in the Select>options , before the Ajax call which set disabled=true
Html <!DOCTYPE html> <html> <div class="wrapper"> {%if messages %} {% for message in messages %} <div class="alert {{ message.tags }} alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {{ message }} </div> {% endfor %} {% endif %} <div class="register-page"> <div class="register-container"> <form id="appointment-form" role="form" method="post" enctype='multipart/form-data'> <!-- SECTION TITLE --> <div class="section-title wow fadeInUp" data-wow-delay="0.4s"> <h2>Book Appointment</h2> </div> {% csrf_token %} <input name="patient_name" value="{{request.user}}" hidden> <div class="wow fadeInUp" data-wow-delay="0.8s"> <div class="col-md-6 col-sm-6"> <label for="name">Clinic name</label> {{ form.clinic_name }} </div> <div class="col-md-6 col-sm-6"> <label for="qualification">Doctor Name</label> {{ form.doctor_name }} </div> <!-- try --> <p id="p-text">foo bar</p> <div class="col-md-6 col-sm-6"> <label for="specialist"> Date</label> {{ form.date }} </div> <!-- try --> <p id="d-text">foo bar</p> <div class="col-md-6 col-sm-6"> <label for="location">Time slot </label> <!-- {{ form.time_slot }} --> <select name="time_slot" required="" id="id_time_slot"> <option value="" selected="">---------</option> <option value="09:00 - 10:00" id="op0">09:00 - 10:00</option> <option value="10:00 - 11:00" id="op1">10:00 - 11:00</option> <option value="11:00 - 12:00" id="op2">11:00 - 12:00</option> <option value="12:00 - 13:00" id="op3">12:00 - 13:00</option> <option value="13:00 - 14:00" id="op4">13:00 - 14:00</option> <option value="14:00 - 15:00" id="op5">14:00 - 15:00</option> <option value="15:00 - 16:00" id="op6">15:00 - 16:00</option> <option value="16:00 - 17:00" id="op7">16:00 - 17:00</option> <option value="17:00 - 18:00" id="op8">17:00 - 18:00</option> </select> </div> <div class="col-md-12 … -
Separate Model classes into Separate Files Django
ku-polls/ manage.py polls/ init.py apps.py forms.py tests.py views.py models/ init.py question.py choice.py How to run 'python manage.py makemigrations' folder models? -
How to add Yahoo Finance API with flask or django
My question is we can see in app.py as a (default="AMZN") i need to get an user input (or) a user can click on the company name to see more info and proceed further for each companys. I'm trying to learn flask and built a small app that contains a list of companies with some general info for each of them. The home page shows a list of all companies and then a user can click on the company name to see more info. I'm now trying figure out how APIs are consumed in flask by using Yahoo Finance to get some stock data about the company and display it on the page. It is fine flask or django web frame work. Also, I need a guidance from scratch. I am beginner. import yfinance as yahooFinance # Here We are getting Facebook financial information # We need to pass FB as argument for that GetInformation = yahooFinance.Ticker(input("enter iput here: " )) #GetInformation = yahooFinance.Ticker("FB") # whole python dictionary is printed here print(GetInformation.info) My code app.py from flask import Flask, redirect, url_for, render_template, request import yfinance as yf app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' @app.route("/login", methods=["POST", "GET"]) def … -
How to implement multiple fields search in Django?
The problem is implementing a search across multiple fields. There is a sqllite database, there is a table and one search button on the page, the user enters a value into the fields (it is not necessary to fill in all the fields, it is filled in randomly). I'm just starting to learn django, don't judge strictly) Thanks! models # Год class Year(models.Model): title = models.CharField(max_length=4, verbose_name='Год') slug = models.SlugField(max_length=4, verbose_name='Slug Год', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('year', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Год' verbose_name_plural = 'Год' ordering = ['title'] # Наименвоание объекта class Subject(models.Model): title = models.CharField(max_length=100, verbose_name='Наименование объекта') slug = models.SlugField(max_length=100, verbose_name='Slug Наименование объекта', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('subject', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Наименвоание объекта' verbose_name_plural = 'Наименвоание объекта' ordering = ['title'] # Вид обследования class Surveys(models.Model): title = models.CharField(max_length=200, verbose_name='Вид обследования') slug = models.SlugField(max_length=200, verbose_name='Slug Вид обследования', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('surveys', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Вид обследования' verbose_name_plural = 'Вид обследования' ordering = ['title'] # Пост class Post(models.Model): title = models.CharField(max_length=100, verbose_name='Пост', blank=False, null=True, ) slug = models.SlugField(max_length=100, verbose_name='Slug Пост', unique=True) content = models.TextField(blank=True, verbose_name='Контент') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Опубликовано') document … -
Problem with "import" when trying to create a Django project in virtual environment with VS code
This is the problem i have, including another one (the solution on this link didn't solve it): How to resolve 'Import "django.contrib" could not be resolved from source' in VS Code? As a bachelors project we are supposed to do an website with django and React. Our university wants us to do it with a lniux-based virtual environment. I followed this tutorial: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react I can run the server with "python manage.py runserver" at first and it works, but when i try to import from for example ".model" errors arise and i can't run the server. I'm running windows and have installed "wsl" to get into a Linux virtual machine first. Then i install a virtual environment in the linux machine. I have set the python interpreter as the one i'm using in my VENV and it sticks. What can i try? Please help i've been stuck on this all day. I tried setting python interpreter as the one in the virtual environment, update python in the virtual environment, tried install the virtual environment in windows instead (a lot of other errors came up, won't be trying that again), tried follow differend tutorials which did it in different ways. The same … -
Form UpdateView and DeleteView and 3 hierarchical models
I am trying to create an 'Expense Tracker'. I have query regarding UpdateView and DeleteView and Models with 3 hierarchical levels. I was able to create the CreateView for the 'Expense' model, but the update and delete view are throwing a lot of errors. Can you please tell how to write the code for update and deleteview (for 'Expense' model). Models.py class Year(models.Model): year = models.IntegerField(choices=year_choices() ,validators=[MinValueValidator(1984), max_value_current_year], name='year', unique = True) def __str__(self): return str(self.year) class Meta(): ordering = ('-year','-year') class Month(models.Model): month = models.CharField(choices=month_choices(), max_length=264) month_year = models.ForeignKey(Year,related_name = 'month',on_delete=models.CASCADE) def __str__(self): return str(self.month) + ' ' + str(self.month_year) def get_absolute_url(self): return reverse("Expense_App:Year") class Meta(): unique_together = [['month','month_year']] class Expense(models.Model): Home_Expense = models.PositiveIntegerField() Groceries = models.PositiveIntegerField() Electronics = models.PositiveIntegerField() Snacks = models.PositiveIntegerField() Other = models.PositiveIntegerField() total = models.PositiveIntegerField() expense_month = models.ForeignKey(Month,related_name = 'expense', on_delete=models.CASCADE) def __str__(self): return str(self.expense_month) + ' ' + str(self.total) def get_absolute_url(self): return reverse("Expense_App:Year") Forms.py #forms.py class ExpensesForm(forms.ModelForm): class Meta(): model = Expenses fields = ('expenses','expense_month') def __init__(self, *args, **kwargs): month_year_id = kwargs.pop('month_year_id') super(ExpensesForm, self).__init__(*args, **kwargs) self.fields['expense_month'].queryset = ExpenseMonth.objects.filter(month_year_id=month_year_id) Views.py #createview for 'expense' model class ExpenseCreateView(CreateView): model = models.Expense form_class = ExpenseForm def get_form_kwargs(self): kwargs = super(ExpenseCreateView, self).get_form_kwargs() kwargs.update({'month_year_id': self.kwargs.get('pk')}) return kwargs Urls.py Update and … -
Django - unique_together with nested field in M2M
I have two model like A and B that have many-to-many relation on ids. B has a field like "type" and it maybe have many record with similar "type". i want manage this relation on every A related to one "type" no more. class throughModel(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) class Meta: unique_together = ['a', 'b__type'] but dosen't work and i have no idea for implementation this. -
PGsql delete fields on a table and related on anoter in one command
In my django project i have two models: class Results(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", primary_key=True, unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) and class VarsResults(models.Model): id = models.AutoField(primary_key=True) on_delete=models.CASCADE) key_res = models.ForeignKey(Results, related_name="keyres", on_delete=models.CASCADE) var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL) var_val = models.CharField(max_length=400, blank=True) var_val_conv = models.CharField(max_length=100, blank=True, null=True) var_hash = models.CharField(max_length=400) has_error = models.BooleanField(default=False) so VarsResults has a key_res ForeignKey to table Results. I would, using PGSql create a query for delete ALL data starting from Results from a certain data and automatically delete the related rows in VarsResults like thisone: DELETE FROM Results WHERE read_date < "2022-01-01" (and delete also the related VarsResults rows) So many thanks in advance Manuel -
i have tried email validations and it was successfull but, I wantnthis error as popup alert
i have tried email validations and it was successfull but, I want this error as popup alert. forms.py class RegisterForm(forms.Form): MailID = forms.CharField(max_length=50, widget=forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Enter Mail_ID'})) validation: def clean_MailID(self): mail = self.cleaned_data.get("MailID") rows = StudData.objects.filter(MailID=mail) if rows.count(): msg="mail already exits" raise ValidationError(msg) return mail i want to change error msg with email already exists to alert popup in window. -
CSRF cookie not set when calling POST request API view
I have encountered a weird behavior as it works with one view but does not with another. Django 3.2 and rest framework 3.13.1 are currently installed within the venv. When I call the view I get the error message: CSRF validation failed, reason CSRF cookie not set. This view uses an own authentication class that extends TokenAuthentication. class APIKeyAuthentication(authentication.TokenAuthentication): logger = logging.getLogger(__name__) def authenticate(self, request): # try to get api key via X-API_KEY api_key = request.META.get("HTTP_X_API_KEY") # try to get api key via Authorization if not api_key: api_key = request.META.get("HTTP_AUTHORIZATION") if not api_key: return None platform_id, api_user = self.validate_api_token(api_key) return api_user, None That class is used as default within rest framework: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "api.authentification.APIKeyAuthentication", "rest_framework.authentication.BasicAuthentication", ), "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], Endpoints are: path("v1/combinedEntries", VerifyV1OrderView.as_view()), path("order/verify/", VerifyOrderView.as_view()), Classes: class VerifyV1OrderView(GenericAPIView): serializer_class = CombinedEntryV1Serializer authentication_classes = (APIKeyAuthentication,) and class VerifyOrderView(GenericAPIView): serializer_class = CombinedEntrySerializer authentication_classes = (APIKeyAuthentication,) so I do not understand the error I even removed the session authentication from the config but without any change. Has someone an idea what the problem could be? Thanks and regards. Matt -
Django Rest Framework - "You do not have permission to perform this action" in tests
I have Profile model which is custom user model. When I try to change it (sending patch request) via postman, all is ok. But when I try to do it in tests in returns "You do not have permission to perform this action" in response with ststus code 403. Here is code: # models.py class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) user_name = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=50) surname = models.CharField(max_length=50) start_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to=photo_upload, default = 'profile_pics/default_avatar.jpg', null=True, blank = True) about = models.TextField(max_length=1024, blank = True, null = True) is_staff = models.BooleanField(default = True) is_active = models.BooleanField(default = True) objects = ProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] objects = ProfileManager() def get_absolute_url(self): return reverse('user', kwargs = {'pk': self.pk}) def __str__(self): return f'{self.user_name}' def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.image: self.image = f"{os.path.join(MEDIA_ROOT, 'profile_pics')}/default_avatar.jpg" else: 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)` # serializer class class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['email', 'user_name', 'first_name', 'surname', 'start_date', 'image', 'about', 'contacts'] read_only_fields = ['start_date', 'user_name'] # views.py class DetailUpdateDestroyUserAPI(RetrieveUpdateDestroyAPIView): Profile = apps.get_model('account', 'Profile') serializer_class = ProfileSerializer permisson_classes = [UserIsHimselfOrRO] lookup_field = 'user_name' def …