Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
not good template loaded in Django generic list view when using filter
I have a strange behavior im my generic views. Below is the classic FBV scheme I want to reproduce in a CBV My FBV def post_list(request, tag_name=None): if tag_name: # filter post according to tag name if provided posts = Post.objects.filter(tag__tag_name=tag_name) else: posts = Post.objects.all() context = {"posts": posts} return render(request, "blog/post_list.html", context) def post_detail(request, post_id): post = Post.objects.get(pk=post_id) context = {"post": post} return render(request, "blog/post_detail.html", context) My CBV class PostList(ListView): model = Post context_object_name = "post_list" template_name = "blog/post_list.html" def get_queryset(self): if "tag_name" in self.kwargs: return Post.objects.filter(tag__tag_name=self.kwargs["tag_name"]) else: return Post.objects.all() class PostDetail(DetailView): model = Post context_object_name = "post_detail" template_name = "blog/post_detail.html" Here are my models from django.db import models # Create your models here. class Tag(models.Model): tag_name = models.CharField(max_length=100) def __str__(self): return self.tag_name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() tag = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title And here my urls from django.urls import path from .views import PostList, PostDetail urlpatterns = [ path("", PostList.as_view(), name="blog-index"), path("<tag_name>", PostList.as_view(), name="blog-index"), path("<int:pk>", PostDetail.as_view(), name="post-detail") ] As you can see I want to use the same generic view for the list of my posts with an optional tag provided in url. It is well filtering my articles when I provide … -
Django: How to create a user action log/trace with vizualization
I am looking for a tool to track user actions like: user logged in user changed password user got bill via email user logged user uploaded image user send message ... which I can include into my Django project. Afterwards I want to build queries and ask the system stuff like: how often did a user a message within a month how often did a user login within a month does the user uploaded any images and I would like to have some kind of interface. (Like google analytics) Any idea? I am pretty sure that this is a common task, but I could not find anything like this. -
object has no attribute 'is_vallid'
I wrote a function with which you can change the data you entered during registration. But Django throws the following error : AccountUpdateForm object has no attribute 'is_vallid' here is my code, tell me where I made a mistake def account_view(request): if not request.user.is_authenticated: return redirect("login") context = {} if request.POST: form = AccountUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: form = AccountUpdateForm( initial={ "email": request.user.email, "username": request.user.username, } ) context['account_form'] = form return render(request,'account/account.html', context) -
Why can't I display my data filtered to active user?
I'm trying to display only data for the logged in user in my table. I can display everything using objects.all() but when I filter to the active user, it doesn't work. I have tried changing my context to refer to the queryset as a whole but I get an error saying that I can't perform get on a tuple. If I have the context as is, I get an error saying 'QuerySet object has no attribute 'user' Models.py: class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"{self.user} | {self.date}" Views.py: def health_history(request): queryset = HealthStats.objects.filter(user=request.user).values() print(queryset) print(type(queryset)) context = { "user": queryset.user_id, "weight": queryset.weight, "date": queryset.date, "run_distance": queryset.run_distance, "run_time": queryset.run_time, } return (request, 'health_hub_history.html', context) health_hub_history.html: {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 text-center"> <h1>My Health History</h1> </div> </div> </div> <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-auto text-center p-3"> <table class="table table-striped table-hover table-bordered"> <tr> <td>User:</td> <td>Weight (lbs):</td> <td>Date:</td> <td>Run Distance (km):</td> <td>Run Time (HH:MM:SS):</td> </tr> {% for stat in queryset %} <tr> <td>{{ stat.user }}</td> <td>{{ … -
Django Backend architecture for multiple projects with shared class models
We are using Django to develop our product. Our product contains 5 Django projects. Each project uses 50 shared class Models and models are in the developing process. There are two possible ways to handle all these related projects with models in the development and production process: One possible solution is to use models in one project with all migration files and use them in other projects with managed=False in the Django class model. But the problem with this structure is: Each change in original models must apply to other projects This approach makes the production process repeatedly and hard to manage properly New features in each project are connected to model changes By adding new required fields to an existing model, other projects that create new instances from the updated model would face rational problems. Even if they don't use these new fields The other possible solution is gathering all projects as one project with the below diagram: Diagram Now this configuration's problem is: Complicated deploying production Complicated to route the project All deployed services should redeploy with every change in one model All of the projects are in one place My question is: Whether the suggested solutions are … -
How can I connect Firebase DB to Django project in Python
Do you know whether it is possible to connect to the Firebase database through the Django framework in Python instead of SQL, SQLLite3, or PostgreSQL, etc., In the event that it is possible to connect Firebase DB to Django, can anyone please assist me in connecting Firebase DB to Django? -
Is there a way of pulling data.id from your frontend using JS to the views in django ... heres my code .... n I can't seem to find the error [closed]
#form to return to db if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # store all the billing info data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.street = form.cleaned_data['street'] data.location = form.cleaned_data['location'] data.county = form.cleaned_data['county'] data.city = form.cleaned_data['city'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.ip = request.META.get('REMOTE_ADDR') #data.save() # generate order number yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr, mt, dt) current_date = d.strftime("%Y%m%d") order_number = current_date + str(data.id) data.order_number = order_number data.save() order=Order.objects.get(user=current_user, is_ordered=False, order_number=order_number) context={ 'order':order, 'cart_items':cart_items, 'total':total, 'tax':tax, 'grand_total':grand_total, } return render(request,'orders/payments.html', context) else: return redirect('checkout') #to pull data id function getCookie(name){ let cookieValue = null; if (document.cookie && document.cookie !== ''){ const cookies = document.cookie.split(';'); for (let i=0; i response.json()) .then((data) => { window.location.href = redirect_url+'?order_number='+data.order_number+'&payment_id='+data.transID; //window.location.href = redirect_url +'?order_number='+data.order_number+'&payment_id='+data.transID; }); } }); } }).render('#paypal-button-container'); -
Django search field in the database
is it possible to change my display employe to a search block because when I select the numbers it displays a list which is not practical when I have a lot of numbers in my database. add info to an existing employee -
Django PasswordResetDoneView does not redirect to login
I have a reset password procedure, here are the codes: Password Reset Request: <form method="POST"> {% csrf_token %} <div class="wrap-input100 validate-input input-group" data-bs-validate="Format email valide requis: ex@abc.xyz"> <a class="input-group-text bg-white text-muted"> <i class="zmdi zmdi-email text-muted" aria-hidden="true"></i> </a> <input id="id_email" class="input100 border-start-0 form-control ms-0" type="email" placeholder="Email" name="email" autocomplete="email" maxlength="254"> </div> <button class="btn btn-primary" type="submit">Envoyer le lien de réinitialisation</button> </form> Password Reset Confirmation: <form method="POST"> {% csrf_token %} <div class="wrap-input100 validate-input input-group" id="Password-toggle"> <a class="input-group-text bg-white text-muted"> <i class="zmdi zmdi-eye text-muted" aria-hidden="true"></i> </a> <input class="input100 border-start-0 form-control ms-0" type="password" placeholder="Nouveau mot de passe" id="id_new_password1" name="new_password1"> </div> <div class="wrap-input100 validate-input input-group" id="Password-toggle"> <a class="input-group-text bg-white text-muted"> <i class="zmdi zmdi-eye text-muted" aria-hidden="true"></i> </a> <input class="input100 border-start-0 form-control ms-0" type="password" placeholder="Confirmation du nouveau mot de passe" id="id_new_password2" name="new_password2"> </div> <div class="container-login100-form-btn"> <button class="login100-form-btn btn-primary" type='submit'>Réinitialiser</button> </div> </form> Password Reset View: def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data["email"] associated_users = Account.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Demande de changement de mot de passe" email_template_name = "core/email/password_reset_email.txt" c = { "email": user.email, "domain": EMAIL_DOMAIN, "site_name": "XXXXXX.XXXX", "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, "token": account_activation_token.make_token(user), "protocol": EMAIL_PROTOCOL, } email = render_to_string(email_template_name, c) try: send_mail( subject, email, "info@XXXXXX.XXXX", [user.email], fail_silently=False, ) … -
Install Django apps through the Django admin-site like plugins in Wordpress
I want to implement a module-manager in Django where third-party modules can be installed through the django admin interface (without changing the code-base of the main project). These modules should have the same capabilities as a django app. For example, defining models and views, making migrations, and interacting with other apps. Similar to how it works with the plugin-manager of Wordpress. Is there a good way to do this? (and are there reasons why I should not?) -
Maximum recursion depth while applying a Listing filter in django
I am trying to implement Listing Filter from django filters. First "type" is the attribute that I want my filter to be based inside models.py of my app. class detaileditems(models.Model): title = models.CharField(max_length= 255) type = models.CharField(max_length= 45, null=True) pubdate = models.DateTimeField() body = models.TextField() image = models.ImageField(upload_to= 'images/') I have created a separate filters.py inside my application where I have called the filters. import django_filters from .models import detaileditems class ListingFilters(django_filters.FilterSet): class Meta: model = detaileditems fields = {'type': ['exact']} Next here is my function inside views.py file- from .models import detaileditems from .filters import ListingFilters def alldetailed2(request): items = detaileditems.objects listing_filter = ListingFilters(request.GET, queryset=items) context = { 'listing_filter' : listing_filter, 'items': items, } return render(request, 'detailed2/detailed2.html',context) Lastly in my html file "detailed2.html" which is inside the application template folder of "detailed2". <div class = "col-lg-6 col-md-8 mx-auto"> <form method = "get"> {{ listing_filter.form }} <button class="btn btn-sm btn-danger" type="submit">Search</button> </form> </div> <div class = "container"> <div class = "row row-cols-1 row-cols-sm2 row-cols-md-3 g-3"> {% for listing in listing_filter.qs %} <div class = "col"> {% include "detailed2/detailed2.html" %} </div> {% endfor %} </div> </div> I am getting a maximum recursion depth error. -
Alter default django models tables generation
I'm trying to create two related models in django, a custom user model and a company model. where one user belongs to one company and one company has many users. class Company(models.Model): name = models.CharField(max_length=255) class User(AbstractBaseUser): objects = UserManager() id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True) name = models.CharField(max_length=67) username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) last_login = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_supuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True By default django generated two tables like this: But I dont want any foreign keys directly on those tables, instead i want a third auxiliary table with the two foreign keys from the models like this: How could I do something like that ? -
Where to store training data files in Django for a Chatbot?
I am trying to display a chatbot that I created on a django site. So I need to load some training data (json, pickle and h5 files) into views.py file. But when I run the server it says: FileNotFoundError: [Errno 2] No such file or directory: 'mysite/polls/intents.json' even though views.py and intents.json are in the same folder. So now I am wondering where I should store these files and how to open/import them into my views.py file. Do I need to put them into my static files folder or something like that? Here is the code from the views.py file: from django.shortcuts import render from django.http import HttpResponse import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() import pickle import numpy as np from keras.models import load_model import json import random # Create your views here. def index(request): intents = json.loads(open('intents.json').read()) model = load_model('chatbot_model.h5') words = pickle.load(open('words.pkl','rb')) classes = pickle.load(open('classes.pkl','rb')) def clean_up_sentence(sentence): sentence_words = nltk.word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] return sentence_words # return bag of words array: 0 or 1 for each word in the bag that exists in the sentence def bow(sentence, words, show_details=True): # tokenize the pattern sentence_words = clean_up_sentence(sentence) # bag of words - … -
Django rest not showing list error in corresponding index
I have a service that accepts a datetime list. I am deliberately sending a list which has the error its 1. index. Error should be returned as an array which has 1. index, but it returns as shown below. The dates field is a RelatedField and many=True post_data=["2020-01-01","a"] Expected error response; 'dates': { '1': { ['Incorrect format. Expected iso format.'] } } Real error response; 'dates': ['Incorrect format. Expected iso format.'] models.py class EventModel(models.Model): title = models.CharField(max_length=100, null=False, blank=False) address = models.CharField(max_length=255, null=False, blank=False) def __str__(self): return self.title class EventDateTimeModel(models.Model): date_time = models.DateTimeField(null=False, blank=False) event = models.ForeignKey('EventModel', on_delete=models.CASCADE, related_name='dates') def __str__(self): return self.date_time.isoformat() serialziers.py class DateTimeReleatedField(serializers.RelatedField): default_error_messages = { 'incorrect_type': 'Incorrect format. Expected iso format', } def to_internal_value(self, data): try: if not isinstance(data, str): raise TypeError return datetime.fromisoformat(data) # str to datetime object in post data except (TypeError, ValueError): self.fail('incorrect_type', data_type=type(data).__name__) def to_representation(self, value): return str(value) # using "EventDateTimeModel" model's __str__() method class EventSerializer(serializers.ModelSerializer): dates = DateTimeReleatedField(many=True, queryset=EventDateTimeModel.objects.all(), required=True) class Meta: model = EventModel fields = ['id', 'title', 'address', 'dates'] def create(self, validated_data): dates = validated_data.pop('dates', None) with transaction.atomic(): instance = super().create(validated_data) if dates: for date_time in dates: EventDateTimeModel.objects.create(date_time=date_time, event=instance) return instance def update(self, instance, validated_data): dates = validated_data.pop('dates', None) … -
how to retrieve latest data from django model in tamplates
i am trying to retrieve latest single data from Django model and show it in templates instead of all the data the method I trying to use in my view to achieve that def preview(request): readme = Personal_readme.objects.latest('create_date') return render(request, 'preview.html',{'readme':readme}) and in my models create_date = models.DateTimeField(default=timezone.now,editable=False) but when I runserve and refer to a page it TypeError at /preview/ Personal_readme' object is not iterable it work fine when use this readme = Personal_readme.objects.all() but retrieve all the data in it but i want to retrieve single(one) the latest data based on create_date I have no idea why its is show like this -
Registration Form error cant seem to locate
I am using Django in Mac. Last week, the registration is good but now when I rerun it I encountered a problem and I cant seem to figure out where the problem lies. Hope someone can help me. Thank you error: [19/Sep/2022 20:24:50] "POST /registerUser/ HTTP/1.1" 200 6995 /opt/homebrew/lib/python3.9/site-packages/PIL/Image.py:3011: DecompressionBombWarning: Image size (139513096 pixels) exceeds limit of 89478485 pixels, could be decompression bomb DOS attack. warnings.warn( invalid form <bound method BaseForm.non_field_errors of < UserForm bound=True, valid=True, fields=(first_name;middle_name;last_name;username;email;mobile_number;password;confirm_password)>> Views def registerUser(request): if request.user.is_authenticated: messages.warning(request, "You are already logged in!") return redirect ('myAccount') elif request.method == 'POST': form = UserForm(request.POST) m_form = MemberForm(request.POST, request.FILES) try: if form.is_valid() and m_form.is_valid(): first_name = form.cleaned_data['first_name'] middle_name = form.cleaned_data['middle_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] mobile_number = form.cleaned_data['mobile_number'] password = form.cleaned_data['password'] user = User.objects.create_user(first_name=first_name, middle_name=middle_name, last_name=last_name, username=username, email=email, mobile_number=mobile_number, password=password) user.role = User.MEMBER user.save() member = m_form.save(commit=False) member.user = user member.save() # send verification email mail_subject = 'Please Activate Your Account' email_template = 'accounts/emails/account_verification_email.html' send_verfication_email(request, user, mail_subject, email_template) messages.success(request, 'You have signed up successfully! Please check your email to verify your account.') print(user.password) return redirect('signin') except Exception as e: print('invalid form') messages.error(request, str(e)) else: form = UserForm() m_form = MemberForm() context = { … -
Django - pass file path/url from html to view in order to change the source of my video stream
Hello I am fairly new to the Django and html world and and would like to be able to select a video file and then play it in an edited version (ai classification and some opencv editing). At the moment, playing of a local file works in that way that the file path of my dummy video file is fixed in my script where I load the VideoStream. However, I would like to be able to specify via html input which file to load. I have the problem that I do not know how to pass the selected file. Via urls parameters can be passed, but I do not know how I can pass the path or url of the video file as a parameter. Or can something like this be achieved via post requests and if so how? Here are parts of my script (I don't use post request for this atm): <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input id="myFileInput" type="text"> <input class="button1" id="inputfield" name="upload" type="file" accept="video/*" onchange="document.getElementById('myFileInput').src = window.URL.createObjectURL(this.files[0]); document.getElementById('buttonStart').className = 'button'; this.form.submit()" value="Select a File"/> </form> The file path is stored in 'myFileInput'. But I could also get the file path through post request. Then I … -
sending same attachments with different mails with Django mail
I'm sending mail with Django mailer from django.core.mail import send_mail,EmailMessage If i send one mail all is working and attachment is on mail and correctly opening in pdf. content = template.render(context) msg = EmailMessage(subject, content, from_email, ['mail@mail.com']) msg.content_subtype = 'html' msg.attach(invoice.name, invoice.read(), 'application/pdf') msg.send() If I want create new message with same attachment in same function msg1 = EmailMessage(subject, content, from_email,['mail@mail.com']) msg1.content_subtype = 'html' msg1.attach(invoice.name, invoice.read(), 'application/pdf') msg1.send() mail is sent but attachment can't be opened. Can't determine why is acting like this. What would be correct way to create new Email message? -
How to filter my data to the active user in Django?
I'm trying to pull through only the latest data for the active user to my Django template. However, I'm currently receiving the below error. Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7f0682901a90>. Models.py: class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"{self.user} | {self.date}" Views.py: def health_hub(request): model = HealthStats def get_queryset(self): user = self.user latest = HealthStats.objects.filter(user=user).latest('date') return latest context = { "user": model.user, "weight": model.weight, "date": model.date, "run_distance": model.run_distance, "run_time": model.run_time, "stats": HealthStats, "latest": get_queryset(model) } return render(request, 'health_hub.html', context) health_hub.html: {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 text-center"> <h1>My Health Summary</h1> </div> </div> </div> <div class="container-fluid"> <div class="row justify-content-center"> <h3>Welcome {{ latest.user }}!</h3> <p>Please see below for your latest stats:</p> <table class="table table-bordered"> <tr> <td>Weight: {{ latest.weight }}</td> <td>Run Distance: {{ latest.run_distance }} km</td> </tr> <tr> <td>Run Time: {{ latest.run_time }}</td> <td>Last Updated: {{ latest.date }}</td> </tr> </table> According to the error message, it looks like there is an issue with what I'm trying to pull through, but I'm not sure … -
Testing update view: how to pass.change value data in updateview with form?
I try to write testcase for one of my view that use a form. views.py def parametrage(request,pk): parametrage = get_object_or_404(Parametrage, asp_par_cle = pk) form = ParametrageForm(request, data=request.POST or None, instance = parametrage) print('form.data',form.data) if form.is_valid(): parametrage = form.save() parametrage.opr_nom = request.user.username parametrage.opr_dat = timezone.now() form.save() return redirect('pharmacy:dashboard') return render(request, 'pharmacy/parametrage.html', {'form': form}) tests.py class PharmacyParametrageTestCase(TestCase): def setUp(self): Parametrage.objects.create(asp_par_loc='TR',asp_par_ale=1,asp_par_con=8) def test_email_alert(self): instance = Parametrage.objects.get(asp_par_cle=1) data = json.dumps({"asp_par_ale":2,}) response = self.client.post(reverse('pharmacy:parametrage', kwargs={'pk':1}),instance=instance, data=data, follow=True, content_type='application/json') self.assertEqual(response.status_code,200) self.assertEqual(Parametrage.objects.get(asp_par_cle=1).asp_par_ale,2) The second assert failed because Parametrage instance is not updated. form.is_valid() return False and form.errors do not return any error. form.data is empty obviously, I never change asp_par_ale value but don't know how to do that in tests. I try to pass data but doesn't work neither appreciate some help -
Django video uploads new video not display
I'm using django 3, when I upload a video from the admin panel, it doesn't appear on the page. When I go to the video url, I get a 404 error, but my old uploads are visible, and the newly uploaded files are not visible. My English is not very good, I translated it with google translate and I'm sorry if there are any mistakes -
serve() is called twice everytime I reload a blog page in wagtail
I am using wagtail to build a blog website. In order to count the visits of each blog, I override the get_context() and serve() to set cookie. The codes are as follows: def get_context(self, request): authorname=self.author.get_fullname_or_username() data = count_visits(request, self) context = super().get_context(request) context['client_ip'] = data['client_ip'] context['location'] = data['location'] context['total_hits'] = data['total_hits'] context['total_visitors'] =data['total_vistors'] context['cookie'] = data['cookie'] context['author']=authorname return context def serve(self, request): context = self.get_context(request) template = self.get_template(request) response = render(request, template, context) response.set_cookie(context['cookie'], 'true', max_age=3000) return response And the function count_visits is as follows: def count_visits(request, obj): data={} ct = ContentType.objects.get_for_model(obj) key = "%s_%s_read" % (ct.model, obj.pk) count_nums, created = VisitNumber.objects.get_or_create(id=1) if not request.COOKIES.get(key): blog_visit_count, created =BlogVisitNumber.objects.get_or_create(content_type=ct, object_id=obj.pk) count_nums.count += 1 count_nums.save() blog_visit_count.count += 1 blog_visit_count.save() The problem I met is that when I reload the blog page, serve() was loaded twice. The first time request was with cookie info. But the second time the cookie of the request was {}, which caused the count of visit does not work correctly. I do not understand why serve() is called twice everytime I reload page. -
How to check if the email/username already exists in the db in django?
How to check if the email_id/ username already exists in the database in django? I want to check the existence of the email/username in the views rather than in serializer. Following is the code: @api_view(['POST']) def registerUser(request): f_name = request.data.get('f_name') l_name = request.data.get('l_name') username = request.data.get('username') email_id = request.data.get('email_id') password = make_password(request.data.get('password')) RegistrationRegister.objects.create( f_name = f_name, l_name = l_name, username = username , email_id = email_id, password = password, created = datetime.datetime.now().isoformat() ) return Response("User registered successfully ") The name of the table is RegistrationRegister. How can I validate the email and check if it exists in the db? -
Register data by multiple select django
I'm a beginner and I was trying to create a registered data form in the database, all the fields are registered well instead of the multiple select fields. from.py class SavePost(forms.ModelForm): user = forms.IntegerField(help_text = "User Field is required.") title = forms.CharField(max_length=250,help_text = "Title Field is required.") description = forms.Textarea() dep = forms.Textarea() class Meta: model= Post fields = ('user','title','description','file_path', 'file_path2', 'dep') HTML <div class="form-group mb-3 "> <label for="exampleFormControlSelect2"> multiple select</label> <select multiple class="form-control" id="dep" value={{ post.title }}> <option>Process</option> <option>Product</option> <option>Equipment</option> </select> </div> <div class="form-group mb-3 "> <label for="title" class="control-label">Title</label> <input type="text" class="form-control rounded-0" id="title" name="title" value="{{ post.title }}" required> </div> <div class="form-group mb-3"> <label for="description" class="control-label">Description</label> <textarea class="form-control rounded-0" name="description" id="description" rows="5" required>{{ post.description }}</textarea> thank you in advanced -
Display field from another model in ModelAdmin of User model
My Django project is based on built-in User model. For some extra attributes, I have defined another model: models.py: class Status(models.Model): email = models.ForeignKey(User, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=False) def __str__(self): return self.email And here's the custom ModelAdmin: admin.py: class CustomUserAdmin(UserAdmin): model = User list_display = ['email'] search_fields = ['email'] I want list_display to show me is_verified and is_active fields from Status model but I'm lost. I've looked into some similar questions on SO like Display field from another model in django admin or Add field from another model Django but none of the solutions are applicable because one of my models is Django's built-in.