Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Group by month based on DateTime Field
I have a model for hotel reservations: class PaymentRequest(SoftDeleteModel): class Meta: verbose_name_plural = "PaymentRequests" user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False, default=None) customer_first_name = models.TextField(blank=False, null=False) customer_last_name = models.TextField(blank=False, null=False) arrival_date = models.DateTimeField(blank=True, null=True) What I'd like to do is make a queryset to group my reservations by month and get a count of it. i.e {'jan' : 10, 'feb' : 11, etc..} I've seen some answers like this but does not work quite right, maybe since it was answered 10 years ago. Appreciate any help. -
this is the code for my manage.py script i would like someone to explain each line please i barely understand it
import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookr.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() the code works i just do not understand why -
How to convert a queryset quickly?
Through an ajax request I request data from the database that has 70 thousand lines. The query is very fast, it lasts 0.2 seconds but I can't return it because I can't return queryset by JsonResponse, so I have to convert it to json but that's the problem. How to convert as fast as possible? I tried using the following code, but it still takes like 6 seconds. queryset = Users.objects.all() list = [] [list.append({"id": query.id, "name": query.name}) for query in queryset] return JSONResponse(list, safe=False) -
How Do I properly create a three column responsive grid
I'm having a little difficulty implementing a three column grid in Django. I'm trying to create a page where my blog post are displayed in columns of three. I'm using bootstrap to do this and I just cant seem to figure out how to get this right. I implemented a for loop in order to display a grid of three. I'm either getting three of the same articles. Which is not what i'm trying to accomplish. Please let me know if you have any idea of how I accomplish fix this. Below you can find my code. {% for post in object_list %} <div class="row "> <div class="column" style="background-color:#grey" > <div class="card h-100 " style="max-width: 24rem; max-height: 28.5rem; "> <img src="{{ post.header_image.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"><a href="{% url 'article-detail' post.pk post.slug %}">{{ post.title }}</a></h5> <p class="card-text">{{ post.snippet }}</p> </div> <div class="card-footer"> <small class="text-muted">By: {{ post.author.first_name }} {{ post.author.last_name }} - {{ post.post_date }} - </small> <a href="{% url 'category' post.category|slugify %}" style=text-transform:uppercase;">{{ post.category }}</a> </div></div></div></div> {% endfor %} -
Unable to install mysqlclient using virtualenv (Fedora 37)
I am developing an app using Django 4 and have set up a virtual environment using venv. THe problem I have is I cannot get the mysqlclient package installed using pip in order to allow my django app to connect to an existing MariaDB hosted on the same server. I am using Fedora 37, Python 3.11.1 . Everytime I try to install mysqlclient via pip within my virtual environment I the the below error: (venv) $ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [18 lines of output] /bin/sh: line 1: mysql_config: command not found /bin/sh: line 1: mariadb_config: command not found /bin/sh: line 1: mysql_config: command not found Traceback (most recent call last): File "", line 2, in File "", line 34, in File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup.py", line 15, in metadata, options = get_config() ^^^^^^^^^^^^ File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup_posix.py", line 70, in get_config libs = mysql_config("libs") ^^^^^^^^^^^^^^^^^^^^ File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not … -
Django many-to-many: I want to query the bootcamps the user has signed up for
#This is my Model.py from django.db import models from django.contrib.auth.models import User class Tipo_Categoria(models.Model): nombre = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) class Bootcamp(models.Model): titulo = models.CharField(max_length=50) contenido = models.CharField(max_length=500) imagen = models.ImageField(upload_to='bootcamps') requisito1 = models.CharField(max_length=100) autor = models.ForeignKey(User, on_delete=models.CASCADE) categoria = models.ManyToManyField(Tipo_Categoria) fecha_inicio = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) class ProgramasAcademico(models.Model): codigo = models.BigIntegerField(null=False, unique=True, primary_key=True) nombre = models.CharField(max_length=100) status = models.BooleanField(default=True) class BootcampInscripcion(models.Model): cedula = models.IntegerField(blank=True, null=True) nombre = models.CharField(max_length=100) apellido = models.CharField(max_length=100) usuario = models.ForeignKey(User, on_delete=models.CASCADE) carrera = models.ManyToManyField(ProgramasAcademico) email = models.EmailField(max_length=254) direccion = models.CharField(max_length=100) telefono = models.CharField(max_length=10) bootcamp = models.ManyToManyField(Bootcamp) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) #This is my Views.py from django.shortcuts import render from bootcamps.models import * from django.contrib.auth.models import User def mis_bootcamp(request,id): try: bootcampBd = BootcampInscripcion.objects.filter(usuario=id) except BootcampInscripcion.DoesNotExist: print("no tiene cursos") else: cursos = Bootcamp.objects.filter() #Bootcamps return render(request, "campus/mis_bootcamp.html",{"bootcampBd":bootcampBd,"cursos":cursos}) Each user has signed up for a bootcamp or several. I want you to help me is in which It would be the query or the way to filter only the bootcamps to which the user signed up. user and thus publish (title, image) of the bootcamp in the html. I appreciate your help. -
Django DJStripe access fields from foreign key in template
I have a user model with a foreign key that points to Subscription which is imported from DJ Stripe. class User(PermissionsMixin, AbstractBaseUser): ... subscription = models.ForeignKey(Subscription, on_delete=models.SET_NULL) ... The Subscription table in djstripe has a subscription field and a created field which I am trying to access through my template like this: {{ user.subscription.subscription }} or {{ user.subscription.created }} I have tried several variations with double underscores or subscription_set.get but I am really just scratching my head. Is there a simple way to access those fields in my template? -
django if elif statement fails: IndentationError
In Django i have two forms. In my code i wanna check which form is filled with a value by the user. I use this to check which form is used: def test(context): if request.method == 'GET' and 'q' in request.GET: --do_something-- elif request.method == 'GET' and 'y' in request.GET: --do_something_else-- <form action="/my_page"> <label for="lblq">find something:</label><br> <input type="text" id="lblq" name="q"><br> <input type="submit" value="find q"> </form> <form action="/my_page"> <label for="lbly">find something else</label><br> <input type="text" id="lbly" name="y"><br> <input type="submit" value="find y"> </form> But i get an error: elif 'q' in request.GET: ^ IndentationError: expected an indented block after 'if' statement on line 12 Don't see the problem, am i missing something? Thnx in advanced. -
I can't get metadata from stripe session in django
I'm doing a course in udemy and there's a stripe payment lesson in django. And the problem is that today's stripe docs are different from docs from the lesson and I can't do a one thing: get an order_id from the order to make my function work correct (function change order status, save order in 'basket_history' dict and delete an actual basket). There are code from the video and my one: views.py Similar code: class OrderCreateView(TitleMixin, CreateView): title = 'Store - Оформление заказа' template_name = 'orders/order-create.html' form_class = OrderForm success_url = reverse_lazy('orders:order_create') def post(self, request, *args, **kwargs): super().post(request, *args, **kwargs) baskets = Basket.objects.filter(user=self.request.user) checkout_session = stripe.checkout.Session.create( line_items = baskets.stripe_products(), metadata = {'order_id': self.object.id}, mode='payment', success_url='{}{}'.format(settings.DOMAIN_NAME, reverse('orders:order_success')), cancel_url='{}{}'.format(settings.DOMAIN_NAME, reverse('orders:order_canceled')), ) return HttpResponseRedirect(checkout_session.url, status = HTTPStatus.SEE_OTHER) def form_valid(self, form): form.instance.initiator = self.request.user return super(OrderCreateView, self).form_valid(form) @csrf_exempt def my_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) Then the difference My code: # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': # Retrieve the session. If you require line items in the response, you may include … -
How to get a queryset from many to many field
I have this model and i want to retrieve all the "members" as queryset class Team(models.Model): name = models.CharField(max_length=120) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner') members = models.ManyToManyField(User, related_name='members') # <--- I tried this but its not working Team.objects.all()['members'] # and Team.members.all() -
How to fetch related model in django_tables2 to avoid a lot of queries?
I might be missing something simple here. And I simply lack the knowledge or some how-to. I got two models, one is site, the other one is siteField and the most important one - siteFieldValue. My idea is to create a django table (for site) that uses the values from siteFieldValue as a number in a row, for a specific site, under certain header. The problem is - each site can have 50s of them. That * number of columns specified by def render_ functions * number of sites equals to a lot of queries and I want to avoid that. My question is - is it possible to, for example, prefetch all the values for each site (SiteFieldValue.objects.filter(site=record).first() somewhere in the SiteListTable class), put them into an array and then use them in the def render_ functions by simply checking the value assigned to a key (id of the field). Models: class Site(models.Model): name = models.CharField(max_length=100) class SiteField(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.name class SiteFieldValue(models.Model): site = models.ForeignKey(Site, on_delete=models.CASCADE) field = models.ForeignKey(SiteField, on_delete=models.CASCADE) value = models.CharField(max_length=500) Table view class SiteListTable(tables.Table): name = tables.Column() importance = tables.Column(verbose_name='Importance',empty_values=()) vertical = tables.Column(verbose_name='Vertical',empty_values=()) #... and many … -
Django many-to-many: Quiero consultar los bootcamps a los que el usuario se haya inscrito
#Model.py from django.db import models from django.contrib.auth.models import User Cada usuario se ha inscrito a un bootcamp o a varios. Quiero que me ayuden es en cual sería el query o la forma de filtrar sólo los bootcamps a los que se inscribió el usuario y asi publicar(titulo,imagen) de los bootcamp en el html. Les agradezco su ayuda. -
Unable to login and redirect in django
I am unable to login and redirect to home page using the custom login view (user_login) and AuthenticationForm. However, if i login using the admin page (http://127.0.0.1:8000/admin) and then reopen login page it automaticaly redirects to home page. There is some issue related to authentication which is not getting done from my custom login page/view .I am unable to fix this or identify resolution based on answers provided online. There is another issue regarding the URL it is showing as http://127.0.0.1:8000/login/?csrfmiddlewaretoken=FhHQjhGGgFDwcikpH9kl3OwQMcZisjWS2zvMHFGBU6KxGNWbamgago7FhtSs8MeN&username=admin&password=admin However, Password and Username should not be showing in the URL if form method is post. URL urlpatterns = [ path("", views.index, name="index"), path("signup/", views.user_signup, name="signup"), path("login/", views.user_login, name="login"), path("home/", views.homepage, name="home"),] Views def user_login(request): if request.user.is_authenticated: return redirect("/home") else: if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("home") else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render( request=request, template_name="socialapp/login.html", context={"login_form": form}, ) def homepage(request): return render(request=request, template_name="socialapp/home.html") Login HTML <form action="{% url 'login' %}" id="login-form" method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"> {% csrf_token %} {{ login_form|crispy }} <button … -
Django class-based form with dropdowns populated with data from model / db
This my Django code: forms.py from django import forms class ReleaseForm(forms.Form): name = forms.CharField() location = forms.CharField() views.py class MyFormView(FormView): template_name = 'form.html' form_class = MyForm success_url = 'home' def get(self, request, *args, **kwargs): form = self.form_class return render(request, 'form.html', {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect('home') else: return render(request, self.template_name, {'form': form}) template form.html <form method="post" action="{% url 'form' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary btn-block py-2" value="OK"> </form> I want both two fields (name, location) to be drop-downs (combobox-es) not CharFields, and I want to populate their entries / values with data coming from db (django models). How can I do that? I am completely new to CBV idea. -
Django4.1 Как в настройках проекта urls ссылаться на другие приложения если их необходимо включить через одинаковый url ""
Столкнулся с проблемой. urls.py в проекте: urlpatterns = [ path('admin/', admin.site.urls), path('', include('catalog.urls')), path('', include('account.urls')), ] urls.py в приложении 1 urlpatterns = [ path('', views.main, name='home'), path('<slug:url>/', views.detail_category, name='detail_category'), ] urls.py в приложении 2 urlpatterns = [ path('register/', views.register_account, name='register'), path('login/', views.login_account, name='login'), path('logout/', views.logout_account, name='logout'), ] в представлении вывожу вот так: <a href="{% url 'app1:login' %}">LOGIN</a> <a href="{% url 'app1:register' %}">REGISTRATION</a> Как вариант в проекте сослаться на account/ тогда все будет работать. Например вот так все заработает: urlpatterns = [ path('admin/', admin.site.urls), path('', include('catalog.urls')), path('account/', include('account.urls')), ] Как вариант в проекте сослаться на account/ тогда все будет работать. Например вот так все заработает: urlpatterns = [ path('admin/', admin.site.urls), path('', include('catalog.urls')), path('account/', include('account.urls')), ] Какие есть еще варианты ? -
Django passing dynamic URL parameter into reverse function
I have just stated to learn Django. So far I pass dynamic URL parameters into reverse function inside the get_absolute_url() method in the following ways: # By using kwargs: def get_absolute_url(self): return reverse('book-detail', kwargs={'id':self.id}) # Or by using the args: def get_absolute_url(self): return reverse('book-detail', args=[self.id]) # But I found several examples of the following code: def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)] I have used the simple library app to pass id of the book into URL in order to get book details. All three variants work fine without any problem. Can somebody explain to me why and when we should use args=[str(self.id)]? -
Django model /w foreign keys transform to CreateView model or form problem
Good day everyone! I’ve made models with related objects, and now I’m stuck as I can’t manage CreateView class.. Let’s imagine that we have these abstract models: class NameValues(models.Model): name = models.CharField(…) value = models.CharField(…) group = models.ForeignKey(GroupOfValues, …) class GroupOfValues(models.Model): sheet = models.ForeignKey(ResultSheet, …) class ResultSheet(models.Model): date = models.DateField(…) name = models.CharField(…) class NameValues(models.Model): name = models.CharField(…) value = models.CharField(…) group = models.ForeignKey(GroupOfValues, …) class GroupOfValues(models.Model): sheet = models.ForeignKey(ResultSheet, …) class ResultSheet(models.Model): date = models.DateField(…) name = models.CharField(…) So is it possible to make a form for ResultSheet or CreateView class that can automatically generate all child forms from related objects? Form Date: 03.02.2023 Name: Some research Group of values: select option would be great [Parameters #1] Age: 32 Height: 180 Weight: 70 Really appreciate any help or advice -
How to port django application's code to python3?
I have a django project that has been developed in python2.7 version. Now I decided to port the code to python3. Porting python2 code to python3 is documented here. One way I chose to port my application is to use futurize tool. I am able to port python2 code to python3 using the futurize: futurize --stage1 -w filename.py and futurize --stage2 -w filename.py. My problem here is that it would become a huge task for me to run this command for each and every file on whole project. Is there any other way to run a command and port the whole django application code to python3? -
What does the thottle_user_ip when caching in django mean?
I implemented django cache like this in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'requests_cache_table', } } And added a simple caching mechanism around my subscription check as follows: stripe_subscription = cache.get(f'stripe-subscription-user:{user_id}') if stripe_subscription is None: stripe_subscription = stripe.Subscription.retrieve(subscription.subscription) cache.set(f'stripe-subscription-user:{user_id}', stripe_subscription, timeout=3600) This correctly works and I see user caches being added to my database. However, every time I login ip adresses are also cached. Even when I remove the caching functions described above. Why does this happen and what does this mean? -
Is serializing a field as FileField and JsonField possible?
My question is simple. In Django REST Framework, is it possible to serialize the same field as either FileField() or JsonField()? which means my serializer must be able to validate the user request provided as Json or csvfile for the same field. Is it possible? Can anyone tell me? -
How to display values from the second field of the form - depending on the selected value of the first field?
I have a Django form. In which there are two select fields from several values. The data from them is contained in the Django model database. The first field of the form contains car brands. In the second field of the form, I would like to display car models - depending on the car brand selected above. How can I make the data appear in the second field of the form depending on the selected value of the first field? -
QuerySet function in Python doesn't return a string
I created a function in Python that converts the QuerySet information into a string. But it isn't working as expected, it does recognize there's an object but it doesn't convert it to string. Function: def __str__(self): return f"{self.id}: {self.origin} to {self.destination}" My python shell: >>> from flights.models import Flight >>> flights = Flight.objects.all() >>> flights <QuerySet [<Flight: Flight object (1)>]> Instead of the last line, I should be getting "Flight: 1: New York to London" -
How to set up Login View in Python Django?
I'm trying to set up passkeys to a testing Django website I made a while back following this guide, but at some point I get asked to "In your login view, change the authenticate call to include the request as follows": user=authenticate(request, username=request.POST["username"],password=request.POST["password"]) However I don't have a Login view as I'm using this in my urls.py: path("login/", userViews.LoginView.as_view(), name="login"), I've tried to look up for guides in how to set up a login view manually but they all get me to the simplified version I'm using already. Is there way to add that line regardless? Otherwise, how do I create a login view manually and how should I change my login.html file? Thanks! -
How to solve RuntimeError: populate() isn't reentrant without changing the django file?
I receive this error in a do droplet. I've installed all requriements listed in installed apps + used inside my project, but the error still points at: File "/usr/local/lib/python3.10/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) I know about this possible change in the django file: self.app_configs = {} Anyways I think I should not change it on the server as I've read its not recommended. Are there other soloutions to solve my unknown issue? My requirements.txt: psycopg2-binary gunicorn Django django-pghistory djangorestframework django-rest-knox markdown django-jazzmin django-celery-results django-cors-headers django-crispy-forms django-environ django-filter django-redis whitenoise django-json-widget crispy-bootstrap5 sendgrid pytz celery flower django-celery-beat eventlet pandas requests django-select2 django-allauth django-tables2 django-htmx simplejson django-mathfilters django-user-agents scipy more-itertools django-debug-toolbar -
How can I write my POSTgresql query in django (column is using JSON and arrays)?
I have a JSON column that is 2 levels deep and has an array of objects at the deepest level. I want to look this up in Django. How can I do it using Django syntax? data is the json column inside my table1. SELECT * FROM table1, jsonb_array_elements(data->'comm') comm where comm->>'f' in ('hello', 'hero', 'heyo') Data Structure: data = {comm: [{f: 'hello'}, {f: 'hero'}]}