Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to require login for homepage in wagtail
I am trying to figure out a way for when someone reaches the website that if they are not authenticated it redirects them to the login screen. I am using WagTail 2.6.2. The home app does not have a views.py to require the class for a login. Any suggestions or documentation out there to do this would be great. -
Object of type Decimal is not JSON serializable error in Django
I am following 'Django 2 by Example' book to create a ecommerce website in Django. But I am getting 'Object of type Decimal is not JSON serializable' when I am trying to save order id in the request.session in the following line. request.session['order_id'] = order.id def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # cart.clear() order_created.delay(order.id) request.session['order_id'] = order.id return redirect(reverse('payment:process')) else: form = OrderCreateForm() return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) -
Django - TypeError: load_stations() missing 1 required positional argument: 'request'?
I'm trying to create dependent dropdowns and when I tried compiling I got this error File "C:\...\operations\urls.py", line 13, in <module> path('ajax/load-stations/', views.load_stations(), name='ajax_load_stations'), TypeError: load_stations() missing 1 required positional argument: 'request' My current code associated with this part is views.py class EnterExitArea(CreateView): template_name = "operations/enter_exit_area.html" form_class = WarehouseForm success_url = reverse_lazy('enter_exit_area') def form_valid(self, form): form.submit_time() return super().form_valid(form) def load_stations(request): work_area_id = request.GET.get('work_area') stations = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') return render(request, 'operations/station_number_dropdown_list_options.html', {'stations': stations}) and my urls is urls.py urlpatterns = [ url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'), path('ajax/load-stations/', views.load_stations(), name='ajax_load_stations'), ] What could be causing this error? -
Django admin, Change inline value before save
I have these inline admin classes: class CompanyEmailInlineFormset(BaseInlineFormSet): pass class CompanyEmailInline(admin.TabularInline): model = CompanyEmail readonly_fields = ('alpha_name',) formset = CompanyEmailInlineFormset The main problem is that my CompanyEmail model has email field and I want to set it to lowercase before saving occurs. Is it possible? -
Dynamic choices for ChoiceFilter depending on the logged in users
I am setting up a bowling score program and want users to select their own choice included in their user group only. But I have a problem when I try to pass 'request' parameter to a function using 'django_filters.ChoiceFilter'. views.py c_filter = TodayScoreFilter(request.GET, request=request, queryset=Score.objects.all) filters.py def date_choice(request): if request is None: return Score.objects.none() for group in request.user.groups.filter(Q(name='mon') | Q(name='wed')): group = group qs = Score.objects.filter(group=group).order_by('-date') date_list=[] for q in qs: date_list.append(q.date) a = np.array(date_list) _, idx = np.unique(a, return_index=True) b = tuple(a[np.sort(idx)]) c = tuple((m,m) for m in b) return c class TodayScoreFilter(django_filters.FilterSet): date = django_filters.ChoiceFilter(choices=date_choice) class Meta: model = Score fields = ['date'] def __init__(self, data=None, *args, **kwargs): if data is not None: choice = date_choice(kwargs['request']) data = data.copy() if len(data) == 0: data['date'] = choice[0][0] super(TodayScoreFilter, self).__init__(data, *args, **kwargs) I expected user can select only the date they involved in. But the error message is as follows, TypeError: date_choice() missing 1 required positional argument: 'request' -
How to combine two differente templates in one common app in django?
I want to create different templates, but both of them share almost the same attributes. For example, both the blog page and the movie page have the model 'Post' that allows users to add new Articles/Movies to the Website. Also, I assume that the 'Movie - Post' model would need different fields than the 'Article - Post' model, but they still share many of them. Someone can help me how to implement that out? -
How to obtain an object ID in formset template code (using django-extra-views)
I'm trying to adopt 'extra-views' as an advanced means of handling formsets, and want to have a link on each row of my formset template to redirect to a relevant object-based page, for which I need the initial value of that object's ID as url parameter. Here's the view: from extra_views import ModelFormSetView from .models import Course class CourseFormSetView(ModelFormSetView): model = Course fields = ['id', 'ceName', 'ceExtName', 'ceDuration'] template_name = 'course_view.html' factory_kwargs = {'extra': 1, 'max_num': None, 'can_order': False, 'can_delete': True} Here's the relevant section of the template: <form method="post"> {% csrf_token %} {% for form in formset %} <p>{{ form.ceName }} {{ form.ceExtName }} {{ form.DELETE }} <a href="{% url 'booksys:coursesetup_view' 1 %}" class="btn btn-info" role="button">Edit</a></p> {% endfor %} {{ formset.management_form }} <input type="submit" value="Submit" /> </form> I've tried {{ form.fields.ceExtName.value }} as url parameter (1). but it does not yield any initial value. Any help much appreciated. -
How to use Django's models in JavaScript
I have an app in Django where 2 news are stored in that data base. I'm using views.py in order to display those news in my html page. Models.py class News(models.Model): news_title = models.CharField(max_length=150) news_body = models.TextField(max_length=1500) Views.py def news(request): news_f = News.objects.all().order_by('-news_id') news_f_html = serializers.serialize("json",News.objects.all()) news_dic= {'news_f':news_f,'ac_tab_n':'ac_tab', 'news_f_html':news_f_html} return render(request, 'news.html',news_dic) I want to display the news' body using html tag but I can't because it's a string. I've been reading and I tried to serialize the news in order to use news_f_html in JavaScript. scripts.js var news = "{{ news_f_html }}"; But this doesn't work. I can't display, for example: console.log(news[1].news_title) //Note that I have 2 news in my db app -
Wagtail CMS send image URL over API request
I am using wagtail headless as a CMS for my front-end application. Everything is working fine so far, but I can not get my images into my front-end application when calling the API. Here is the model I am working with right now, I am using streamfield too: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import StreamField from wagtail.core import blocks from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.images.blocks import ImageChooserBlock as DefaultImageChooserBlock from wagtail.api import APIField class ImageChooserBlock(DefaultImageChooserBlock): def get_api_representation(self, value, context=None): if value: return { 'id': value.id, 'title': value.title, 'large': value.get_rendition('width-1000').attrs_dict, 'thumbnail': value.get_rendition('fill-120x120').attrs_dict, } class HomePage(Page): body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ],) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] api_fields = [ APIField('body'), ] I got the override code for ImageChooserBlock here : Wagtail getting/generating image urls from JSON api or directly This no longer seems to be working, I am still getting a response from API as follows: "title": "now", "body": [ { "type": "image", "value": 1, "id": "f5714257-bf5d-469b-9b4f-875212ec8d8d" } I need the URL so I can display them in my application. Any other ideas? I can't find any info about this anywhere else. -
Jinja2 Extension in Django: access args inside the function called by CallBlock
I'm building a Jinja extension for Django. It looks something like this: class FieldObjectExtension(jinja2.ext.Extension): """A custom extension to render different objects fields.""" """The tags this extension will parse.""" tags = {'fieldobj'} def parse(self, parser): lineno = next(parser.stream).lineno args = [parser.parse_expression()] # If there is a comma, the user provided a field type. If not use # None as second parameter. if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(jinja2.nodes.Const(None)) call = self.call_method('_create_field', args) # <== I want to access this args argument ins return jinja2.nodes.CallBlock(call, [], [], '').set_lineno(lineno) def _create_field(self, name, caller): """Gets the field type and creates the HTML tag from it.""" if args == "text": # <== Here I where I want to have access to args html = f'<input type="text">' elif args == "textArea": html = f'<textarea></textarea>' return html I want to access the parameters stored in args from within the _create_field function. For example, if I write {% fieldobj text %}, the _create_field function would receive the string text. I've been trying several ways, but getting all sorts of errors. -
Submit form automatically that is present inside a javascript
I have below code that I want to submit automatically on page reload. This is giving showing me a button "pay now" but I want to click that button automatically. I think that button is part of src="https://checkout.razorpay.com/v1/checkout.js". Can someone help me with this? Thanks! <div class="container" name="payment_submit"> <form action="{% url 'razorpay_response' %}" method="POST"> {% csrf_token %} <!-- Note that the amount is in paise = 50 INR --> <input type="hidden" name="creator" value="{{creator}}" /> <input type="hidden" name="sub_value" value="{{sub_value}}" /> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="{{rzr_id}}" data-subscription_id="{{sub_id}}" data-name = "My Billing Label" data-description ="Auth txn for {{sub_id}}" ></script> <input type="hidden" value="Hidden Element" name="hidden"> </form> </div> -
How to display data from a python script in Django?
I've created a program that scrape data and store it in a JSON format. Usually, when I want to display data in Python I use this code: product_list = daily_deals() for i in range(len(product_list)): print("Name: ", product_list[i]["name"]) print("Price: ", product_list[i]["price"]) print("Old Price: ", product_list[i]["old_price"]) print("Link: ", product_list[i]["link"]) print("Image: ", product_list[i]["img"]) print() When I wanted to do the same thing in Django, I added the script to the index view (because data will be displayed in the Home page) views.py def index(request): template = loader.get_template("search/index.html") daily_deals_list = daily_deals.deal_scraper return HttpResponse(template.render({}, request), daily_deals_list) And then in my index.html: {% for product in daily_deals_list %} <div class="deal-item"> <a class="deal-product-link" href="{{ product.link }}" target="_blank"> <div class="deal-img-block"> <img class="deal-img" src="{{ product.img }}"> </div> <p class="deal-product-name text-center">{{ product.name }}</p> <p class="deal-product-price text-center" style="color: orange;"> <span class="deal-old-price" style="text-decoration:line-through;">{{ product.old_price }}</span>&emsp; {{ product.price }}</p> </a> </div> {% endfor %} -
Can we have nested HTML form in Django framework?
<form action="#" method ="POST> <input …> <input …> <form action ="#" method="POST> <input …> <input …> <button type = "submit" name = "inner">.. </form> <button type = "submit" name = "outer">.. </form> Can we use such nested form to submit to a single function in views.py ? -
Need to change form in django
I want to change form input. I want to change look for each element. Every widget should have personal class or id, so something like this will be not a solving: <form action="/contact/" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Send message" /></p> </form> Can I do it not using view-export? -
How to write a django-like Class ("Models") initialization
I have an object called a "TemporaryPriceReduction" that tells me information on a product that undergoes a sale. The class looks something like this: class TPR: def __init__(self, product_id, territory): self.product_id = product_id self.territory = territory In django models, it allows you to define things outside an init (at least in the specific model that inherits the models.Model base class: class TPR(models.Model): product_id = ... territory = ... How could I build something like an abstract base class so that I can define things outside the init (like in django) rather than having to write the init? -
Why the images of my media library is not showing in my home page
enter image description here I included the images in my database and store the images in the media directory. but when i access my data from my database then the other thing go well but my images is not showing. please help me. This is my index.html file '''{% block body %} {% load static %} <div class="container"> <h1>Men Fashion</h1> <div id="demo" class="carousel slide my-3" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#demo" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#demo" data-slide-to="{{i}}" ></li> {% endfor %} </ul> <!--Slideshow starts here --> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> {% load static %} <img src='/media/{{product.0.image}}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{product.0.product_name}}</h5> <p class="card-text">{{product.0.desc}}</p> <a href="#" class="btn btn-primary">Add to Cart</a> </div> </div> </div> {% for i in product|slice:"1:"%} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{i.product_name}}</h5> <p class="card-text">{{i.desc}}</p> <a href="#" class="btn btn-primary">Add To Cart</a> </div> </div> </div> {% if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last %} </div><div class="carousel-item"> {% endif %} {% endfor %} </div> </div> </div> <!-- left and right controls for the slide --> <a class="carousel-control-prev" href="#demo" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" … -
How can I make my comments form work in django?
I'm trying to call my comment form from the blog page, but it just keeps refreshing the particular blog page. Here's my code; models.py class BlogPost(models.Model): # id = models.IntegerField() user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = BlogPostManager() class Meta: ordering = ['-publish_date', '-updated', '-timestamp'] def __str__(self): return self.title def get_absolute_url(self): return f"/blog/{self.slug}" def get_edit_url(self): return f"{self.get_absolute_url()}/edit" def get_delete_url(self): return f"{self.get_absolute_url()}/delete" class Comment(models.Model): comment_cont = models.TextField(max_length=200, verbose_name='Comment content') user_name = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) comment_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments') comment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.comment_cont def get_absolute_url(self): return f"{BlogPost.get_absolute_url()}" def get_add_url(self): return f"{self.get_absolute_url()}/addc" views.py def add_comment_to_post(request, slug): post = get_object_or_404(BlogPost, slug=slug) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog_post_detail_view', slug=post.slug) else: form = CommentForm() template_name = 'formc.html' context = {"title": f"New comment on {post.title}", "form": form} return render(request, template_name, context) urls.py path('<str:slug>/addc', add_comment_to_post), formc.html <form method='POST' action='.' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Comment</button> </form> button in home.html <a class="btn btn-primary" href="{{ comments.get_add_url }}">Add Comment...</a> I know the href … -
ModuleNotFound error with django + gunicorn
I am trying to deploy a django project using this tutorial as a guide. I am getting a "ModuleNotFoundError". What am I dong wrong? (see attached) I don't know if its worth mentioning that when I run- "gunicorn portal.wsgi:application --bind 0.0.0.0:8000" or "gunicorn -w 2 -b 0.0.0.0:8000 --chdir /home/CleanBoy portal.wsgi" it works fine. ("gunicorn -w 2 -b 0.0.0.0:8000 --chdir /home/CleanBoy portal.wsgi" seems to respond faster) but when I call the batch file (./gunicorn_start.bash) in step 6. (from jee-appy.blogspot.com/) I get the error below. Please help. -
How to downgrade sqlite3 that comes with Python and Django
So I am stuck in this problem: Django - No such table: main.auth_user__old I can't upgrade Django because many other applications are connected to it using version 2.1. The only approach is to edit the sqlite3. Currently, I am using SQLITE3 3.26.0 and I want to downgrade to 2.5.1. How can I do this? -
django return variable back to user
I'm trying to add a tool to my site that hashes a serial number, and as such I don't require a model for this particular part of the site. What I wanted to do is use if statements in the template to remove the form fields and submit button and display the hash on the same page, however, I can't figure out how to get my result back to the template. The form I have created is the most basic with just two fields. here is my view: def voice_search_view(request): form = VoiceSearchForm() if request.method == 'POST': form = VoiceSearchForm(request.POST) if form.is_valid(): hw_number = form.cleaned_data['hw_number'] ca_serial = form.cleaned_data['ca_serial'] if len(ca_serial) == 16: prehash = hw_number + ca_serial[5:-1] + 'cc_voice' territory = 'DE' elif len(ca_serial) == 11: prehash = hw_number + ca_serial[:-1] + 'cc_voice' territory = 'UKIT' print(hw_number) print(ca_serial) print(prehash) sha_sig = hashlib.sha256(prehash.encode()).hexdigest() print(sha_sig) return redirect('/voice_search/') return render(request, 'voice_search.html', {'form': form}) how can I return the sha_sig back to the user, in an ideal world, I would just add it to the context, but that doesn't seem to be possible. Bearing in mind that I am not even using any css for this, it's a very quick temporary tool. What would … -
Enable subsite on Apache2 with Django
so I have django installed as my main directory django.conf (in Apache2): djanAlias /robots.txt /home/django/NAME/static/robots.txt Alias /favicon.ico /home/django/NAME/static/favicon.ico Alias /media/ /home/django/NAME/media/ Alias /static/ /home/django/NAME/static/ <Directory /home/django/NAME/static> Require all granted </Directory> <Directory /home/django/NAME/media> Require all granted </Directory> WSGIScriptAlias / /home/django/NAME/NAME/wsgi.py WSGIPythonHome /home/django/NAME/venv WSGIPythonPath /home/django/NAME <Directory /home/django/NAME/NAME> <Files wsgi.py> Require all granted </Files> </Directory> Now I want to enable roundcube as mail.NAME.net this is my conf: <VirtualHost *:80> ServerName mail.NAME.net ServerAdmin admin@NAME.net DocumentRoot /var/www/html/roundcube ErrorLog ${APACHE_LOG_DIR}/roundcube_error.log CustomLog ${APACHE_LOG_DIR}/roundcube_access.log combined <Directory /var/www/html/roundcube> Options -Indexes AllowOverride All Order allow,deny allow from all </Directory> RewriteEngine on RewriteCond %{SERVER_NAME} =mail.keyinator.net RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> When disabling Django everything works fine. When enabling it I get a 400 Bad Request error on mail.keyinator.net So my question is: How can I make my subsite mail.keyinator.net available whilst using django? -
How do I display a queryset based on a category linked to a slug that is requested?
I am trying to display querysets linked to a certain category, based on the webpage slug requested. I am in school and trying to learn the Django framework. Here is the view that I have tried: class ProductCategoryListView(ListView): template_name = 'products/product_list.html' def get_queryset(request, *args, **kwargs): if Product.category == ProductCategory.title: instance = ProductCategory.objects.get(title=instance) post = Product.objects.filter(category=instance) return post And here are my models: class ProductCategory(models.Model): title = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.PROTECT) class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(ProductCategory, null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) image = models.ImageField(upload_to='products/', null=True, blank=True) This view loaded the webpage, but did not render any queries. -
Issues when define a Django Foreign Key from CharField DataType
i'm new in Django and I am using it for create a small APIrest, the situation is that when defining the application models I got this class Localities(models.Model): id = models.BigAutoField(primary_key=True) field_id = models.CharField(unique=True, max_length=50,db_column='field_id') class Meta: managed = False db_table = 'localities' class Stratigraphy(models.Model): id = models.BigAutoField(primary_key=True) locality = models.ForeignKey(Localities, models.DO_NOTHING, blank=True, null=True, related_name='locality_id') class Meta: managed = False db_table = 'stratigraphy' The model Stratigraphy is related with the model Localities to the chardfield field_id when creating the serializer to create the json with the data i got this class BedSerializer(ModelSerializer): class Meta: model = Stratigraphy fields = '__all__' depth = 1 when I try the api with postman it shows me the following enter image description here but if I remove the depth attribute it shows me the following. class BedSerializer(ModelSerializer): class Meta: model = Stratigraphy fields = ('id','locality') enter image description here What am I doing wrong? -
In Django, how do I return a generated dynamically named document as a download?
I have created a page that takes user input via form fields and then takes that data and generates a document from the information. It saves it to a specified directory and uses form data to create the file name. I am trying to then have it redirect to prompt a download of that file as well. The function inside the page view that indicates the directory and creates the filename is 'makefileandpath()'. I then create a variable 'docname' and call the function. It works perfectly. My problem is then being able to make this variable work with returning the document as a download. I've tried to create different functions internally to handle this as well as tried to create another view and use it as an endpoint (all which can be seen below), but it won't allow me to call the variable name and the document could be called anything. I'm not sure how to solve this problem and I have been at this for almost a week now. Here is the code for my view: views.py import os from django.shortcuts import render from django.conf import settings from django.http import HttpResponse, Http404, FileResponse from docx import Document import mimetypes … -
Concurency celery django bulk create or update
I have a competition problem with django, I have a celery task that updates the number of users in a table. Since there are a lot of lines to update, I use a bulk update, and to avoid creating unnecessary lines, I use a bulk create. all_statistic_user = StatisticsCountriesUser.objects.filter(user__in=all_branch_user,countries=user.country) if all_statistic_user: all_statistic_user.update(total_users=F('total_users') +1) all_statistic_user = StatisticsCountriesUser.objects.exclude(user__in=all_branch_user,countries=user.country) if all_statistic_user: all_statistic_user = [StatisticsCountriesUser(user_id=user.id,countries=user.country) for user in all_statistic_user ] StatisticsCountriesUser.objects.bulk_create(all_statistic_user) else: all_statistic_user = [StatisticsCountriesUser(user_id=user.id, countries=user.country) for user in all_branch_user] StatisticsCountriesUser.objects.bulk_create(all_statistic_user) The problem is that if the task is executed asynchronously, if the tasks are executed at the same time the first task creates the user list, then the second task also retrieves the user list, the first creates or updates the users, but the second task the list no longer has the right information to update. the solution I thought was to put the tasks in a synchronous list and not asynchronously is this possible? Thank you in advance