Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass kwargs to the django signals
I want to send kwargs to Django signals from my serializer which is actually creating an object of a model User. Here is the create method of serializer - @transaction.atomic def create(self, validated_data): company = validated_data.pop('company') user_group = validated_data.pop('user_group') user_group = Group.objects.get(name=user_group) company = CompanyDetails.objects.create(**company) validated_data['company'] = company user = User.objects.create_user(**validated_data) user_and_group = user.groups.add(user_group) return user The User model also has a manager class as stated below - class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, mobile_number, password, company, is_mobile_number_verified=None, is_email_varified=None, is_active=None): if not email: raise ValueError("You need an email to create account") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, mobile_number = mobile_number, password = password, company = company, is_mobile_number_verified = is_mobile_number_verified, is_email_varified = is_email_varified, is_active = is_active ) user.set_password(password) user.save(using = self._db) return user In models.py I have connected to User model's post_save signal as shown below - signals.post_save.connect(user_post_save, sender=User) user_post_save is receiver method which sends email to the newly registered users. I want this method to send email only if user is registered as Organisation Admin. So how do I pass a flag as Organisation Admin= True to the receiver from my serializer's create method. -
Why does my apache2 server temporarily crash when I submit forms on my django website?
I have made a website using Django. It has login functionality and allows you two create, update and like posts. It works correctly on the development server running locally but when I set it up on apache2 almost all the functionality works. The parts that break are that whenever I create, update or like a post the page does not load and the apache server shuts down for a while. When I check the apache logs it gives an empty 408 error. I have tried making both the timeouts in the apache config larger and this has not helped. I'm sorry if the answer to this is on here as I couldn't find it despite searching if you know of one please link me. If any extra info is required please ask. Thank you! -
Django: return populated form after login redirect
I have a form for posting comments to a Django website that redirects to the login page if an anonymous user attempts to comment, then directs to the comment form after login. Is there a way to retain what the user filled out and populate the form after the redirect? Code below, thanks. def post(self, request, pk, slug): if request.method == "POST": post = get_object_or_404(Post, pk=pk) form = CommentForm(request.POST) if not request.user.is_authenticated: messages.info(request, f'Please login to post your suggestions, compliments, or insults.') return redirect(reverse('login') + '?next=/' + str(post.pk) + '/' + post.title + '/' +'#comments') if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect('detail', post.pk, post.slug) -
IS THERE AWAY TO DEACTIVATE ACCOUNT ON SIGNUP IN DJANGO REST AUTH AND ALSO NOT SEND EMAIL
I build a django app from and organization and they dont want user accounts to be pre-activated on signup, am using django rest auth and the settings I used previously was sending email now I did modify my settings to ACCOUNT_EMAIL_VERIFICATION = "none" and by default account is active without email being sent, what I need is account email to be unverified can someone come to the rescue please, as at now am causing and exception in sending email by not setting the urls which I know is not the best but at least it is doing it -
How to get data from a form and store it in a variable in django
So here is the form class in views.py: class SearchForm(forms.Form): querry = forms.CharField(label='Search', max_length=10) The form is added to the concerned page as: <form action="/encyclopedia/search.html" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> {{ form }} </form> I've tried to implement the view function in two ways: first:- def search(request): form = SearchForm(request.GET) if form.is_valid(): querry = form.cleaned_data['querry'] else: querry = None return HttpResponse(querry) second:- def search(request): form = SearchForm(request.GET) querry = request.GET.get("querry") return HttpResponse(querry) The given HttpResponse is just to check if i have successfully got the desired data inside variable "querry". In both ways, it simply returns None. I see methods to get data from POST all over the internet. Am i missing something here??? I've tried so many things. Can someone please just write a function they would use to get data from a form using GET method? I will really appreciate it. I have no idea what else to do now.... -
sends tokenizing data from def process to def def bobot django
I want to send tokenizing data from def process to def bobot on django, I'm still a beginner, please help help help def a(request) def b(request) -
Django set last_online middleware not working
I want to log the last time my user has accessed the website and have implemented this middleware. It however does not store the most updated time. middleware.py class LastOnlineMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_request(self, request): if request.user.is_authenticated(): request.user.profile.last_online = timezone.now() request.user.profile.save() models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) last_online = models.DateTimeField(default=timezone.now) -
How do I pass parameters to Django forms?
So let me explain what I'm trying to build first. There is a question provided to each user, and the user answers. It looks like this: class Question(models.Model): question_number = models.IntegerField(primary_key=True) main_question = models.CharField(max_length = 200, blank=False, default="") sub_question = models.CharField(max_length = 100, blank=False, default="") class Answer(models.Model): authuser = models.ForeignKey(User, on_delete=models.CASCADE, null=True) question_number = models.ForeignKey(Question, on_delete=models.CASCADE, null=True) main_answer = models.CharField(max_length = 10000, blank = True, default="") sub_answer = models.CharField(max_length = 10000, blank = True, default="") Apparently, main_answer is the answer that user inputs for main_question and the sub_answer works the same way. Then form is provided is as well, for each question. Like this: class AnswerForm(forms.ModelForm): main_answer = forms.CharField(required=True, widget=forms.Textarea(attrs={'rows' : 3})) sub_answer = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows' : 2})) And finally, this is the view. Pretty standard. (As you can see, I'm using formset) def userAnswer(request, pk): AnswerFormSet = modelformset_factory(Answer, form=AnswerForm, extra=1) formset = AnswerFormSet(queryset=Answer.objects.filter(authuser=request.user.id, question_number=pk)) thisQuestion = Question.objects.get(question_number=pk) if request.method == "POST": formset = AnswerFormSet(request.POST) if formset.is_valid(): instance = formset.save(commit=False) instance[0].authuser = request.user instance[0].question_number = thisQuestion instance[0].save() return redirect('/home') context = { 'thisQuestion':thisQuestion, 'formset':formset } return render(request, 'qanda/userAnswer.html', context) NOW THE THING IS, I want to add label to each input field(main_answer and sub_answer) with respective question(main_question and sub_answer). And … -
When sending a post request using axios in React Native, an error occurs only in Android
I make an api with Django restframe work and try to send a post request using axios in react-native. I am working on a window and if I send a request from postman or the web, it works normally. When sending a post request from my mobile phone or adroid emulator (nox appplayer) Network Error occurs. import axios from "axios"; const callApi = async (method, path, data, jwt) => { const headers = { Authorization: jwt, "Content-Type": "application/json", }; const baseUrl = "http://127.0.0.1:8000/api/v1"; const fullUrl = `${baseUrl}${path}`; if (method === "get" || method === "delete") { return axios[method](fullUrl, { headers }); } else { return axios[method](fullUrl, data, { headers }); } }; export const createAccount = (form) => callApi("post", "/users/", form); error message Network Error - node_modules\axios\lib\core\createError.js:15:17 in createError - node_modules\axios\lib\adapters\xhr.js:88:22 in handleError - node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent - node_modules\react-native\Libraries\Network\XMLHttpRequest.js:600:10 in setReadyState - node_modules\react-native\Libraries\Network\XMLHttpRequest.js:395:6 in __didCompleteResponse - node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 in emit - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0 - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard - node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue * [native code]:null in callFunctionReturnFlushedQueue I don't know how to solve this problem. Please help me. -
ManagementForm data is missing or has been tampered with in django
I am using the following code in my django app which is working fine but i am getting this error when trying to save a form: ['ManagementForm data is missing or has been tampered with'] Views: def employedit(request, pk, id): employ_academic_forms = EmployAcademicUpdateFormSet(queryset=EmployAcademicInfo.objects.filter(employ_id=pk)) if request.method == 'POST': employ_academic_forms = EmployAcademicUpdateFormSet(request.POST) if employ_academic_forms.is_valid(): employ_academic_forms.save() return redirect('employ-list') context = { 'employ_academic_forms':employ_academic_forms, } return render(request, 'admins/employ/edit_employ.html', context) form: EmployAcademicUpdateFormSet = modelformset_factory( EmployAcademicInfo, exclude = ['employ_id'], extra=0, labels = { 'degree': 'Enter Employ Degree', 'last_passing_institution_name': 'Enter Employ Passing Institution', 'last_passing_year': 'Enter Employ Passing Year', }, widgets = { 'degree' : forms.Select(attrs={'class':'form-control form-control-lg', 'placeholder':'Enter degree'}), 'last_passing_institution_name' : forms.TextInput(attrs={'class':'form-control form-control-lg', 'placeholder':'Enter institution name'}), 'last_passing_year' : forms.DateInput(attrs={'class':'form-control form-control-lg', 'type':'date'}), }, ) Html: {% extends 'base/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="card-body"> <div class="card-body"> <div class="form-horizontal"> {{ employAcademicFormSet.management_form }} {% for form in employ_academic_forms %} {% for field in form.visible_fields %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label> <div class="col-md-9">{{ field }}</div> </div> {% endfor %} {% endfor %} </div> </div> </div> <div class="card-footer"> <button class="btn btn-lg btn-primary" type="submit">Submit</button> </div> </form> </div> {% endblock %} Does anyone know … -
Installing pycopg2 gave me an issue
I was able to install other pip libraries instead of pycopg2 when running this command - pip install psycopg2. I am using Azure Linux VM - Ubuntu 18.04 LTS and have setup database configuration in settings.py. Below is an issue: (venv) azureuser@signbank:~/projects/signbank$ pip install psycopg2 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/fd/ae/98cb7a0cbb1d748ee547b058b14604bd0e9bf285a8e0cc5d148f8a8a952e/psycopg2-2.8.6.tar.gz Building wheels for collected packages: psycopg2 Running setup.py bdist_wheel for psycopg2 ... error Complete output from command /home/azureuser/venv/bin/python3 -u -c "import setuptools, tokenize;file='/tmp/pip-build-wzcbc8dl/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(__file __);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d /tmp/tmpnx61owb_pip-wheel- --python-tag cp36: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'bdist_wheel' Failed building wheel for psycopg2 Running setup.py clean for psycopg2 Failed to build psycopg2 Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error Complete output from command /home/azureuser/venv/bin/python3 -u -c "import setuptools, tokenize;file='/tmp/pip-build-wzcbc8dl/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(fi le);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-nrmq1jq2-record/install-record.txt --single-version-externally-managed --co mpile --install-headers /home/azureuser/venv/include/site/python3.6/psycopg2: running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/init.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errors.py … -
i am facing looping problem. my silde is going upto the last slide then it stops.and my previuos key is not working any help will be great
{{product.0.title}} Learn more {% for i in product|slice:"1:" %} {{i.title}} Learn more {% endfor %} {% for i in range %} {% endfor %} <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> -
Is it possible to pass an instance of a class defined in one view to another view in Django
Is it possible to pass an instance of a class defined in one view to another view in Django? I tried using session and am able to pass attributes but not able to pass a method. Ideally, I'd like to pass the class instance to session directly but I get an error saying 'Object is not JSON Serializable' More context, I have 2 views. One renders a page for each user. It also declares a class (MyClass) with a method get_response() that returns a response based on an input text. def display_user(request, pk, slug): obj = MyClass(...) ... request.session['obj_name'] = obj.name request.session['obj_method'] = obj.method(input_text) # <-- how to pass method to session return render(request, 'page.html', context = {...}) I have a view that I can make api calls to get the response from the method of the class defined above. def obj_api(request, pk, slug): obj_name = request.session['obj_name'] # this works if request.method == 'POST': input_data = json.loads(request.body.decode('utf-8')) response = obj.get_response(input_data) # <-- how to get method from session ## response = request.session['obj_method'](input_data) ... return JsonResponse(response_data, status=200) Any help would be appreciated. -
linking button to required html using django python
I am trying to build a web page, where if I am having 2 buttons I can refer to different links linked to them. I have tried multiple to pull info of clicked button of form, javascript,ahref somethings not working right. Currently I am trying this code: for views def indiCountData(request): if request.POST.get('US'): (code inside working) return render(request,'india.html',context) elif request.POST.get('India'): (code inside working) return render(request,'india.html',context) for html <button onClick="myOnClickFn()">US</button> <script> function myOnClickFn(){ document.location.href="us.html"; } </script> <button onClick="mynClickFn()">India</button> <script> function mynClickFn(){ document.location.href="india.html"; } </script> for url if use this path('',views.home,name='home'), path('us.html',views.indiCountData,name=''), path('india.html',views.indiCountData,name=''), The view covi.views.indiCountData didn't return an HttpResponse object. It returned None instead. if use this path('',views.home,name='home'), path('',views.indiCountData,name='us'), path('',views.indiCountData,name='india'), 404 error code Please guide I am confused here your answers are much appreciated. -
How to render pdf file as HTMl pages using pagination Django from django views?
I has a book pdf in my static files.I want to write a view that reads this book.pdf and renders this pdf as html pages using django pagination concept.Is it possible to perform it.please help. -
MultipleObjectsReturned at / get() returned more than one City -- it returned 2
I am new to Python and have inherited the code base from another developer. I am getting a MultipleObjectsReturned at / get() returned more than one City -- it returned 2! error. In the code below, I changed the get to filter and checked that there are no duplicates in the database. context['count_promotions'] = count_promotions = promotions.count() count_cities = 0 count_products = 0 for promotion in promotions: for location in promotion.store.all().values_list('city__name', flat=True).order_by('city__name').distinct('city__name'): count_cities += 1 primary_key = City.objects.filter(name__icontains=location).pk province = Region.objects.filter(city__name__icontains=location) new_text = location.replace(',', '') almost_finished = new_text.replace('&', '') finished = almost_finished.replace(' ', '-') store_locations.append({ 'pk': primary_key, 'city' : finished, 'province' : province.name, }) What else can I check to resolve the issue? Thanks in advance. -
django: How to put date value from database to "input type='date'"?
why is it i cant put value from my database to input type date? even though my query is correct? {% for feedback in feedbacks %} <input name="datef" value="{{feedback.dateSubmitted}}" type="date"> {% endfor %} this is my views.py feedback = obj.objects.all() print(feedback) this is the result for print <QuerySet [<TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords: mystudent>]> my models.py class TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords(models.Model): ..... dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) ..... the result in my webview -
Which is the best way to build an online code editor web application?
I am planning to build a leet code model website for my project. What is the best code editor I can embed into my web application. I am planning to build my application using Django and saw a recommendation that django-ace package can be used to embed Ace- editor into the web application. In that case, how will I able to run the code entered into the code editor? While researching about it , I found some concepts like sandbox , docker. Can someone suggest which is the best way to implement this project as I am new to software development? Thank you. -
register() missing 1 required positional argument: 'auth_user'
from django.shortcuts import render def register(request, auth_user): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] auth_user = auth_user.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name) auth_user.save() print('user created') return redirect('/') else: return render(request,'register.html') -
Exception Value: 'QuerySet' object has no attribute 'password'
I'm getting an error Query set object has no attribute 'password'.Can any one please help me how to compare user entered password with return <QuerySet [<Customer: Customer object (42)>]> query set. Please find the below views.py for login. def login(request): if request.method == 'GET': return render (request, 'login.html') else: email = request.POST.get('email') password = request.POST.get('password') print(email,password) #Now we will try to match user entered email ID and search it in db(here we Can't use pass because it is in ecrypted mode we can see from admin panel # to filter result we can use Customer.objects.filter which will return match in list form but we want a single object so better is to use get # Customer.objects.get(email=email)) #drawback of get is that if result is matched then good else it will give error. login_customer = Customer.objects.filter(email=email) print(login_customer) print('-------') error = None if login_customer: print(email) flag = check_password(password, login_customer.password) #if user email ID is exit then we'll Check his password.:) if flag: return redirect('home') else: print(email, password) error = 'Entered Email ID OR Password is incorrect' return render(request, 'login.html',{'error':error}) customer.py(models): from django.db import models ##Customer Model Creation. # Create your models here. class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = … -
Incomplete Context in Template due to ManyToManyField
I have a beginners question, I am trying to debug and understand the reasons why my context is not showing in the template. I have followed a tutorial to show PDF invoices in the Django Admin but there seems to be something off with my code which I have been battling for a while. I want help to know what could be wrong with my code. So, to summarize the issue I have Project where there are 3 models: Item, OrderItem and Order. The Order has a Many-to-Many relationship with OrderItem and the OrderItem has a Foreign Key with Item. In the template, I am trying to loop between the Order.Items which is items = models.ManyToManyField(OrderItem) but it is not rendering any data. Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only … -
How to send welcome emails when users log in to my website with django?
I want to send emails to my users when they log in for the first time with Python Django. How can I do that? -
Django CSRF cookie not being set inside iframe
Short story, I need my Django site to be used by a bunch third party sites. I was able to get the site to display inside iframes by using django-csp. But whenever I need any user to use a form, the main problem being the login, I get a CSRF verification error that's caused because the csrftoken cookie is not being created when the page is loaded inside an iframe. Also, I suspect any AJAX request made by the site will also fail as they required CSRF validations. I have already tried the following settings: CSRF_TRUSTED_ORIGINS = ['mydomain.com', 'examplethirdparty.com'] CSRF_COOKIE_SAMESITE = None CSRF_COOKIE_SECURE = True It still doesn't work, I have read the Django documentation regarding CSRF and I found nothing else about this matter. I know I can disable CSRF protection but that's not an option for me. I'd greatly appreciate any suggestions to solve this. -
How can I validate data to be posted on a table with reference to the same table?
While creating donation I want to check whether the data with same donor_id exists or not. If data don't exists then create donation else if there is data then get the latest donated date and validate whether the latest donated is greater then 3 months or not (if latest donated date exceeds three month then create donation else display message with donation cannot be made.) Code of models.py from django.db import models GENDER_CHOICES = ( ('M', 'MALE'), ('F', 'FEMALE'), ('O', 'Others'), ) BLOOD_GROUP_CHOICES = ( ('A+', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), ('O-', 'O-'), ('AB+', 'AB+'), ('AB-', 'AB-'), ) class Donor(models.Model): first_name = models.CharField(max_length=20) middle_name = models.CharField(max_length=20, blank=True) last_name = models.CharField(max_length=20) blood_group = models.CharField(choices=BLOOD_GROUP_CHOICES, max_length=3, null=True) gender = models.CharField(choices=GENDER_CHOICES, max_length=1) email = models.EmailField(blank=True) mobile_number = models.CharField(max_length=15) telephone_number = models.CharField(blank=True, max_length=15) date_of_birth = models.DateField() def __str__(self): return self.first_name + ' ' + self.last_name class Donation(models.Model): donor = models.ForeignKey(Donor, related_name='donor_name', on_delete=models.CASCADE) date_of_donation = models.DateField() donation_address = models.CharField(max_length=200) def __str__(self): return self.donor.first_name code of views.py from django.shortcuts import render, redirect from .forms import DonorForm, DonationForm from .models import Donor, Donation from datetime import datetime def donorPage(request): donors = Donor.objects.all() context = {'donor': donors} return render(request, 'donor/donor_page.html', context) def createDonor(request): form … -
How can i use middleware decorator for class-based view in djabgo?
How can i use middleware decorator for classbased view? class APIViewMixin(): apiMiddleware = decorator_from_middleware(APISecretMiddleware) @apiMiddleware def dispatch(*args, **kwargs): return super().dispatch(*args, **kwargs) class ThemesView(APIViewMixin, View): def get(self, request, id= None, *args, **kwargs): if (id!= None): serializer = vocabulary.customserializers.ThemesSerialiser(showWords=True); return HttpResponse(serializer.serialize([vocabulary.models.Theme.objects.get(pk= id)]), content_type='application/json') else: serializers = vocabulary.customserializers.ThemesSerialiser(showWords=False); return HttpResponse(serializers.serialize(vocabulary.models.Theme.objects.all()), content_type='application/json',) this doesnt work