Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django.mo and Django.po files while moving to a Linux server
I am following CoreySchafer's tutorial to deploy my Django app onto a linux server. When I start copying the files to a linux server it finishes it but it takes a lot longer than his because in my case it is copying A LOT of django.mo and django.po files ? In his example none of that is happening ? I am struggling to understand why is that ? I don't like the idea of something working for me but me not knowing why is it working the way it is. -
why error_messages dictionary doesn't working in Meta class in forms.py?
My forms.py from django.core.exceptions import ValidationError from django.forms import ModelForm from django import forms from . models import Detail class DetailForm(ModelForm): name = forms.CharField(validators=[not_contain_number], required=True) email = forms.EmailField(required=True) phone_no = forms.IntegerField( validators=[number_validation], required=True) class Meta: model = Detail error_messages = { 'name': { 'required': 'enter your name', }, } labels = {'name': 'Your Name', 'email': 'Your Email', 'phone_no': 'Your Phone No.'} widgets = {'name': forms.TextInput( attrs={'placeholder': 'type your Name'})} fields = ['name', 'email', 'phone_no'] Does it occurs due to my any mistake in ModelForm API? It is working when i used it while defining: class DetailForm(ModelForm): name = forms.CharField(validators=[not_contain_number], required=True,error_messages={'required': 'Enter Your Name'}) -
Django: local variable 'form' referenced before assignment
With the post Proper way to handle multiple forms on one page in Django I tried to create multiple forms in just one template, so when I press just one submit button, it doesn't submit all the forms right away. I gave my submit buttons a name, for example form1_btn for my first form. Before I could even try if it works, I get the following error, even though I specified in the Else statement what happens when request != 'POST local variable 'form' referenced before assignment View Files @login_required def DashboardView(request): browser = str(request.user_agent.browser.family) user = str(request.user) short_user = user[0:7] + "..." try: radius = request.user.fieldradius except FieldRadius.DoesNotExist: radius = FieldRadius(user=request.user) try: font_size = request.user.fontsize except FontSize.DoesNotExist: font_size = FontSize(user=request.user) try: change_color = request.user.colors except Colors.DoesNotExist: change_color = Colors(user=request.user) try: toggle_settings = request.user.togglesettings except ToggleSettings.DoesNotExist: toggle_settings = ToggleSettings(user=request.user) try: page_details = request.user.pagedetails except PageDetails.DoesNotExist: page_details = PageDetails(user=request.user) if request.method == 'POST': if 'form1_btn' in request.POST: form = FieldForm(request.POST, prefix='form1', instance=Field(user=request.user)) if form.is_valid(): obj = form.save(commit=False) obj.creator_adress = get_client_ip(request) obj.save() return redirect('/dashboard#5') elif 'form2_btn' in request.POST: togglesettings_form = ToggleSettingsForm( request.POST, prefix='form2', instance=toggle_settings) if togglesettings_form.is_valid(): togglesettings_form.save() return redirect('/dashboard/#panel1') elif 'form3_btn' in request.POST: radius_form = FieldRadiusForm( request.POST, prefix='form3', instance=radius) if radius_form.is_valid(): radius_form.save() … -
Multiform - how can i control each button seperately
How can i use 2 forms in 1 page by using class based view in Django. I have 2 different models tables and i created 2 different forms for each model. Each form contain 1 button each. each form submits different data. I have no of fields in my 1st form and have 1st button. parallel to 2nd field i created my 2nd button(used 2nd form there). Each button saves data for different models. currently works 1st form control for my 2 button. How can i control each button seperately.. which technique i want to use for that? I searched about multiform.. but i can't find good solution.. -
How to display the values of the attributes of the data queried and retireved by ajax call in django
I am trying to query the database based on what the user has clicked on the page and display the data retrieved by it wihtout refreshing the page. I am using ajax for this. Let me show you the codes html <label for="landacq" class="civil-label">Land Acquisation Cases</label> <input class="civil-category" type="radio" name="civil-cat" id="landacq" value="land acquisation" hidden> <label for="sc" class="civil-label">Supreme Court</label> <input class="civil-court" type="radio" name="civil-court" id="sc" value="supreme court" hidden> <label for="limitation" class="civil-label">Limitation</label> <input class="civil-law-type" type="radio" name="civil-law-type" id="limitation" value="limitation" hidden> js for (i = 0; i < lawTypeInput.length; i++) { lawTypeInput[i].addEventListener("click", (e) => { e.preventDefault(); cat = civilCatval; court = civilCourtval; lawT = civillawTypeval; console.log("this is from ajax : ", cat, court, lawT); $.ajax({ type: "POST", headers: { "X-CSRFToken": csrftoken }, mode: "same-origin", // Do not send CSRF token to another domain. url: "civil", data: { "cat[]": civilCatval, "court[]": civilCourtval, "lawT[]": civillawTypeval, }, success: function (query) { showCivilQ(query); // console.log(data); }, error: function (error) { console.log(error); }, }); }); } function showCivilQ(query) { q.textContent = query; console.log(query); } So here for example, if the user the click the radio button in the html, the values are grabbed by in js file and then sent to the url mentioned as a POST request. There these … -
Python: Regex for four of more words and hyphens
I want to match a slug with 4 or more words using regex Example - /productivity-courses-and-programs/ , /artificial-intelligence-courses-and-programs/ should match but /ai-category/ , /data-science/ or /data-science-category/ shouldn't. Tried r'^(?P<slug>\w+(?:-\w+)+)/$ but this takes all of the above example. -
django 404 - a list of known urls includes one that is reportedly not found
in my core urls.py, an app-specific urls.py is included, with namespace set to 'accounts'. path("accounts/", include("shop.apps.accounts.urls", namespace="accounts")), in that accounts.urls, likewise, nothing appears to be missing. Using stock views: from django.contrib.auth import views as auth_views and defining, among others in urlpatterns, this one: path("logout", auth_views.LogoutView.as_view(next_page="/accounts/login/"), name="logout"), Everything appears to be in place. And yet when I click on the logout link defined thus: <a href="{% url "accounts:logout" %}">Logout</a> , I receive a mysterious Page Not Found 404. I say mysterious, because the 404, when in DEBUG=True, lists all the urls which Django knows about - including this item: accounts/ logout [name='logout'] whaaat? I do notice some strange extra space in "[namespace]/ [path]", but I don't think it matters. Any suggestions are much appreciated, thanks! -
Python was not found showing in windows cmd even added path but pip --version has no problem
python -- version showing run without argument but pip --version showing proper output in windows cmd even I add path when installing python -
Render Plotly chart without background
I have a Plotly donut chart rendering in my Django template that comes with a default white background. I can't figure out how to render it without the background. I know how to make the background transparent but when I try to resize the chart, obviously the background is still there and it stretches the div or if I make the chart smaller so it fits then its too small and unreadable. Is there a way to get rid of the background all together? Or maybe I should use something other than Plotly? Thanks for your help! import plotly.graph_objects as go fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.3)]) fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', width=300, height=300,) chart = fig.to_html() -
Display Recent 3 Record from Django model in a HTML Template
I would like to show the latest 3 posts in the Latest Posts section of my page. How can I do it without using for loop or is that the only way? I was successful to get the result in the shell console, however, I am not able to show it in the HTML template. Please help models.py from typing import Any from django.db import models from django.contrib.auth.models import User from django.utils import timezone from ckeditor.fields import RichTextField class BlogPost(models.Model): blogpic = models.CharField(max_length=1000) title = models.CharField(max_length=255) description = models.CharField(max_length=100, default='Enter a short desctiption', editable=True) body = RichTextField(blank=True, null=True) category = models.CharField(max_length=50, default='banking', editable=True) tag = models.CharField(max_length=50, default='consulting', editable=True) author = models.ForeignKey(User, on_delete=models.CASCADE) blog_date = models.DateField(default=timezone.now, editable=True,) def __str__(self): return self.title + ' | ' + str(self.author) views.py from django.views.generic import ListView, DetailView from . models import BlogPost class BlogView(ListView): model = BlogPost template_name = 'blog.html' ordering = ['-blog_date'] class BlogDetailsView(DetailView): model = BlogPost template_name = 'blog_details.html' urls.py from django.urls import path from AssayBlog.models import BlogPost from . views import BlogView, BlogDetailsView urlpatterns = [ path('', BlogView.as_view(), name="blog"), path('_detail/<int:pk>', BlogDetailsView.as_view(), name="blog_details"), blog_details.html <h3 class="sidebar__title">Latest Posts</h3> <ul class="sidebar__post-list list-unstyled"> <li> <div class="sidebar__post-image"> <img src="{% static 'assets/images/blog/lp-1-1.jpg' %}" alt=""> </div> <div class="sidebar__post-content"> <h3> … -
Подскажите, как вывести данные на страницу?
Пишу погодное приложение и вроде все работало, а потом перестало выводить в самом приложении . В базу данных все добавляет, но выводит только сломанный шаблон. В чем дело? 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.