Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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'}]} -
Django 3: ValidationError is not displayed
I recently started learning Django framework and had some problems with variable validation. When I try to output field.errors variable in html file there is no output, although when I pass error variable from create method, it outputs "errors" list (i.e. clean_number method is supposed to work) and when I fix them, list gets smaller (i.e. clean_number method does not work). Please tell me what I am doing wrong. Thanks in advance. File create.html <!doctype html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport> content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Adding a train to the list</title> <link href="https://getbootstrap.com/docs/5.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> <style> .sidenav { height: 100%; width: 267px; position: fixed; z-index: 1; top: 0; left: 0; background-color: #f2f2f2; overflow-x: hidden; padding-top: 50px; } .container { max-width: 900px; } </style> </head> <body> <body class="bg-light"> <header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow"> <a class="navbar-brand col-md-3 col-lg-2 me-0 px-3 fs-6" href="/">Home page</a> <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <input class="form-control form-control-dark w-100 rounded-0 border-0" type="text" placeholder="Search" aria-label="Search"> <div class="navbar-nav"> <div class="nav-item text-nowrap"> <a class="nav-link px-3"></a> </div> </div> </header> <div class="container"> <main> <div class="row g-5"> <div class="py-5 text-center"> <h2>Add a train</h2> <p class="lead">On … -
Django append to FileField
Is there any way to append directly to a FileField in django? Doing something like this: class ChunkedUpload(models.Model): id = models.CharField(max_length=128) data = models.FileField(upload_to='chunked_uploads/') def append_chunk(self, chunk, create): if create: self.data.save(self.id, ContentFile(chunk.encode())) else: self.data.append(ContentFile(chunk.encode()) I'm working on an existing solution that sent data by chunks (base64 encoded string) in TextField. But some data are now too big to be handled in a TextField (250++ Mb). I can't change the other parts of the application, so I'm trying to find a way to handle this situation. -
Increment value in loop in django
{% for match in response %} <tr> <td>{{ match.i.position }}</td> <td>{{ match.i.team.name }}</td> <td>{{ match.i.games.played }}</td> <td>{{ match.i.games.win.total }}</td> <td>{{ match.i.games.lose.total }}</td> <td>{{ match.i.games.win.percentage }}</td> </tr> </tr> {% endfor %} I am trying to increment the value of 'i' within a for loop in my standings.html django project. I am having trouble doing this as django doesnt seem to like me trying to increment values. Is there any way to fix this? I would like the value to start at 0 and increase by 1 in each iteration of the loop. -
Get URL Works Fine in PostMan But Nothing Shows in Browser
I am creating a E commerce site in Django Everything is working fine but I am unable to display my QuerySet result in Django View My Cart Function looks like this def cart(request): if request.method == 'POST': return redirect('index') else: if request.method == 'GET': # Recieve local storage product in post_id varibale post_id = request.GET.get('get_cart') cat_product = Product.objects.filter(id=.11) if post_id is not None: # Fomrat and remove { } and " from post_id string post_id = post_id.replace('{','') post_id = post_id.replace('}','') post_id = post_id.replace('"','') print("The Id is", post_id ) # Find ':' in string and get the value of id in cart_prod_index index =0 while index < len(post_id): index = post_id.find(':', index) if index == -1: break local_storage_prod_id = post_id[index-1] # '|' operator is used to append the queryset result cat_product = cat_product | Product.objects.filter(id=local_storage_prod_id) index+=2 print("Below Index" ,cat_product) else: print("Below else" ,cat_product) # return render(request, "cart.html" ,{"x":cat_product,}) print(cat_product) return render(request, "cart.html" ,{"cat_product":cat_product}) I have following Product in cat_product varibale <QuerySet [<Product: Men Black T shirt>, <Product: White T Shirt>, <Product: Black Lady T Shirt>, <Product: Tomato>, <Product: White Ladies T Shirt>]> When I use postman using Get Url i got the desired result But in my browser it shows nothing … -
I'm not able to connect proxy host database in Django
after running python manage.py runserver Got the Error port 5432 failed: FATAL: Feature not supported: RDS Proxy currently doesn’t support command-line options. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DATABASE_NAME', 'USER': 'DATABASE_USER' 'PASSWORD': 'DATABASE_PASSWORD' 'HOST': 'PROXY_HOST', 'PORT': '5432', 'OPTIONS': { 'options': f"-c search_path={DATABASE_SCHEMA}" }, } } After commented OPTIONS -- {DATABASE_SCHEMA} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DATABASE_NAME', 'USER': 'DATABASE_USER' 'PASSWORD': 'DATABASE_PASSWORD' 'HOST': 'PROXY_HOST', 'PORT': '5432', # 'OPTIONS': { # 'options': f"-c search_path={DATABASE_SCHEMA}" # }, } } so finally getting migrations error because it's pointing to the database not particular schema You have 178 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): **address, analytics, etc...** Run 'python manage.py migrate' to apply them. February 09, 2023 - 15:42:20 Django version 3.2.9, using settings 'MoreProjectAPI.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. it's not connected my schema could any one please suggest how can i fix this issue in root level not in every model level. -
Hide django model
I would need help, I'm on a django project and I have a button with a button type submit and when I click on it since I had made the model mandatory, it puts me "please fill in this field" and I so can't interact with the button How to hide or remove it only from the page? I try to put if but no idea -
UUID from django database to Javascript that changes link based on current page
I made a wordlegolf game that tracks your scores and one user can have multiple scoreboards. I am trying to have arrows that lets you rotate through your scoreboards. image of arrows So I need to be able to track which scoreboard the user is currently on and rotate through each scoreboard I've tried a bunch of things and was able to get it to work but now that I have implemented UUIDs I am getting a bunch of errors with my javascript. I tried adding this UUIDEncoder class which I saw online but that hasnt helped. views.py newlink = [] links = list(CreatedScoreboardUnique.objects.filter(players=request.user)) for link in links: newlink.append(link.pk) newlink = json.dumps(newlink, cls=UUIDEncoder) class UUIDEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, UUID): # if the obj is uuid, we simply return the value of uuid return obj.hex return json.JSONEncoder.default(self, obj) html <svg width="37" height="37" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" onclick="nextScoreboard()"> <path d="M15.0378 6.34317L13.6269 7.76069L16.8972 11.0157L3.29211 11.0293L3.29413 13.0293L16.8619 13.0157L13.6467 16.2459L15.0643 17.6568L20.7079 11.9868L15.0378 6.34317Z" fill="currentColor"/> </svg> javascript function nextScoreboard(){ console.log('next clicked') var links = JSON.parse("{{links|safe}}") var currId = "{{scoreboard.id}}" var nextlink = false for(i = 0; i < links.length; i++){ if(links[i] == currId){ window.location.href = "http://127.0.0.1:8000/scoreboard/" } } } This is the …