Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create interactive user interface in django?
I am working on a python project using the framework Django. I want my code to display a popup window for the user with a question and different options to choose from, then the user get to choose one or multiple options, and the code continues according to the choices made by the user. How can i do this with Django ? -
Search bar in Django does not redirect correctly (website like wikipedia)
I am programming a website that works like wikipedia using Django. I have already make it able to show an entry by putting the title of the entry in the url (like, for example, http://127.0.0.1:8000/wiki/Django). Now I'm doing a search bar but introducing the name of the entry in the searchbar results in the url http://127.0.0.1:8000/wiki/?q=Django, which doesn't work. This is the form I'm using(in layout.html): <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form> <input class="search" type="search" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'create' %}">Create Page</a> </div> Those are the paths I am using in urls.py: urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entry, name="entry"), path("q", views.search, name="search") ] And this is the file views.py: from django.http import HttpResponseRedirect from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry (request, title): return render(request, "encyclopedia/entry.html", { "info": util.get_entry(title), "title": title }) def create (request): return render(request, "encyclopedia/create.html") def search (request, q): q = request.GET.get('q','') return render ("encyclopedia/entry.html", { "info": util.get_entry(q), "title": q }) I also have de file util.py with some functions: import re from django.core.files.base import ContentFile from django.core.files.storage import default_storage def list_entries(): """ Returns a … -
DateTime Picker is not saving Date
I am building a BlogApp and I am implementing a Feature of DateTime Picker using bootstrap BUT post is not adding. It is showing DateTime Picker perfectly BUT when i try to post it then page refresh BUT post is not saving. forms.py class PostForm(forms.ModelForm): date = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput()) class Meta: model = Post fields = ('post_title','date') widgets.py class BootstrapDateTimePickerInput(DateTimeInput): template_name = 'mains/bootstrap_datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = 'datetimepicker_{name}'.format(name=name) if attrs is None: attrs = dict() attrs['data-target'] = '#{id}'.format(id=datetimepicker_id) attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context create_post.html {{ form.date|as_crispy_field }} <!-- I have also loaded all the bootstrap links --> Whe i click on save post then it refresh and again it redirect on create_post page. I have no idea, what am i doing wrong. Any help would be Appreciated. Thank You in Advance. -
How to print the objects created last month instead of using datetime.timedelta(days=30)
I am making a Django app to print the expenses made each month I have been searching since a long time how to print the objects(expenses) created in a specific month(or may be last month) I checked across many stack overflow questions similar to this but was not able to find an appropriate answer. Many people use datetime.timedelta(days=30) But how can this method be proper to print the expenses of a particular month. I want to use a method like datetime.timedelta(previous month) Is there any possible way to do this? -
Django Order QuerySet based on ManyToManyField value
I have a business model as follows: class Business(models.Model): class Meta: verbose_name_plural = "Businesses" name = models.CharField(max_length=60, null=False, verbose_name="Title") about = models.TextField(max_length=5000, null=True, verbose_name="Description", blank=True) upvote = models.ManyToManyField(Account, verbose_name="Upvote Count", blank=True) The Account model is as follows: class Account(models.Model): CHOICES = [('Male', 'Male'),Female', 'Female'),] class Meta: verbose_name_plural = "Accounts" name = models.CharField(max_length=60, null=False, verbose_name="Title") gender= models.CharField(max_length=6, null=True, verbose_name="Gender", choices=CHOICES) I am trying to get a QuerySet that will be sorted by gender of the Account. How do I achieve this? So far I have achieved sorting by the upvote count. Business.objects.all().order_by("upvote") -
django: __init__() missing 1 required positional argument: 'user'
I'm trying to add a PasswordChangeForm into my project, but i gean error: "init() missing 1 required positional argument: 'user'" How can i fix it? My View: def password_change_view(request): if request.method == 'POST': pass_form = PasswordChangeForm(request.POST, instance=request.user) if pass_form.is_valid(): pass_form.save() return redirect('users/login') else: pass_form = PasswordChangeForm(instance=request.user) return render(request, 'users/change_password.html', {'password_form': pass_form}) and my html file: {% extends 'main/layout.html' %} {% block title %} Изменение пароля {% endblock %} {% block content %} <div class="user_content"> <form method="post"> {% csrf_token %} {{ password_form.as_p }} <center><button type="submit">Сохранить</button></center> </form></div> {% endblock %} I think, my mistake is somewhere in view, but i cant find it. -
HTML POST a text to Django
I need to make a form in HTML for a global search (just some selects in mysql) but I'm struggling in making the form work. I created the view: class GlobalSearch(View): template = "name.html" def post(self, request): global_json = {} if "global_search" in request.POST: global_val = request.POST["global_search"] global_json = get_all_elements(global_val) return render(request, self.template, global_json) and gave the URL in the urls.py path('global-search', views.GlobalSearch.as_view(), name='global-search'), indeed i can properly reach my view. HTML form is this: <form class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0" action="/global-search" method="POST" id="global-search">{% csrf_token %} <div class="input-group"> <input class="form-control" type="text" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2" name="global_search" id="global-search"/> <div class="input-group-append"> <button class="btn btn-primary" type="submit" name="global_search" id="global-search"><i class="fas fa-search"></i></button> </div> </div> </form> but when i submit the form, the global-search field is empty (''). What am i missing? -
channels restrict message sending based on permissions
So I have models called lockers. class Locker(CoreModel): # PLAN CHOICES BASIC = 0 BEGINNER = 1 STANDARD = 2 BUSINESS = 3 PLAN_CHOICES = ( (BASIC, 'Basic'), (BEGINNER, 'Beginner'), (STANDARD, 'Standard'), (BUSINESS, 'Business') ) PLAN_MAPPING = { settings.BEGINNER_PLAN_ID: BEGINNER, settings.STANDARD_PLAN_ID: STANDARD, settings.BUSINESS_PLAN_ID: BUSINESS } SPACE_MAPPING = { BASIC: settings.BASIC_MAX_SPACE, BEGINNER: settings.BEGINNER_MAX_SPACE, STANDARD: settings.STANDARD_MAX_SPACE, BUSINESS: settings.BUSINESS_MAX_SPACE } topic = models.CharField( verbose_name=_('topic'), help_text=_("locker description"), null=True, max_length=1024 ) icon = models.ImageField( verbose_name=_('icon'), help_text=_("locker icon"), max_length=512, validators=( MaxFileSizeValidator( max_size=settings.MAX_LOCKER_ICON_SIZE ), ), upload_to='icons/', ) name = models.CharField( verbose_name=_('name'), help_text=_("locker name"), max_length=100, validators=( MinLengthValidator(2), ) ) owner = models.ForeignKey( to=settings.AUTH_USER_MODEL, related_name='owned_locker_set', verbose_name=_('owner'), on_delete=models.CASCADE ) plan = models.SmallIntegerField( verbose_name=_('plan'), help_text=_('billing plan'), default=BASIC, choices=PLAN_CHOICES ) multiple users can join lockers. class GatewayEventsConsumer(AsyncWebsocketConsumer): """ An ASGI consumer for gateway event sending. """ # OPCODES FOR GATEWAY # COMMANDS AND EVENTS DISPATCH = 0 HEARTBEAT = 1 IDENTIFY = 2 READY = 3 HELLO = 4 HEARTBEAT_ACK = 5 def __init__(self): super(GatewayEventsConsumer, self).__init__() self.connection = None self.last_heartbeat = 0 # handlers for gateway commands self.opcode_receivers = { self.IDENTIFY: self.identify, self.HEARTBEAT: self.heartbeat } def authenticate_scope(self, token): """ sets the scope's user to the token's user object after validating the same. We need to do this explicitly without and token-authentication-middleware because … -
How to pass model fields to a signal receiver method?
I have a Founder(models.Model) with some fields like name=models.charfield; I want to execute post_save signal to a receiver function "generate" which will run a custom "management.call_command" function which takes "name" as an argument. To my understanding, this receiver "generate" function should be a method of a Founder for it to be able to take it's name field as an argument ? but when I'm creating a founder in admin, I get an error in console saying TypeError: generate() missing 1 required positional argument: 'self' -
Cross-project iframe testing on localhost with different ports
I am relatively new to iFrame, and what I try to do is to load project A in an iframe that is in project B. Project A is running as a Django project on localhost:8000, and project B as a separate Django project on localhost:8001. Inside the project B, I have a Django template with the following content: <iframe src="http://127.0.0.1:8001" height="500px" width="500px"></iframe> The problem is that instead of seeing the content of project A home page, I see error message stating that: 127.0.0.1 refused to connect Is there anything I am terribly missing? -
Nested if in Django Rest API [closed]
Want to update details in two models,so here using curresponding serializers and the out: first key value is updated but remaining is still not updating Help to solve this -
Django: Method to execute after "clean" in admin
Fairly simple: Which method can be overwritten after "clean" method? I am using "clean" to verify an uploaded image and once I confirmed it is ok and saved, I want to switch it using some external API: class FooAdminForm(forms.ModelForm): class Meta: model = Asset fields = ["name", "file",] def clean(self): cleaned_data = super(FooAdminForm, self).clean() ... return cleaned_data def bar(self): # do stuff with new data in database class FooAdmin(admin.ModelAdmin): list_display = ["name", "file",] form = FooAdminForm is there some method bar that can do what I need? Or do I have to wrsetle with a signal (like here)? -
Как в cookie хранить значение checkbox, чтобы у сайта была возможность вкл темный режим django [closed]
Я новичок и хочу в сайте сделать темный режим любим способом будто с помощью django или js -
django-rest-framework csrf cookie not set react
I am new to Django, react and "http header" related stuff. My django dev server runs at: http://127.0.0.1:8000/ and my react dev server runs at: http://127.0.0.1:3000 In order to access the website, login is required. So, all unauthorized requests are 1st redirected to login page, by configuring react-router and following this template. So, till now, no api calls are made. In order to post login data, i need to have csrf token set by the server. But since i have not made any api calls, i created an endpoint /api/csrf/ explicitly, to set the csrf token. # URL: /api/csrf/ class CSRFGet(APIView): """ Explicitly set csrf cookie """ @method_decorator(ensure_csrf_cookie) def get(self, request): return Response('hello') I call this endpoint, when useProvideAuth hook is mounted. function useProvideAuth() { const [token, setToken] = useState(null); const login = (username, password) => { return axios.post( '/auth/', { username: username, password: password }) .then(response => { setToken(response.token) }) } useEffect(()=> { axios.get( '/csrf/' ) },[]) return { token, login, } } To retrieve and set this cookie, i followed the official Django docs. I also enabled CORS policy using django-CORS-headers allow all origins. Now, when i make a request to any page, it redirects to login page, … -
preview before save image in Django admin inline
I'd like to preview the picture chosen as [choose file]. Like in the picture below. I'm using django, what should I do? admin.py class GolferPhotoInline(NestedStackedInline): model = GolferPhoto extra = 1 formset = GolferPhotoInlineFormset class GolferProfileInline(NestedStackedInline): model = GolferProfile extra = 1 inlines = (GolferPhotoInline,) @admin.register(GolferUser) class GolferUserAdmin(NestedModelAdmin): inlines = (GolferProfileInline,) readonly_fields = ("user_gender", "user_join_dts", "is_secession") fields = ["user_nm", "user_gender", "user_email", "user_tel"] list_display = [ "id", "user_nm", "user_gender", "user_email", "user_tel", "is_secession", "user_join_dts", ] -
How to create password confirmation with old password for update profile?
I want to create a confirmation for updating the profile. For example, when a user wants to change name or password, he/she should enter their old password for confirmation. How can I do that? models.py class UserProfile(AbstractUser, UserMixin): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=250) email = models.EmailField(max_length=254) image = models.ImageField(upload_to='profile_image', blank=True, null=True, default='profile.png') views.py def update_user(request, id): user = request.user form = SignUpChangeForm(request.POST or None, request.FILES or None, instance=user) if form.is_valid(): form.save() ... if form.cleaned_data['password1'] != "": user.set_password(form.cleaned_data['password1']) user.save() auth_login(request, user) return redirect('home') context = { 'form': form, } return render(request, "update_user.html", context) forms.py class SignUpChangeForm(forms.ModelForm): password1 = forms.CharField(max_length=250, required=False, label="New Password (leave blank if you do not want to change it)", widget=forms.PasswordInput) password2 = forms.CharField(max_length=250, required=False, label="New Password Confirmation (leave blank if you do not want to change it)", widget=forms.PasswordInput) class Meta: model = UserProfile fields = ('first_name', 'last_name', 'email', 'image') widgets = { 'password1': forms.PasswordInput(), 'password2': forms.PasswordInput(), 'old_password': forms.PasswordInput(), } def clean(self): cleaned_data = super(SignUpChangeForm, self).clean() if cleaned_data['password1'] != cleaned_data['password2']: raise ValidationError("Password confirmation does not match!") return cleaned_data -
How to Group by timestamp column serving as PK by day/month/year, and select that timestamp column at the same time in Django
I have a table with a 'timestamp' field as its PK. In Django View, I want to select all from the table and group by month('timestamp) and year('timestamp). In terms of MySQL script, I am looking for this: SELECT timestamp, sum(col1) col1, sum(col2) col2 FROM my_table GROUP BY MONTH(timestamp), YEAR(timestamp) ORDER BY timestamp One approach I have followed is from here. You can find more elaboration on that answer here. So to GROUP BY the rows, I work with annotate and values as discussed in this answer. The code in my Django View is the following: from django.db.models.functions import TruncMonth, TruncYear from django.db.models import Sum queryset = MyModel.objects .annotate(month=TruncMonth('timestamp'), year=TruncYear('timestamp')) .values('month', 'year') #Group by Month and Year .annotate(col1 = sum('col1'), col2 = sum('col2')) #Sum data of two columns .order_by('month', 'year') #Also tried 'timestamp' here. queryset_serialized = MySerializer(queryset, many=True) The code above does produce the query as expected. Here is the query generated from the code above: SELECT CAST(DATE_FORMAT(`timestamp`, '%Y-%m-01 00:00:00') AS DATETIME) AS `month`, CAST(DATE_FORMAT(`timestamp`, '%Y-01-01 00:00:00') AS DATETIME) AS `year`, SUM(`col1`) AS `col1`, SUM(`col2`) AS `col2` FROM `my_table` GROUP BY CAST(DATE_FORMAT(`timestamp`, '%Y-%m-01 00:00:00') AS DATETIME), CAST(DATE_FORMAT(`timestamp`, '%Y-01-01 00:00:00') AS DATETIME) ORDER BY `month` ASC However, while serializing the data … -
How to catch / get json from webhook in Django?
I am working with Pipedrive and Django. So far I have the following: I have configured a webhook in pipedrive that fires every time a new Deal is created, I am receiving the correct http status in the Django console, however, I cannot capture the data from the json that the webhook sends . The idea is to capture that data and then enter it into Django's model. -
Call function after update/bulk_update in Django
I am calling a function after an object is created in the model like this: class MyModel(models.Model): name = models.CharField() image = models.OneToOneField(Image, on_delete=models.CASCADE) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.image.my_function() Now I want to call the same function after updating/bulk_updating the instances. I know I can create a post_save listener which can handle the case after update(), but how to call the function after bulk_update()? -
Odoo developer as a Full stack developer
Is odoo developer will work as a full stack developer later in career. He can work on core python and framework like Django??? -
Setting time zone according to user's Country
I am building a BlogApp AND i am stuck on a Problem. What i am trying to do :- I am trying to store timezone in every field ( post date, comment date ) according to User's Country. Suppose, A user is registered account on webapp from Brazil then i am trying to automatically set time zone of Brazil for the User. But i have tried many answers LIKE THIS and LIKE THIS but nothing worked for me. Some told that it should be done through JavaScript BUT i have no idea idea how can i do it. When i try to register then it automatically sets the timezone which i have settled in settings.py. TIME_ZONE = 'UTC' Any help would be appreciated. Thankyou in advance. -
user register form in the django not getting register
I am trying to register the user of the django website but it was not getting register I am posting the code please help me this is the code of the views.py where I get the input from django.shortcuts import render , redirect # Create your views here. from django.contrib.auth import login from django.contrib.auth.forms import UserCreationForm from .models import User_Main def become_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request , user) user_main = User_Main.objects.create(name = user.username, created_by=user) return redirect('home') else: form = UserCreationForm() return render(request, 'user_of_ecommerce/become_user.html' ,{'form':form}) code of urls.py from django.urls import path from . import views urlpatterns = [ path('become-user/' , views.become_user , name="become_user") ] and here is the code of the form {% extends "core_of_ecommerce/base.html" %} {% block content %} <form action="." method="post" > {% csrf_token %} {{form.as_p}} <div> <button>sbmot</button> </div> </form> {% endblock content %} another URLs.py from django.urls import path from . import views urlpatterns = [ path('' ,views.home, name='home') ] -
One transaction for mongoDB and MySQL with one to many relationship
My Django application uses both MySQL and MongoDB to store its data. I need to create one transaction to delete an instance with its relations from both MySQL and MongoDB. If the execution of one of the queries fails (SQL or Mongo) I must rollback all the executed queries. Is that possible? Example: from django.db import models class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer',on_delete=models.CASCADE) # ... def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document tr return super(Instance, self).delete(*args, **kwargs) class Motorcycle(models.Model): manufacturer = models.ForeignKey('Manufacturer',on_delete=models.CASCADE) # ... def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document tr return super(Instance, self).delete(*args, **kwargs) class Manufacturer(models.Model): # ... pass def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document transaction) return super(Instance, self).delete(*args, **kwargs) When I delete a manufacturer, I need to delete the related cars and motorcycles from both MySQL and MongoDB. If one transaction fails (let's say delete one of the motorcycles has failed for some reason), I need to rollback all the transactions. Is there any way to do it? -
preferred way of designing model in Django
I have a very simple model in Django with 3 fields. The issue is that I have dozens of billions of data that needs to be stored in the table associated with that model in Postgresql database. I stored around 100 millions of rows, and then my server first got sluggish and then gave me "Nginx 505 bad gateway" when clicking on that table in Django admin or requesting data using API. I was wondering what is the best way to handle this simple scenario of having massive data in Django. What's the best model. Should I split my model in order to split my table? Thanks, -
Why does ChannelsLiveServerTestCase doesn't allow file upload
I am currently using ChannelsLiveServerTestCase to spin-up a runserver for my test, for some reason when I try to test my file upload feature it is failing but when I try using different "test server" (StaticLiveServerTestCase) it is working well. I opted to use ChannelsLiveServerTestCase because I need the websocket support which is not possible with StaticLiveServerTestCase.