Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ManyToMany field constraints in Django
This is a general database question that is not specific to Django. Since I'm using Django, I am asking it in this context. Suppose I have three models: class ModelA(models.Model) name = models.CharField(max_length=255) class ModelB(models.Model) a = models.ForeignKey(ModelA, on_delete=models.CASCADE) class ModelC(models.Model) a = models.ForeignKey(ModelA, on_delete=models.CASCADE) bs = models.ManyToManyField(ModelB, blank=True) I would like ModelC to have a link to many ModelBs. I would like there to be a constraint that only allows ModelC to have a ModelB if they share a common ModelA. Is there a way to architect this properly at the database level or should this be done logically in other parts of the system? -
Django: Object.objects.get returns me `Jquery Datepicker widget`
urls.py: from django.urls import path from . import views urlpatterns = [ path('<int:pk>/', views.show_object, name='show-object') views.py: def show_object(request, pk): testt = 2 objj = Object.objects.get(id=pk) pdb.set_trace() So I found pdb to debug with, but when I open console in debug mode (via pdb) and type objj it returns me <Object: Jquery Datepicker widget, create new date and getTime method?> if I type testt it returns me 2, I'm confused. -
class Meta VS form fields in Django
I'm learning Django forms from this example. When I run my server I get django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited (solved here). Using class Meta everything works. Explain pliese could I use these both aproaches with Django==2.2.6 and pros and cons of them. -
How to pass custom url parameter for each Search button of raw_id_fields in django-admin
I have models class Product(models.Model): number = models.CharField(_('OEM/Part number'), max_length=128,) .... class Orderitem(models.Model): searchstring = models.CharField(_('OEM/Part number'), max_length=128, blank=True, default='',) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE,) .... class Order(models.Model): .... And admins @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('number', .....) search_fields = ('number',) class OrderitemInline(admin.TabularInline): model = Orderitem fields = ('searchstring', 'product', .....) readonly_fields = ('searchstring',) raw_id_fields = ["product"] def get_formset(self, request, obj=None, **kwargs): form = super().get_formset(request, obj, **kwargs) field = form.form.base_fields['product'].widget.rel.limit_choices_to = {'q': '11111111'} return form @admin.register(Orderdiscuss) class OrderdiscussAdmin(admin.ModelAdmin): list_display = (....) inlines = [ OrderdiscussItemInline, ] ..... How can I replace "11111111" from field = form.form.base_fields['product'].widget.rel.limit_choices_to = {'q': '11111111'} to each Orderitem's "searchstring" field, to have raw_id_fields urls like: http://localhost:8003/admincp/catalog/product/?q=searchstring1 http://localhost:8003/admincp/catalog/product/?q=searchstring2 and other, so I can view only related records in Popup window? Thanks a lot! -
How do I alter my API request based on a field from the user?
What I would like is an API request that gives me data based on a field from the User. i.e. If the User is premium, give all of the data, otherwise, give a subset of that data. This is easy enough, as shown in the DRF filtering documentation: class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ This view should return a list of all the purchases for the currently authenticated user. """ user = self.request.user return Purchase.objects.filter(purchaser=user) The problem: I currently have it set up so anyone trying to access the API needs a Token. But, I'd like a 'Guest' user (someone who is not logged in) to still be able to see some data from my API. I am using these Django Rest Framework settings: REST_FRAMEWORK = { "TEST_REQUEST_DEFAULT_FORMAT": "json", 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } -
How to link memo to all users in group
I have a simple model called Memos that looks like this: class Memo(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_time = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Now if I want to create a table so that I have a sender and receiver I could change author to sender and then add a receiver with a foreignkey to link it to the receiving party. Problem is that I have "groups" of employees with specific permissions (using Django groups and permissions) in which each user of the group needs to receive these memos separately and mark as read. To mark as read I simply planned on adding a models.BooleanField(default=False) then switch it to True when user visits that page. So my question is how to allow group(s) to be selected as a receiver then each user in the receiver group have their own Memo assigned to them so that they can mark as read/unread? -
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?