Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How does UpdateView change value of fields that is excluded in ModelForm?
Here I have a ride-request class, and it has original passenger number and total passenger number. I allow user to change the value of original passenger number with ModelForm, and in UpdateView, I would like make total passenger number equals the original passenger number just received from ModelForm. Like this: ModelForm: class RequestOwnerForm(ModelForm): class Meta: model = OwnerRequest fields = [ 'passenger_num', labels = { 'passenger_num': 'How many passengers do you have?', } and UpdateView: class OwnerRequestEditView(LoginRequiredMixin, generic.UpdateView): model = OwnerRequest template_name = 'ride/request_edit.html' form_class = RequestOwnerForm success_url = reverse_lazy('ride:view_requests') def form_invalid(self, form): print("form is invalid") return HttpResponse("form is invalid.. this is just an HttpResponse object") def form_valid(self, form): pk = self.kwargs.get('pk') request = get_object_or_404(OwnerRequest, pk=pk) if request.status == 'open': request.passenger_num = form.cleaned_data['passenger_num'] passenger_num = form.cleaned_data['passenger_num'] request.total_passenger = passenger_num # I want total_passenger equals to passenger_num request.save() return super().form_valid(form) But the fact is total_passenger does not change. Could someone help me? Thank you! -
How to handle custom forms in django
I need view function also with an example to handle custom form in django give an example for implementing this thing -
Django: get latest database object values after submitted form
I have a form that saves three input-values to a database, 1) number, 2) color, 3) make. After I press "submit" another routine should immediately display those values. Problem is that I cannot get latest values to display but instead, once the values have been initially assigned, they do not update and sticks to the first assigned values. Trying to solve it, posts suggests to update the object, such as Django Get Latest Entry from Database, I created a function which I called upon within view after pressing submit, but without luck. def database(): dbo = Product.objects.latest('id') dbo.refresh_from_db() return dbo I call upon this function in my View .... def get_success_url(self): database() print(Product.objects.latest('id')) # just as a test return reverse('product') I have a simple routine I create a linkage between a database object and variables, such as: number = database().number color = database().color make = database().make Problem is: once 'number', 'color', and 'make' have been assigned a value, they become sticky and does not respond to my object refresh (Product.objects.latest('id')). Question is: How should I do, to always get the latest values once I press submit on my form? -
Django runserver not working from google cloud platform
This question is very similar to (but is not the same because I am running on the google cloud, which I suspect may be cause of the issue): Django runserver does not respond when opened in the browser Django manage.py runserver is not working I am trying to set up an api running on a VM-instance on the google cloud platform. So far I got nginx working (when I go to the ip address it greats me with a welcome message). When I run: python3 manage.py runserver 0.0.0.0:8000 I get the following output: Performing system checks... System check identified no issues (0 silenced). February 06, 2019 - 09:27:13 Django version 2.1.5, using settings 'my_api.settings.development' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Which seems good, but when I go to any of the following pages (all of which I've listed under allowed_hosts): 0.0.0.0:8000 127.0.0.1:8000 < my ip address>:8000 The page won't load. I´ve tried checking which ports are used using netstat And I've killed all programs using this port after which I restarted my program, but to no avail. At this point, I've fixed everything suggested in other posts and I'm out of ideas. What would be the … -
How to performing calculation between two fields in Django models in a many to many relationship
I have two models on a many to many relationships and I am trying to subtract one field on a model from the other field on another model. I am having trouble figuring out how to get that done. I am trying to subtract Leave_current_balance from the LeaveBalance model from Total_working_days on the NewLeave model. class LeaveBalance(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,) Leave_current_balance= models.FloatField(null=True, blank=True, default=None) Year=models.CharField(max_length=100,default='') def __unicode__(self): return self.Year class NewLeave(models.Model): user=models.ForeignKey(User,default='',on_delete=models.CASCADE) leave_balance=models.ManyToManyField(Leave_Balance) Leave_type=models.CharField(max_length=100,blank=False,default='') Total_working_days=models.FloatField(null=True, blank=False) def __unicode__(self): return self.Leave_type -
How to add extra data to a HyperlinkedModelSerializer?
I want to add some extra data to my serializer. In my ajax call I am already sending an additional field "message" (Text from a textarea). This field is not in my model. Bellow is a sample snippet of my code. views.py class BookingRequestViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): serializer_class = BookingRequestSerializer serializers.py class BookingRequestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BookingRequest fields = ( 'last_name', 'email', 'startdate', 'enddate', 'guests', 'building' ) def create(self, validated_data): bookingrequest_obj = super().create(validated_data) #How can I get the message from my rest ajax call? message=validated_data['external_bookingrequst'] BookingRequestMessage( bookingrequest=bookingrequest_obj, message=message, sender=BookingRequestMessage.Mieter ).save() return bookingrequest_obj Any idea how to make it work? -
CORS headers block accessing without domain
I'm trying to make a request to the api on my backend from the frontend. It works when I do it with: http://127.0.0.1:8000/api/ but I don't want to use domain in my front-end, so I'm trying to connect like this: //api/ and this request is blocked by CORS. What should I add to the whitelist? CORS_ORIGIN_WHITELIST = ( 'localhost', '127.0.0.1', 'localhost:8081', 'localhost:8080', '127.0.0.1:8000' ) -
Django Authentication Ldap Full example
I partially understood the Django Ldap Authentication. Can anyone give the full example developing very basic application that uses Django Authentication Ldap . I went through this resource and tried to understand many things but still I am not able to understand that how to use it in implementation. How to create user model that will be used along with LdapBackend class, and how to write many stuff within authenticate() method etc. -
SMTPDataError (553, b'Relaying disallowed as abc@email.com') while using Contact Form and Zoho Mail
Note:- I have checked the question and answer of this post and I have already added default_from_email in my settings as described below. Now, in my contact form I want to receive and email from the users who are trying to contact me. Hi, I have a blog built in Django which uses Zoho mail to send activation and password reset email. To implement the same, I have added the following code in my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.zoho.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '<myadmin emailaddress>' EMAIL_HOST_PASSWORD = '<myadmin password>' DEFAULT_FROM_EMAIL = '<myadmin email address' It works flawlessly and the user signing up is getting the activation email and reset emails. Now, while creating the contact page for my website, I have added a contact form where the user is required to add his name, email and message. The contact form is like this class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea) The view for the same is :- def contact_us(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = f"{sender_name} has sent you a new message:\n\n{form.cleaned_data['message']}" send_mail('New Enquiry', message, sender_email, ['admin@saralgyaan.com']) return HttpResponse('Thanks … -
code working fine, just problem is on successful operation, successful message not working
This code is working Fine Updating User password the only problem am facing that on successful operation. Success msg is not printing on page views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('change_password') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/change_password.html', { 'form': form }) change_password.html {% extends 'accounts/base.html' %} {% block content %} <!-- {{messages}} --> {{ pwd_updated }} <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Save changes</button> </form> {% endblock %} i tried this but this is also not working: print(messages.success(request, 'Your password was successfully updated!')) -
signals fire up at every user login instead of post_save
I have a small signal connected to post_save of the user model. I want it to only send an email on user creation and not on login as it does in this form. I've tried with if created: but still sends email on login. from django.db.models.signals import post_save def save_profile(sender, instance, created, **kwargs): print("Signal patched") subject = 'New Order Created %s'%instance message = 'Order %s created at %s . Please check if needs further settings!'%(instance, datetime.now()) emailFrom = 'test@test.com' emailTo = [settings.EMAIL_HOST_USER] send_mail(subject, message, emailFrom, emailTo, fail_silently=True) post_save.connect(save_profile, sender=Order) -
Django models compare field to field
Let's say we have model class MyModel(models.Model): int_field_one = models.IntegerField(default=0) int_field_two = models.IntegerField(default=0) The question is: Does Django models supports filter one field by another field? In other words i want to exectute following query SELECT * FROM MyModel WHERE int_field_one > int_field_two with filter syntax MyModel.objects.filter(int_field_one=int_field_two) -
sequential numbering of IntegerField in Django models
I have a model that looks more or less like that: class MyModel(models.Model): period = models.IntegerField(unique=True) beta = models.IntegerField() gamma = models.FloatField() And I need period to be a number from 1 to N where N is number of records in this model. So if there are 5 records there it would be a set of integers [1, 2, 3, 4, 5], but if someone deletes number 4, it should be updated in such a way that number 5 becomes 4, so they would be consecutive again. What is the right way to do it? -
in html page i am using {{form.fieldname}} to fetch check box in model how to i disable input fields on check box checked
I have a checkbox field in model.py cr=models.BooleanField(default=False) and in html page i have {{form.cr}} Continuous Rx how will i disable text field on checkbox check -
Django login not working after extending User class
I have the following files in my Django project. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_designer = models.BooleanField(default=False) is_client = models.BooleanField(default=False) class Skill(models.Model): skill = models.CharField(max_length=50) def __str__(self): return self.skill class Designer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) description = models.TextField(max_length=500, blank=True) date_created = models.DateField(auto_now_add=True) profile_img = models.ImageField(upload_to="gallery",null=True, blank=True) skills = models.ManyToManyField(Skill, related_name='skills') experience = models.IntegerField(blank=True, null=True) def __str__(self): return self.user.username class Project(models.Model): designer = models.ForeignKey(Designer, on_delete=models.CASCADE, related_name='projects') name = models.CharField(max_length=100) description = models.TextField(max_length=500, blank=True) image_file_path = models.ImageField(upload_to="gallery") date_created = models.DateField(auto_now_add=True) def __str__(self): return self.name forms.py from django import forms from .models import Project, Designer, Skill, User from django.contrib.auth.forms import UserCreationForm from django.db import transaction class DesignerSignUpForm(UserCreationForm): skills = forms.ModelMultipleChoiceField( queryset=Skill.objects.all(), widget=forms.CheckboxSelectMultiple, required=True ) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_designer = True user.save() designer = Designer.objects.create(user=user) designer.skills.add(*self.cleaned_data.get('skills')) return user class ClientSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User def save(self, commit=True): user = super().save(commit=False) user.is_client = True if commit: user.save() return user class DesignerSkillsForm(forms.ModelForm): class Meta: model = Designer fields = ('skills', ) widgets = { 'skills': forms.CheckboxSelectMultiple } views.py class SignUpView(TemplateView): template_name = 'user_profile/register.html' def home(request): projects = Project.objects.all() skills = Skill.objects.all() context = { 'projects':projects, 'skills':skills, } return render(request, "user_profile/home.html", … -
What Query Sets can help me produce results dependent on two Choice Fields?
My project has many physics questions stored in its database where each of these questions belongs to a Physics' topic and a Question type. I have two ChoiceField: * One for topics and includes 16 topics. * One for question type and includes two question types. I have a submit button that is supposed to show me the results of my filtering, however, I don't know how to write the Query Sets in the views.py although I have read the Documentation but still don't know how to make one query or more to get my results. This is the models.py from django.db import models from home.choices import * # Create your models here. class Topic(models.Model): topic_name = models.IntegerField( choices = question_topic_name_choices, default = 1) def __str__(self): return '%s' % self.topic_name class Image (models.Model): image_file = models.ImageField() def __str__(self): return '%s' % self.image_file class Question(models.Model): question_type = models. IntegerField( choices = questions_type_choices, default = 1) question_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) question_description = models.TextField() question_answer = models.ForeignKey( 'Answer', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.question_type class Answer(models.Model): answer_description = models.TextField() answer_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' … -
is it possible write watchtower logs in single file in aws
I have developed one small application. For logs , i'm using watchtower in aws. logs are working fine.Logs are inserted in cloudwatch by file wise logs in aws but i wants all logs to be registered in a single file only (for example api.views ) .is this possible? if yes, how? -
fields.E300: Field defines a relation with model, which is either not installed, or is abstract
Yes, I know this is repeated and I have gone through other questions but nothing works for me. I have just started learning Django and I am getting this error while migrating two models with circular import. I have no idea what i can do to solve this as I have tried most of possible solutions I have found. I guess maybe I am doing something wrong which raises this error. Please, guide me if that is the case. User Model class UserCustom(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(unique=True) password = models.TextField() last_list = models.ForeignKey(TaskList, on_delete=models.CASCADE) class Meta: app_label = 'UserCustom' def __str__(self): return self.first_name TaskList Model class TaskList(models.Model): title = models.CharField(max_length=100) description = models.TextField() created_date = models.DateField(default=timezone.now) author = models.ForeignKey('user.UserCustom', on_delete=models.CASCADE) settings.py INSTALLED_APPS = [ 'users.apps.UsersConfig', 'listtask.apps.ListTaskConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Note: I do not want to use default user table of Django admin. -
How to fix the labels positioned wrong in my default Django form?
I created a signup page and a login page. For this, I used django's default authentication features and forms. To modify a bit I used crispy forms but my labels are positioned wrong on my screen. I have attached an image of my signup page where you can see the labels username, password, password again are positioned wrong. Signup page here's my signup.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <body> <div class="container"> <div class="col-md-6 mx-auto text-center"> <img src="{% static 'pd/images/logo.png' %}" style="width:300px;"> <h2>Welcome to Panasonic Energy</h2> </div> <div class="row"> <div class="col-md-4 mx-auto"> <div class="myform form "> <form method="post"> {% csrf_token %} {{ form|crispy }} <div class="text-center "> <button type="submit" class=" btn btn-block send-button tx-tfm">Create Your Free Account</button> </div> {% if form.errors %} <p class=" label label-danger"> Please try again. </p> {% endif %} </form> </div> </div> </div> </div> </body> {% endblock %} and this is my signup.css. I thought the problem wass in my css as the label effecting styles may be overriding django's default styles so i commented them out but still the problem remains. .send-button { background: #54C7C3; width: 100%; font-weight: 600; color: #fff; padding: 8px 25px; } … -
How to get only page data set in bootstrap-table pagination in django?
I have created django project and applied bootstrap-table with pagination. Everything is working fine and great. But my problem is when i load the page, bootstrap-table prefect all the data and brings in UI. So if i have 100 entries it fetch all 100. Is there any easy/good/possible way to get only required set of records as per page request? For example: Pagination is of 10 records per page. Suppose I hit page 3, it should call for 30-40 records and render only those. -
Http Post from AngularJS is reading empty, am I doing something wrong?
So I have been going at this for hours. Usually this works out for me so I decided to ask for some help. My Http Post from AngularJS: $scope.receipt_pay_update = function(){ response = confirm("Do you want to continue with the changes?") if(!response){ return; } var data = { 'items': "ABC", } console.log($scope.current_farmer) $http.post('/foodhub/dashboard/receipt_pay_modal_update',data, {data: JSON} )} Here is my views.py for the request: def receipt_pay_modal_update(request): import sys reload(sys) sys.setdefaultencoding('utf8') print "#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$" print request print "#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$" print request.GET I am trying to get that "ABC" but it keeps showing empty. Here is my logs: #$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$ <WSGIRequest: GET '/foodhub/dashboard/receipt_pay_modal_update/'> #$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$#$$$$##$$$ <QueryDict: {}> This usually works for me so I have no idea what is happening. -
How to use Django Password validation in my existing views?
I have an existing django views.py where I have some password, username, and email validation logic applied. However, going forward I need to apply more advanced password validation. for e.g. password length limitation, uppercase sesitivity etc. I have a code written for advanced validation, but I am not able to apply them on my existing views.py. Below is the code from views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import messages from . import validator def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] username = request.POST['username'] password = request.POST['password', validator.MinimumLengthValidator] password2 = request.POST['password2'] # check if the password match if password == password2: if User.objects.filter(username=username).exists(): messages.error(request, 'username already exist') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request, 'Registration Failed - Try different email address') return redirect('register') else: user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) user.save() messages.success(request, 'Registration complete, please proceed to login') return redirect('register') else: messages.error(request, 'password dose not match') return redirect('register') else: return render(request, 'ACCOUNTS/register.html') Below is the code for advanced password validation from validate.py import re from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ class MinimumLengthValidator: def __init__(self, min_length=8): self.min_length = min_length def validate(self, password, user=None): if … -
How to point a form action to a function in django
I have a function called search in views.py which I use to process search parameters and display results on a different page. My search form is on the home page template so that I can search from there and be redirected to the page specified by my search function. Currently my views.py looks like this: from django.shortcuts import render from django.views.generic import ListView from django.core.paginator import Paginator from core.models import Movie from core.documents import MovieDocument class MovieList(ListView): model = Movie template_name='movie_list.html' paginate_by = 10 queryset = Movie.objects.all() def search(request): q = request.GET.get('q') if q: movies = MovieDocument.search().query("match", title=q) else: movies = '' return render(request, 'search.html', {'movies': movies}) The home page is being served by the MovieList class and I have the following html snippet for the search field in the home page movie_list.html: <form method="get" action="{{ views.search}}"> <input id="q" name="q" type="text" placeholder="Search..."> </form> The url path for MovieList looks like this: path('movies',views.MovieList.as_view(),name='MovieList') When,for example I type 'terminator' in the search box, the url in the browser changes to http://127.0.0.1:8000/movies?q=terminator but the search function is not called and nothing happens. How can I get this working properly, preferably without having to define a new url to capture the search query string … -
query api response for content
I have a create method in my ModelViewSet and after validating and cleaning the serializer I'm making a post request using requests library. def create(self, request): serializer = MySerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() # post to remote server response = requests.post( url='{}/server'.format(settings.URL), json=do_some_cleaning(serializer.data) ) logger.debug('response from server >>>>=%s', response.json) return Response({'response': response}, status=response.status_code, data=response.json) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I need to check my response get the id and store it in the object, or if it's not there need to query it and check do i have it, I need this id so I can work on the PUT method. Can someone please explain me how can I achieve this. -
How to prevent django settings variable change?
I have some settings variable in my settings.py like this: USER_INITIAL_PREFERENCE_DATA = { 'SOME KEY': { 'SOME KEY': SOME DATA }, } I load this data in the session by using request.session['USER_INITIAL_PREFERENCE_DATA'] = settings.USER_INITIAL_PREFERENCE_DATA The problem is, my settings variables get changed in runtime somehow. How can I make the settings variable immutable in runtime?