Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django NOT NULL constraint failed on migration
I've recently encountered the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: new__blog_law.definitions Here is the code in the migrations: https://pastebin.com/hkzeNsgD Here is the models code: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from ckeditor.fields import RichTextField from tinymce.models import HTMLField class Law(models.Model): identifier = models.CharField(max_length=15) title = models.CharField(max_length=100) description = models.TextField(max_length=400, null=True) definitions = models.TextField() content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) writer = models.CharField(max_length=100) signed = models.DateField() proposed = models.DateField() author = models.ForeignKey(User, on_delete=models.CASCADE) is_repealed = models.BooleanField() is_amendment = models.BooleanField() law_amended = models.TextField(blank=True) has_amendments = models.BooleanField() amendments = models.TextField(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('law-detail', kwargs={'pk': self.pk}) class AssemblyPerson(models.Model): name = models.CharField(max_length=15) description = models.CharField(max_length=100) committees = models.TextField(max_length=400) content = HTMLField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) party = models.CharField(max_length=100) start_term = models.DateField() end_term = models.DateField() portrait = models.ImageField(default="default.jpg", upload_to="profile_pics") author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('assembly-detail', kwargs={'pk': self.pk}) class ExecutiveOffice(models.Model): name = models.CharField(max_length=15) logo = models.ImageField(default="default.jpg", upload_to="profile_pics") content = HTMLField(blank=True, null=True) documents = models.TextField() organizational_structure = models.ImageField(default="default.jpg", upload_to="profile_pics") director_name = models.CharField(max_length=15) director_desc = models.CharField(max_length=200) director_portrait = models.ImageField(default="default.jpg", upload_to="profile_pics") author = models.ForeignKey(User, on_delete=models.CASCADE) director_start_term = models.DateField() def __str__(self): return self.name What did I do wrong? It … -
Why model formset don't save in django
When i save formset it don't save and it return same page. But i don't find my problem. Please help me for find the problem view: def employedit(request, pk, id): employ_academic_forms = EmployAcademicUpdateFormSet(queryset=employ_academic) if request.method == 'POST': employ_academic_forms = EmployAcademicUpdateFormSet(request.POST, queryset=employ_academic) if employ_academic_forms.is_valid(): user_obj = User.objects.get(id=pk) name = employ_basic_forms.cleaned_data['name'] email = employ_basic_forms.cleaned_data['email'] user_obj.username=email user_obj.first_name=name user_obj.email=email user_obj.save() instances = employ_academic_forms.save(commit=False) print(instances) for instance in instances: instance.employ_id = user_obj instance.save() return redirect('employ-list') context = { 'employ_academic_forms':employ_academic_forms, } return render(request, 'admins/employ/edit_employ.html', context) -
Design a Blog Administration System [closed]
The Blog must allow the user to host articles and allow comments from readersThe Index page of the blog must contain a list of all articles, the dates on which the articles were published and hyperlinks to themEvery article has a dedicated webpage which consists of the title, author, publication date,a comments section and a form for readers to submit commentsReaders must be able to enter comments and view their submitted comments instantlyAll articles must contain a title, an excerpt, author, body and a publication dateAll comments must contain the name of the commenter and the comment textQ2: Create a REST API that fetches all comments, the author of the comments and the article on which the comment is made -
Which Module I use for making a Register api Django REST?
I have to make a Register api through Django REST. and I couldn't find any module for doing this. Can anyone Help me. -
django admin with djongo(MongoDB)
i'm trying to apply these models with django admin but it just work in front-end means models appears in django admin, also forms appears well, but when i try to submit form it gives me this error in terminal packages/djongo/models/fields.py", line 581, in str model_form = self.field.model_form_class(instance=instance, **self.field.model_form_kwargs) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/forms/models.py", line 292, in init object_data = model_to_dict(instance, opts.fields, opts.exclude) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/forms/models.py", line 82, in model_to_dict opts = instance._meta and this error in browser -
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 = …