Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Djagno REST field lookup "range" does not return a range, but rather single value results
I am trying to return a range of objects containing date attributes. Using the field lookup range, it only returns objects with the start range. For example: If start of the range is equal to 2021-05-19 and end of the range is equal to 2021-05-21, only objects with the date 2021-05-19 are being returned. urls.py urlpatterns = [ ... path('weekly/<str:activity_date>/', views.ActivityDateList.as_view(), name='weekly_dates'), ... ] views.py from django.shortcuts import render from rest_framework import generics from .serializers import ActivityListSerializer from .models import Activity from keeper import serializers ... class WeeklyActivityView(generics.ListAPIView): serializer_class = ActivityListSerializer def get_queryset(self): end_of_week = "2021-05-21" # Temporary test date activity_date = self.kwargs['activity_date'] return render(Activity.objects.filter(activity_date__range=(activity_date, end_of_week))) models.py class Activity(models.Model): activity_name = models.CharField(max_length=200, blank=False) activity_duration = models.CharField(max_length=300, blank=False) activity_date = models.DateField(auto_now=False, blank=False) def __str__(self): return f"Activity: {self.activity_name} Started at: {self.activity_start} Activity Duration: {self.activity_duration}" serializers.py from rest_framework import serializers from .models import Activity from rest_framework.reverse import reverse class ActivityListSerializer(serializers.ModelSerializer): absolute_url = serializers.SerializerMethodField() class Meta: model = Activity fields = [ 'activity_name', 'activity_duration', 'activity_date', 'absolute_url' ] def get_absolute_url(self, obj): return reverse('activities_detail', args=(obj.pk,)) Only single dates are being returned: Objects with other dates exist: How can I return objects with date attributes within the range specified? -
DJANGO RANGE IN LIST
I have 1 problem is filter in a list of range. Does django have any method for filter in range of a list? For example: I have a list list_a = [(100,200), (300,400)] i tried Models.objects.filter(field_wanna_search__range__in=list_a) but it not work Can anybody help me on this! -
How to set value for time input in HTML? (I am using Django)
Inside a form, I want to input time. For this I am using the HTML input type="time" . I tried to set a value, but it does not appear Time value just appears empty <input type="time" name="due_time" id="id_due_time" class="form-control form-control-lg" value="{{ todo.due_time }}"> This is how I tried to get it done. When the time default value did not appear, I tried formatting it like this- <input type="time" name="due_time" id="id_due_time" class="form-control form-control-lg" value="{{ todo.due_time|time:'h i A' }}"> But it still doesn't work... I'm a newbie, and I'm not familiar with Javascript, so I would appreciate it if the answers were kept simple. Thank You -
Django sphinx docs made by cookicutter folder confusion
I'm a bit confused by the folder structure the sphinx makes for its documentation when starting a fresh new Django project with cookiecutter. I have my project set up in docker, as per instructions, everything is serving fine and I have the following folder structure for the documentation. When I run the command make html in the docs container (or by using the docker-compose local.yml file) I get the following structure. A new folder "html" is created and it's containing everything from the surrounding folders. Is this correct? Am I understanding the process correctly? For me, it looks like some bad settings for some source folder somewhere. I'm an experienced python dev, familiar with Docker as well, but I'm pretty new to Django and sphinx. Can somebody please guide me to the right path, possibly share their Django sphinx docs workflow? Thank you very much. -
foreignkey( settings.AUTH_USER_MODEL) should set its value to the current user automatically butI got this field is required?
Error when I send POST a request with {'title': 'bla bla'} I got this error { "created_by": [ "This field is required." ] } But when I send POST a request with {'title': 'bla bla','created_by':1} it work fine. MY Code #models.py from safedelete.models import SafeDeleteModel, NO_DELETE class MyModel(SafeDeleteModel): title = models.CharField(max_length=30) date_created = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #views.py class MySer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' class MyView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = MyModel.objects.all() serializer_class = MySer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) goals automatically add the currently authenticated user. I tried replace (SafeDeleteModel) with (models.Model)` set a defualt value created_by = models.ForeignKey( settings.AUTH_USER_MODEL,defualt=settings.AUTH_USER_MODEL on_delete=models.CASCADE) but nothing worked -
how to use try accept in a better way while making an object of model class to get data?
looking for help to handle the exception in a better way, I am new to python and django so if any one can suggest me that what can i write in place of pass, as i dont have any code to write there can i return Response(status=status.HTTP_200_OK) where pass is written or is there any thing which is better than this ? if(computedsignature==signature): try: order=Orders.objects.get(id=id) except (Payments.DoesNotExist): pass payment_collection_webhook_url=order.payment_collection_webhook_url application_id = order.applications try: application = Applications.objects.get(id=application_id) except (Applications.DoesNotExist): pass if(transaction_status=='SUCCESS'): try: payment= Payments.objects.get(orders=order,direction=direction) except (Payments.DoesNotExist): payment.save() -
How can i make a field editable in django admin when another boolean field is true or false?
here are my codes. i have viewed a couple of website and all am getting is just making the field readonly. -
Is there a way to check if some value is IN request.session.name?
Can anybody clarify, please? I got a Cart object in request.session I want to check if request.session.cart CONTAINS item.id as a key from template {% if game.id in request.session.cart %} I know that game.id is FOR SURE in that cart object, but template doesn't react on that. I HAVE a context processor added -
django cassandra get Unable to connect to any servers docker
I use windows 10. get this error when building cassandra.cluster.NoHostAvailable: ('Unable to connect to any servers', {'127.0.0.1:9042': ConnectionRefusedError(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")}) Dockerfile FROM python:3.8.5 ENV PYTHONUNBUFFERED=1 ENV CASS_HOST=cassandra ENV CASSANDRA_HOST=cassandra RUN apt-get -y update RUN apt-get -y upgrade RUN apt-get -y install wait-for-it RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ EXPOSE 8080 docker-compose.yml version: '2' services: cassandra: hostname: cassandra image: cassandra:latest ports: - "9042:9042" - "9160:9160" networks: - cassandra web: build: . command: /bin/bash -c "cd api_messages && wait-for-it cassandra:9042 -- python manage.py sync_cassandra && python manage.py runserver 0.0.0.0:8080" volumes: - .:/code ports: - "8000:8080" depends_on: - cassandra networks: - cassandra environment: - PYTHONUNBUFFERED=1 - PYTHONDONTWRITEBYTECODE=1 - CASSANDRA_HOST=cassandra - CASS_HOST=cassandra networks: cassandra: -
Django browser upload failed
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: dbik: image: postgres volumes: - ./data/dbik:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres ports: - 5432:5432 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - dbik links: - dbik $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Please below the logs after I ran docker-compose build docker-compose up Attaching to djangoblast_dbik_1, djangoblast_db_1, djangoblast_web_1 dbik_1 | db_1 | dbik_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization dbik_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | dbik_1 | 2021-05-19 10:45:54.221 UTC [1] LOG: starting PostgreSQL … -
Django: To check if old password emtered by the user is valid or not
I am able to check the new_password1 and new_password2, but i am unable to check whether the old password entered by the user is right or not. As it is not giving me the validationerror on old password on the django template. Please suggest me the condition that can be used on forms.py This is forms.py class ChangePasswordForm(forms.Form): old_password = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) new_password1 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) new_password2 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) def set_user(self, user): self.user = user def clean(self): old_password = self.cleaned_data.get('old_password') valpwd = self.cleaned_data.get('new_password1') valrpwd = self.cleaned_data.get('new_password2') if not old_password: raise forms.ValidationError({ 'old_password':"You must enter your old password."}) elif valpwd != valrpwd: raise forms.ValidationError({ 'new_password1': 'Password Not Matched'}) return self.cleaned_data This is views.py class PasswordsChangeView(FormView): template_name = 'dashboard/password/password_change.html' form_class = ChangePasswordForm success_url = reverse_lazy('dashboard:admin_login') def get_form(self): form = super().get_form() form.set_user(self.request.user) return form This is change_password.html <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <h6>Old Password</h6>{{form.old_password}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <span style="color:red">{{ form.old_password.errors }}</span> <div class="input-group mb-3"> <h6>New Password</h6> {{form.new_password1}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="input-group mb-3"> <h6>Re-Type Password</h6> {{form.new_password2}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> … -
POST request to upload file
I want to upload a file to my django application. views.py @api_view(['POST']) def upload_to_evm(request): if request.method == 'POST' and request.FILES['file']: file = request.FILES['file'] filename = FileSystemStorage().save('abcd', file) return JsonResponse({'Status': 'Successful'}) urls.py urlpatterns = [ path('api/evm_process/', views.upload_to_evm) ] Currently, I am sending my request with Binary File option and with header Content-Type: multipart/form-data and it gives MultiValueDictKeyError error which means my request.FILES is empty and I cannot understand why. My question are: What is the correct way to make a POST request with all the headers and query_params for the same ? Do I need a parser (FileUploadParser, MultiPartParser or FormParser) to upload, save or process the uploaded file ? Python version: 3.6.9 Django version: 3.2.3 -
Set default values of year and month using django-yearmonth-widget
How to set default value using django-yearmonth-widget for year as current year and month as month_name-1 Forms class FileUploadForm(forms.ModelForm): file = forms.FileField(required=True,widget=forms.ClearableFileInput(attrs={'multiple':True}), label='Select Files') file_remote = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple':True}), required=False) class Meta(): model = FileUpload fields= ('file_upload_datetime','file','file_remote') widgets = { 'file_upload_datetime': DjangoYearMonthWidget(), 'file_remote':forms.HiddenInput() } Models class FileUpload(models.Model): file = models.FileField(upload_to='files') file_remote = models.FileField(upload_to=RetailFormsConfig.remote_folder, storage=upload_storage, blank=True) file_upload_datetime = models.DateField() -
How to post data to custom user model using abstract user?
I'm pretty confused in this I've created a form for accepting the user model data. Even i customised the user model data to Abstract user. models.py class User(AbstractUser): user_role=models.IntegerField(default=0) views.py from django.contrib.auth.models import User def register(request): if request.method == 'POST': post.first_name=request.POST.get('first_name') post.last_name=request.POST.get('last_name') post.email=request.POST.get('email') post.username=request.POST.get('user') post.password=make_password(request.POST.get('password')) post.user_role=1 post.save() while posting, no data is passed ,it's totally null and when tried print(post.user_role) it says user has no attribute user_role any help will be appreciated. -
django.db.utils.OperationalError: no such table: store_product
When I run makemigrations error is occurred. Here is models.py def unique_order_id(): not_unique = True while not_unique: uo_id = random.randint(1000000000, 9999999999) if not Order.objects.filter(order_id=uo_id): not_unique = False return uo_id class Product(models.Model): #product code, name, category, unit price, current stock product_code = models.IntegerField(unique=True) name = models.CharField(max_length=100) category = models.CharField(max_length=100) unit_price = models.FloatField() current_stock = models.IntegerField() def __str__(self): return self.name class Order(models.Model): order_id = models.IntegerField(unique=True, default=unique_order_id) customer_name = models.CharField(max_length=100) phone = models.CharField(max_length=14) email = models.EmailField() qr_code = models.ImageField(upload_to='qr_codes', blank=True) def __str__(self): return self.customer_name #override ths save method for creating qrcode based on fields on this model. def save(self, *args, **kwargs): qr_info = "Invoice No : "+ str(self.order_id)+" Name : "+self.customer_name +" Phone : "+str(self.phone)+ " Email : "+ self.email qrcode_img = qrcode.make(qr_info) #canvas = Image.new('RGB', (290, 290), 'white') canvas = Image.new('RGB', (qrcode_img.pixel_size, qrcode_img.pixel_size), 'white') canvas.paste(qrcode_img) fname = f'qr_code-{self.customer_name}.png' buffer = BytesIO() canvas.save(buffer,'PNG') self.qr_code.save(fname, File(buffer), save=False) canvas.close() super().save(*args, **kwargs) class OrderItem(models.Model): qty = models.IntegerField(default=0) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) #this will return total price of product(unit_price*quntity) @property def get_total(self): total = self.product.unit_price * self.qty return total This is forms.py codes class ItemSelectForm(forms.Form): p_name = forms.ChoiceField(label='Select Product',choices=list ((obj.product_code,obj.name) for obj in Product.objects.all())) qty = forms.IntegerField() #function for checking product … -
Django: 'utf-8' codec can't decode byte 0xe9 in position 10298: invalid continuation byte while performing python manage.py loaddata operation
Good day, I am transferring db from vscode django project to heroku postgres db. when I do python manage.py loaddata products.json I get the error: thank you -
TypeError: 'NoneType' object is not subscriptable in Django?
@property def geolocation(self): """ This function will fetch lat and lng value from location_data JSON filed and return combined value in form of string( pattern="lat,lng"). """ location = "" if self.location_data: lat = self.location_data["geometry"]["location"]["lat"] lng = self.location_data["geometry"]["location"]["lng"] location = location + str(lat) + "," + str(lng) return location when this function is called it return Type error. This function is @property of model and location data JSONFIELD of model and where I stored lat and lng value and it can be null. But when i fetch empty location data it show error? I am confused why Iif I already handled else? -
django sendgrid get error when sending email
I set up sendgrid as following and it works perfectly when I use send_mail to send a test message EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 EMAIL_USE_TLS = True Howerver when I implement it with an activation code in views.py for registration as bellow: def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() #completed sign up username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) # Create data in profile table for user current_user = request.user data=UserProfile() data.user_id=current_user.id data.image="images/users/user.png" data.save() current_site = get_current_site(request) subject = 'Please Activate Your Account' # load a template like get_template() # and calls its render() method immediately. message = render_to_string('user/activation_request.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), # method will generate a hash value with user related data 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('activation_sent') # messages.success(request, 'Your account has been created!') # return HttpResponseRedirect('/') else: messages.warning(request,form.errors) return HttpResponseRedirect('/register') form = SignUpForm() #category = Category.objects.all() context = { 'form': form, } return render(request, 'user/register.html', context) It throws out this error: SMTPDataError at /register (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error … -
Django Admin connection to Firebase
I don't know how to connect the Django Administration page to Firebase. For example, I can't set data entered in a field of a model in my Firebase Database. I know how to do it with the other pages I created but with admin page I can't get a way to do so. And I don't know how to deal with admin page like the other pages so that I can customize it or add functions to it. -
Django Form Validation: It is not showing me django error message in template
Here I want to show validationerror on template but it is not returning the error before i even type the password. I want to check the newpassword entered by the user and match the re-entered password, but it's not showing me the error message though it isnot accepting the form if the password arenot matched. This is my views.py class PasswordsChangeView(FormView): template_name = 'dashboard/password/password_change.html' form_class = ChangePasswordForm success_url = reverse_lazy('dashboard:admin_login') def get_form(self): form = super().get_form() form.set_user(self.request.user) return form This is forms class ChangePasswordForm(forms.Form): old_password = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) new_password1 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) new_password2 = forms.CharField( widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'})) def set_user(self, user): self.user = user def clean(self): cleaned_data = super().clean() old_password = self.cleaned_data.get('old_password') valpwd = self.cleaned_data.get('new_password1') valrpwd = self.cleaned_data.get('new_password2') if valpwd != valrpwd: raise forms.ValidationError({ 'new_password1':'Password Not Matched'}) return self.cleaned_data This is template <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <h6>Old Password</h6>{{form.old_password}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="input-group mb-3"> <h6>New Password</h6> {{form.new_password1}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="input-group mb-3"> <h6>Re-Type Password</h6> {{form.new_password2}} <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> <span class='form-error'> {{form.errors.new_password1}}</span> </div> {% comment %} {{ … -
Pip install mysqlclient this command shows error while iam trying to connect django with existing wamp MySQL. Is there any other way to do it?
the prblem that I have is given below -
What is this url path mean?
Hello I am new to Django, I saw a line path('dashboard/(?P<user>.*)/$'), . I didn't understand this. I want to learn this part. But I don't know how to search on google and youtube about this. -
Get the last 2rd item in HTML
I have used Django to develop a webapp In the admin model, I want to choose the last 2rd one in the list(models) How could I slice in the below? <div v-for="(c,j) in models" :key="c.name" class="quick-wrap"> <a href="javascript:;" @click="openTab(c,(j+1)+'')"> <span class="icon" :class="c.icon"></span> <span class="card-name" v-text="c.name"></span> </a> </div> -
Most effective way of updating an m2m field in django?
I have looked at the documentation on how to update an m2m relation, but I got confused with the backend working of .set as it says that .set([]) clears all the previous relationships and then adds new ones for many to many relations, since bulk keyword argument does not exist. NOTE-> I want to update the list of objects in my model. link to django docs -> https://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.set -
browser time out using domain name but not on local server
I require help in setting up the browser (Chrome) time-out session. For example:- 1 am generating a report in real-time when I am generating it on the local server (127.0.0.1). it is working without any issue and no time-out issue. But when I am trying that the same using domain name from a local PC and if it is taking more than 120 Sec to generate because of more data say 1000000 records in the report the page is getting expired or timeout. How to fix this issue? The development platform is Python, Django & PostgreSQL.