Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Подскажите, как вывести данные на страницу?
Пишу погодное приложение и вроде все работало, а потом перестало выводить в самом приложении . В базу данных все добавляет, но выводит только сломанный шаблон. В чем дело? vievs: ''' import requests from django.shortcuts import render from .models import City from .forms import CityForm def index(request): appid='8daaf5ff8c413765ce21a9610fad80cf' #https://home.openweathermap.org/api_keys url ='http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=' + appid if(request.method == 'POST'): form = CityForm(request.POST) form.save() form = CityForm() cities = City.objects.all() all_cities =[] for city in cities: city_info = { 'city': city.name, 'temp': res['main']['temp'], 'icon': res['weather'][0]['icon'], } print(city_info) if res.get('main'): city_info = { 'city': city.name, 'temp': res['main']['temp'], 'icon': res['weather'][0]['icon'], 'error': False, } else: city_info= { 'city': city.name, 'error': True } all_cities.append(city_info) context = {'all_info': city_info, 'form': form} return render(request, 'weather/weather.html', context) ''' templates ''' Information {% for info in all_info %} <div class="alert alert-info"> <div class="row"> <div class="col-9"> <b>City:</b> {{ info.city }} <br> <b>Temperature:</b> {{ info.temp }}<sup>o</sup> <br> </div> <div class="col-2 offset-1"> <img src="http://openweathermap.org/img/w/{{ info.icon }}.png" alt="photo weather"> </div> </div> </div> {% endfor %} </div> ''' enter image description here -
Need help in returning the Date field in Django models
models.py class Add_Timelog(models.Model): project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project') project=models.ManyToManyField(Project) client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client') client=models.ManyToManyField(Client) Job=models.ForeignKey(Add_Job,on_delete=CASCADE,related_name='Job') Job=models.ManyToManyField(Add_Job) Date = models.DateTimeField(max_length=10) Hours=models.TimeField(null=True) def __str__(self): return self.Date TypeError at /api/Add_Timelog/ str returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/api/Add_Timelog/ Django Version: 2.2.12 Exception Type: TypeError Exception Value: str returned non-string (type int) This is the error I received. The solution what I was expecting is to receive the date inputted by me in the database and receive the value as date (integer) not a string -
Does property decorator method run whenever an object is accessed?
Suppose this is a class: class A(models.Model): user_id = models.UUIDField() date = models.DateField() def __str__(self): return f"({self.pk})-({self.user_id})-{self.date}" @property def related_day(self): return RelatedDay.objects.filter(user_id=self.user_id, date=self.date).first() My question is, if I access an object of class A, will the related_day() method be called everytime? Or it will be called only when I access A.related_day? I don't want to take any performance hit for using property decorator when I don't need related day. I've read these answers but I'm not sure yet about this. -
why do i get this error creating superuser django?
I'm currently using django 4 and python 3.10 tryig to create a superuser bur i get this error Traceback (most recent call last): File "C:\Users\sebas\Desktop\django2\myvenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 159, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "C:\Users\sebas\Desktop\django2\myvenv\lib\site-packages\django\contrib\auth\password_validation.py", line 44, in validate_password password_validators = get_default_password_validators() File "C:\Users\sebas\Desktop\django2\myvenv\lib\site-packages\django\contrib\auth\password_validation.py", line 19, in get_default_password_val idators return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "C:\Users\sebas\Desktop\django2\myvenv\lib\site-packages\django\contrib\auth\password_validation.py", line 30, in get_password_validators validators.append(klass(**validator.get('OPTIONS', {}))) TypeError: MinimumLengthValidator.init() got an unexpected keyword argument 'min_lenght' -
User object name customization in django
#model.py class Users(models.Model): JOINING_ROLES_CHOICES= ( ('sde-intern','SDE Intern'), ('sde-trainee','SDE Trainee'), ('sde_1','SDE I'), ('ui/ux','UI/UX Designer'), ('quality-engineer-trainee','Quality Engineer Trainee'), ('quality-engineer','Quality Engineer'), ('product-manager','Product Manager'), ('technical-manager','Technical Manager'), ('technical-architect','Technical Architect'), ('technical-lead','Technical Lead') ) BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) employee_name = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=100,default=None) aadhar=models.CharField(max_length=100,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) joining_role=models.CharField(max_length=250,choices=JOINING_ROLES_CHOICES,null=True) relieving_role=models.CharField(max_length=250,null=True) joining_Date=models.DateTimeField(max_length=8,null=True) relieving_Date=models.DateTimeField(max_length=20,null=True) def __str__(self): return self.employee_name I need to get the value entered in the employee_name in the User model, this code is giving the user object as the output.(for ex: if i enter the value as "vinoth" in employee_name, i need to return the same name but iam recieving it as user object 1. Kindly help me to solve this issue. -
how to remove a newletter popup when someone sucscribes in django
when someone subscribes to the newsletter i automatically want to remove the popup for the user that just subscribed, i tried create a subscribed = False then change it to subscribed = True when a user subscribes. but it doesnt work. i can easily achieve this is a user is logged i, but in this case even unauthenticated users can also subscribe to the newsletter so that is where the issue comes in. views.py subscribed = False if request.method == "POST": form = NewsLetterForm(request.POST) if form.is_valid: form.save() messages.success(request, f"Subscription Successfull, Thank you!! - Now check your mail") subscribed = True return redirect('/') else: form = NewsLetterForm() templates.html {% if subscribed != True %} <p class="mb-0">Subscribe to our <b>NewsLetter</b></p> <form class="form-inline" method="POST"> {% csrf_token %} {{form.email}} <button type="submit" class="btn btn-success-soft btn-sm" type="submit">Get Now</button> {% endif %} -
How to stop django management command after a time period using multiprocessing?
I have to run a python command function in the following manner: from django.core.management import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('plant', type=int) parser.add_argument('month', type=int) def handle(self,*args,**options): func= Library_Class() plants= options.get('plant') date= options.get('month') for plant in plants: result= func.library_function(length,breadth) return This code gives arguments to the library function which in turn returns the required output. I want to stop this command function after 100 seconds of run time. How Do I use multiprocessing to call the library function as a process and terminate the program in 100 seconds? -
Django Rest Objects being showed twice or more
Currently I have a model named Board, and a Board can be colored and shapped: class Board(models.Model): name = models.CharField(max_length=200) colored = models.BooleanField(default=False) shaped = models.BooleanField(default=False) I would like to create an API that return all colored and all shapped separated in a single request like this: [{ "all_colored": [ { "id": 1, "name": "test 1", "colored": true, "shaped": false } ], "all_shaped": [ { "id": 2, "name": "test 2", "colored": false, "shaped": true } ] }] Yeah, I need the exactly output above, no matter how I can achieve this. But currently I'm receiving this twice or more, if I create 2 Boards, I will receive twice, if i create 3 boards I'll receive three times, the current output when create 2 boards: [ { "all_colored": [ { "id": 1, "name": "test 1", "colored": true, "shaped": false } ], "all_shaped": [ { "id": 2, "name": "test 2", "colored": false, "shaped": true } ] }, { "all_colored": [ { "id": 1, "name": "test 1", "colored": true, "shaped": false } ], "all_shaped": [ { "id": 2, "name": "test 2", "colored": false, "shaped": true } ] } ] My viewset: class BoardViewSet(ModelViewSet): serializer_class = BoardSerializer queryset = Board.objects.all() def get_serializer_class(self): if self.action … -
Rendered fields manually from modelform..How can i save it?
I am beginner in django. I Rendered fields manually from modelform by using {{form.field_name}}.There are 5 fields in my model . how can i save field data by using class based view. When Rendered fields by using {% form %} then i can save my form by using CreateView.like this class StudentCreate(CreateView): model = StudentDetails fields = '__all__' success_url = reverse_lazy('list-student') but when i Rendered fields manually from modelform by using {{form.field_name}}.. i can't save it by using Createview.. Any idea about it? Why is this not working ? How can i save it? -
drf- Doesnot raise exception when give PUT request
i have image field in my model. I created one api for only edit image file only. But its not required in my model. so, I made it as required file in serializers. When i give empty file it wont through default message like field required. Here my code serializers.py class LogoApiSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ["id", "logo_filename"] extra_kwargs = {'logo_filename': {'required': True}} def update(self, instance, validated_data): image_data = validated_data.pop('logo_filename') try: if image_data is not None: instance.logo_filename.delete(save=True) instance.logo_filename = image_data instance.save() return instance except Exception as e: raise serializers.ValidationError(e) I tried this. when i not upload any file it wont go inside exception. It gives update function didnot return instance. I want show required file as default msg which throgh django itself. I shouldnot give static message exception there. Please give solution asap,.. -
Django add element in manytomany relationship inside the save method
I try to add the author field in viewed_by manytomany relationship when the model is saved but nothing is added and I don't know why. Please help me. class Message(AbstractCreateUpdate): class TypeMessage(models.TextChoices): TEXT = "TEXT" EVENT = "EVENT" IDEA = "IDEA" UPDATE = "UPDATE" id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) showcase = models.ForeignKey("Showcase", on_delete=models.CASCADE, related_name="messages", related_query_name="messages") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="messages", related_query_name="messages") type_message = models.CharField(max_length=32, choices=TypeMessage.choices) viewed_by = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="messages_visualize", related_query_name="messages_visualize", blank=True) class Meta(AbstractCreateUpdate.Meta): db_table = "message" verbose_name = _("Message") verbose_name_plural = _("Messages") def save(self, *args, **kwargs): message = super().save(*args,**kwargs) if not self.viewed_by.filter(id=self.author.id).exists(): self.viewed_by.add(self.author) return message def __str__(self): return str(self.id) -
self.queryset or super.get_queryset() for custom queryest?
Here I want to override my queryset for this should I get default queryset with self.queryset or super().get_queryset(). What's the better way ? class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.filter(value__gte=1).select_related("related") serializer_class = Myserializer def get_queryset(self): user = self.request.user qs = super().get_queryset() # OR qs = self.queryset if not user.is_superuser: qs = qs.filter(user=user) return qs OR class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = Myserializer def get_queryset(self): user = self.request.user qs = MyModel.objects.filter(value__gte=1).select_related("related") if not user.is_superuser: qs = qs.filter(user=user) return qs -
How do I change the CTA URL after password reset in Django?
So I've set Django's built-in password reset feature(?) in my project. Everything works fine, except redirection in /password_reset_complete page. The custom login url in my project is /login, but the CTA button in /password_reset_complete page is linked to /accounts/login , which causes error apparently. How do I change the CTA link in password_reset_complete page? Thanks -
how to filter data from two data base table in django
if two database table in django models. how to get latest data from both tabels. and print the order_by('date') first database table: class ANI_News_Detail(models.Model): # Represents ANI News Detail Model read_time=models.DecimalField(decimal_places=2, max_digits=12, default=0.00) news_id=models.BigIntegerField(default=0) title = models.CharField(max_length=500, default='News-title') slug = models.CharField(max_length=500, default='slug') tags = models.CharField(max_length=500, default='tags') category_name=models.ForeignKey(news_category,on_delete=models.CASCADE,null=True) sub_category_name=models.ForeignKey(news_sub_category,on_delete=models.CASCADE,null=True,blank=True) image_banner=models.URLField(max_length = 200) medium_thumbnail=models.URLField(max_length = 200) content = RichTextField() # Field Used For Paragraphs created_at=models.DateTimeField(null=True) 2 database table class News_Detail(models.Model): # Represents Our News Detail Model author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) read_time=models.DecimalField(decimal_places=2, max_digits=12, default=0.00) title = models.CharField(max_length=500, default='News-title') slug = models.CharField(max_length=500,blank=True) tags = models.CharField(max_length=500, default='tags') category_name=models.ForeignKey(news_category,on_delete=models.CASCADE,null=True,blank=True) sub_category_name=models.ForeignKey(news_sub_category,on_delete=models.CASCADE,null=True,blank=True) image_banner= models.FileField(upload_to='image_banner', blank=True, null=True) medium_thumbnail = models.FileField(upload_to='medium_thumbnail', blank=True, null=True) content = RichTextField() # RichTextField is used for paragraphs created_at=models.DateTimeField(auto_now_add=True) -
How to remove Pay later option in paypal checkout page. (we use python ,Django)
How to remove this option How to remove pay later option from paypal payment page. -
Django Testing using Testcase error finding the batch_name and instances
I am performing the testing for the models.py file Django After completing the test case for a few classes I am stuck at a point First, let me share the models.py file import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) … -
Why IsAdminUser is not naming IsStaffUser?
Why IsAdminUser is not named IsStaffUser in django restframework permmission? class IsAdminUser(BasePermission): """ Allows access only to admin users. """ def has_permission(self, request, view): return bool(request.user and request.user.is_staff) IsStaffUser seems more appropriate just to me? -
Django CSRF verification failed. Webhook payment system
I'm trying to implement a webhook for my payment system. I have a path to my webhook view, which is a simple definition where the provided id is printed. The usage is like this http://localhost:8000/api/mollie-webhook/?id=ExampleId Path # mollie webhook path('api/mollie-webhook/', mollie_webhook, name='mollie_webhook'), View def mollie_webhook(request): id = request.POST['id'] print(id) return JsonResponse(data={"response": "Success!"}) I'm getting the following error CSRF verification failed. Request aborted. -
Django_filters check if value/connection exists
Hej! I'm looking for an option on how to filter IF the value exists, the value itself is irrelevant. To filter all institutions with the given AddOn. A checkbox would be best where I can 'check' if I want my database entries filtered by this variable or not. If it's 'checked' I want to filter all entries which have the given variable and if it's not checked I don't want to filter. models.py class Institution(models.Model): name = models.CharField( verbose_name=_("Name of the institution"), max_length=200, ) abbreviation = models.CharField( # null=False, but "" allowed. Is Django convention verbose_name=_("Acronym"), max_length=25, blank=True, help_text=_("if applicable"), ) class AddInstitutionMorebio(models.Model): institution = models.OneToOneField( Institution, on_delete=models.PROTECT, related_name="institution_morebio" ) id_morebio = models.CharField( max_length=6, unique = True ) filters.py class InstitutionFilter(django_filters.FilterSet): name = django_filters.CharFilter(method='name_filter', label="Name") morebio_id = AddInstitutionMorebio.objects.filter(id_morebio=True) # this does nothing Does someone know what to do? Any help is appreciated! :) -
Creating a form that updates only 1 field of an entry
I am currently trying to create a checklist that would print a customer database. this checklist would print all the customers for a specific service - in this case, its IT14's- and it would let the user update the checklist field (isdone_IT14) However, the error I am running into at the moment, is that the form is not valid due to the fact that the rest of the fields are required. It looks like when the checklist is ticked, the form is trying to create a new entry. How would I fix that issue so that it only updates the field for that one entry? Please see the below code and errors (print(form.errors)) Models.py: class CompanyClass(models.Model): #Company Only Fields CompanyName = models.CharField(max_length=50 , blank=False) RefNo = models.CharField(max_length=50 , blank=False ) #Contact Details ContactPerson = models.CharField( max_length=50, blank=False) EmailAddress = models.CharField(max_length=50, blank=False) #Services IT14 = models.BooleanField(default=True) FinancialStatements = models.BooleanField(default=True) IsProvisionalTaxPayer = models.BooleanField(default=True) AnnualReturns = models.BooleanField(default=True) # CheckList isdone_IT14 = models.BooleanField(default=False) isdone_FinancialStatements = models.BooleanField(default=False) isdone_Provisionals = models.BooleanField(default=False) isdone_AnnualReturns = models.BooleanField(default=False) Views.py: class companyIT14(View): def get(self,request): it14s = CompanyClass.objects.filter(IT14 = True).order_by('CompanyName') form = CompanyForm() content = {'it14s':it14s , 'form':form} return render(request, 'main/Checklists/companyIT14.html', content) def post(self,request): it14s = CompanyClass.objects.filter(IT14=True).order_by('CompanyName') form = CompanyForm(request.POST) content = … -
How to serve django video streaming app on nginx
I have a django app which uses opencv videocapture to stream video from a cctv cam into my computer screen. But after hosting it using nginx. The video stream gets slowed down, hangs and sometimes quit with an error message. I read that configuring rtmp server is the way to do it but there is literally no tutorial to do so. Please Help! -
signal for custom user registration in django
help please !! I have a custom user model that I am using in my project. And I create a wallet to my new users by using signal, when they register. @receiver(post_save, sender=User) def create_saving_wallet(sender, instance, **kwargs): [...] In the function, I am doing basic things like wallet = Wallet(user_id=user, wallet_type=wallet_type, amount=amount And, I have in app.py this class to send the signal : from django.apps import AppConfig from django.core.signals import request_finished class MyAppConfig(AppConfig): def ready(self): from wallet import views # Explicitly connect a signal handler. request_finished.connect(views.create_saving_wallet, dispatch_uid="azerty123") Everything work well when we use the registration form, but if we use admin site to login the signal is called and then the old wallet is updated. How can I do to avoid this behavior ? The signal should just be called when save() method of my custom user is called. I am not sure but since I have this bug, does it mean that when a user logged in, save() method is called ? -
Django Baton installation
I am trying to add Django-Baton to my Django project but i get this error when trying to run the server: from django.utils.translation import ugettext as _ ImportError: cannot import name 'ugettext' from 'django.utils.translation' (/home/kalilinux/Desktop/Virt/myvirtualenv/lib/python3.8/site-packages/django/utils/translation/__init__.py) -
How to get a csv right into SQL
The question from a noob. I have a website from which i can download csv. This is the only purpose of the site: open it in a web-browser, enter a login + password, select the necessary fields - get a csv. The question is : are there any ways to execute this http request from my web application (django) to get this csv upload right into my SQL, bypassing the web browser? -
is Heroku apps Ranks on Google
I want to deploy my Django Project on Heroku just for testing project such as testing project. But I dont want to rank my project on google. I am not sure heroku project is rank on google or not. is any option available like I can make my project private..