Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating endpoints inside an endpoint in fastapi
suppose there as an audio server, you can upload Songs, podcasts, or Audiobook. So in the create endpoint i have created 4 endpoints, so i have put an condition if the audio_type is a song, return all audio of that type but unfortunately this return null @app.get('/audio/{audio_type}') def show_all(audio_type): if audio_type == "Songs": @app.get("audio/song") def all(db: Session = Depends(database.get_db)): songs = db.query(models.Song).all() print("songs = ", songs) return songs elif audio_type == "podcast": @app.get('audio/podcast') def all(db: Session = Depends(database.get_db)): podcast = db.query(models.Podcast).all() return podcast elif audio_type == "audiobook": @app.get('audio/audiobook') def all(db: Session = Depends(database.get_db)): audiobook = db.query(models.Audiobook).all() return audiobook else: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f' {audio_type} - audio type is not valid') -
Django can't upload file
I'm doing a django app with a form using image file upload. I have a default image in case user doesnt choose an image. But when I save the form, my image isn't saved in my files. Any idea ? Here's my code : First my views.py class AnimalCreateView(generic.CreateView): model = Animal form_class = AnimalForm template_name = 'myApp/animal_create.html' success_url = reverse_lazy('animal:index') Then my models.py class Animal(models.Model): name= models.CharField() animal_photo= models.ImageField(upload_to="images/",default="images/noPhoto.svg", null=False, blank=True) def __str__(self): return f'{self.name}' When I save my file and then check my html or django admin page, all the rows of animal_photo are using the default file... -
Can I host Django REST and React in the same cpanel account?
I have developed a Django REST API with a react frontend in separate repositories. I tried to publish them in my cpanel account (godaddy) but once I upload the React after having configured the API, then my API won't work, even though I put a subdomain (api.domain.com) for the it. I get a 500 internal server error :(( . Is there any way of solving that? -
Django AttributeError: 'QuerySet' object has no attribute 'fitler'. Trying to filter the manytomany relation objects [closed]
I try to filter manytomany queryset objects. I have 2 models: class Product(models.Model): environment = models.CharField(choices=PRODUCT_ENVIRONMENTS, max_length=25) ... class TelegramUser(models.Model): last_query_products = models.ManyToManyField( Product, related_name='users_from_query', blank=True ) ... Filtering def environment_response(query): # TELEGRAMUSER OBJECT user = get_user(query.message.chat.username) filtered_products_by_env = user.last_query_products.all().fitler(environment=query.data) user.last_query_products.clear() user.last_query_products.add(*filtered_products_by_env) Here's I just get saved query products and filter them by the environment parameter. Error: Traceback (most recent call last): ... File "/Users/kalik/Desktop/agrochemistry-telegram-bot/agrochemistry/calculator/bot/bot.py", line 106, in environment_response filtered_products_by_env = user.last_query_products.all().fitler(environment=query.data) AttributeError: 'QuerySet' object has no attribute 'fitler' -
Create 4 dependant dropdown django with only 1 model
Right now i am able to filter 4 dependent dropdown, but the problem is i write script onchange for each dropdown seperately, and i am unable to get variables from other dropdown and pass it back to views to filter my tables. My 4 dropdowns are Thickness,Grade,Weight,Color All of these fields are in one single model I am trying to chain these 4 dropdowns so that: Grade filter(thickness = thickness) Weight filter(thickness = thickness,Grade = Grade) Color filter(thickness = thickness,Grade = Grade,Weight = Weight) Right now i'm only able to do this: Grade filter(thickness = thickness) Weight filter(Grade = Grade) Color filter(Weight = Weight) views.py thickness_id = request.GET.get('thickness') grade_id = request.GET.get('grade') weight_id = request.GET.get('weight') print(thickness_id) print(grade_id) grades = FormulasTable.objects.filter(thickness=thickness_id).values('grade').distinct() weights = FormulasTable.objects.filter(grade=grade_id).values('Weight').distinct() colors = FormulasTable.objects.filter(Weight=weight_id).values('Color').distinct() return render(request,'first_app/formula_options.html', {'grades': grades,'weights':weights,'colors':colors}) models.py class FormulasTable(models.Model): thickness = models.IntegerField() grade = models.CharField(max_length=50) Weight = models.IntegerField() Color = models.TextField(max_length=50) def __str__(self): return str(self.thickness) +" "+ str(self.grade) +" "+ str(self.Weight) +" "+ self.Color jquery <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#thickness_id").change(function () { var url = $("#formula_pageForm").attr("data-grades-url"); var thicknessId = $(this).val(); $.ajax({ url: url, data: { 'thickness': thicknessId }, success: function (data) { $("#grade_id").html(data); } }); console.log(thicknessId) } ); </script> <script> $("#grade_id").change(function () { var url = $("#formula_pageForm").attr("data-grades-url"); var … -
Customizing size of django admin portal text fields
How do I make a text field in the django admin portal bigger? Right now its one line, I want to make it about 5, so I can type in a small paragraph and see the whole thing. -
When I click on the save button it will check that data on the database before saving it in Django?
When I click on the save button it will check that data on the database before saving it in Django. search data at database before insert in Django administration. I don't want to save the same data that already save in the database. like this on: Here Home save to double. But I want that if home already save then the second time I try to Save the same name it will not save. How can I code it? models.py class Brand(models.Model): brand_id = models.id = models.AutoField(primary_key=True, auto_created=True) brand_name = models.CharField(max_length=50) brand_date = models.DateTimeField(auto_now_add=True, null=False) -
Django is not migrating migrations that exist
when first I did the makemigrations command, django did it sucessfully. But after migrate it says no migrations to apply. Than I tried to do delete migrations folder than make and migrate delete migrations and pycache and same thing migrate --fake migrate -f -
how to make the page redirects to the same page after the event occured
I am trying to make a upvote and downvote functionality on my website. however there is a particular behaviour that i don't like which is that whenever a user clicks the button, he should not be redirect to another page but should remain on the same page. What happens after clicking the upvote button is that it goes to the url http://localhost:8001/upvote/2/ which i don't want. I want it to remain on the same page which is http://localhost:8001/view-supplier/ models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) def get_email(self): return self.email views.py @login_required def upvote(request, pk): supplier_vote = get_object_or_404(User, id=pk) supplier_vote.upvotes += 1 supplier_vote.save() upvote_count = supplier_vote.upvotes context = {"supplier_vote":supplier_vote, "upvote_count":upvote_count} return render(request, "core/view-suppliers.html", context) @login_required def downvote(request, pk): supplier_vote = get_object_or_404(User, id=pk) supplier_vote.downvotes -= 1 supplier_vote.save() downvote_count = supplier_vote.downvotes context = {"supplier_vote":supplier_vote, "downvote_count":downvote_count} return render(request, "core/view-suppliers.html", context) urls.py from django.urls import path from . import views urlpatterns = [ path('upvote/<int:pk>/', views.upvote, name='upvote'), path('downvote/<int:pk>/', views.downvote, name='downvote'), ] view-supplier.html <table class="table table-borderless table-data3"> <thead> <tr> <th>No</th> <th>Country</th> <th>Votes</th> </tr> </thead> <tbody> {% for supplier in suppliers %} … -
How can pass primary key to url Django
I have basically 3 issues I am trying to pass the primary key of vendor in url after creating it, but when i go the vendor page it shows the error ' Reverse for 'vendorCategory' with arguments '('',)' not found. 1 pattern(s) tried: ['vendorCategory/(?P<vendor_id>[0-9]+)/$'] ' In Vendor Category when i am trying to store multiple products against the specific vendor it show the error 'Field id int but You got ['12', '11'] ' in Vendor Category template when i select any category it just show the last category which i added View.py class Vendor(TemplateView): template_name = 'purchase/vendor.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, vendor_id): try: data = self.request.POST.get vendor = VendorModel( name=data('name'), email=data('email'), Contact_No=data('Contact_No'), address=data('address') ) vendor.save() vendor.objects.get(id=vendor_id) return redirect('vendorCategory') except Exception as e: return HttpResponse('failed{}'.format(e)) class Vendor_Category(TemplateView): template_name = 'purchase/vendorCategory.html' def get(self, request, vendor_id=None, *args, **kwargs): categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') products = ProductModel.objects.filter(category_id=categoryId) vendor= VendorModel.objects.get(id=vendor_id) args = {'categories': categories, 'products': products, 'selectedCategory': categoryId, 'vendor': vendor} return render(request, self.template_name, args) def post(self, request): categoryobj = self.request.GET.get('SelectCategory') productobj = self.request.POST.getlist('ProductSelect') try: vendor = VendorCategory( vendor_id=self.request.vendor_id, category_id=categoryobj, product_id=productobj ) vendor.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Urls.py urlpatterns = [ path('vendorCategory/<int:vendor_id>/', Vendor_Category.as_view(), name='vendorCategory') … -
How to use const values from JavaScript as an argument of Django Custom template tags and filters?
If I have custom filters and write {% load file_name %} into index.html, How to write: <script> const x = 10; const = "{{ obj|function:x }}"; </script> -
Django perform CRUD function in Pop-Up form without reloading the page
I'm currently working(Practicing) on a task To-Do App where I want to perform CRUD functionality in Pop-Up(Modal) form. As I want to perform many CRUD functions I don't want to reload the page every time I do some actions. Image-1 is the overview of the application. A todo item has an update option. Once it was clicked update todo Pop-up form(modal) displayed. Image-2 is the update todo pop-up form(modal) Here I can add a task that will be displayed under its corresponding todo item. Also, I want to update the task item via another pop-up form. The problem I'm facing was If I do some action on any of the pop-up forms the page is getting reloaded. So, that it is redirecting to the home page. models.py from django.db import models from django.conf import settings class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): heading = models.CharField(max_length=100) todo = models.ForeignKey( Todo, on_delete=models.CASCADE, related_name='tasks') date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.heading views.py from django.shortcuts import render, redirect from django.http import Http404, HttpResponse from django.utils import timezone from django.contrib.auth import login, logout … -
Use tmp table to run multiple django queries from a postgres function
I have two versions of a recursive psql function that both select from the same table but return different results. function a (simplified for example): create or replace function public.all_link_traversal(source_ids bigint[], depth_count integer) returns table (id bigint) begin if depth_count > 0 then return query select id from service_item_links where child_service_item_id = any(source_ids) union all select id from all_link_traversal( select distinct parent_service_item_id from service_item_links where child_service_item_id = any(source_ids) else return query select id from service_item_links where child_service_item_id = any(source_ids) function b does a very similar traversal over service_item_links table, but returns a distinct list of child_service_item_ids. In Django, I call both functions separately (but within the same rest call) like so: service_item_links_raw = ServiceItemLinks.objects.filter( id__in=RawSQL(f"select id from {function_query_a}", params=query_params) ) child_service_item_ids = ServiceItems.objects.filter( id__in=RawSQL(f"select id from {function_query_b}", params=query_params) ) return child_service_item_ids.values_list('id', flat=True), service_item_links_raw.values("parent_service_item_id", "child_service_item_id", "link_type", "action_date", "action_key") Due to having to traverse the tree twice, performance with this query has been slow. I'm looking at a solution of creating a tmp table, then having both of these functions run against the tmp table, then deleting it but I'm unsure of how postgres can return two sets of results, or how Django can interact with the tmp table and run both … -
Django forms custom field Left Outer Join
I have a form where I add CUSTOM FIELD checkbox miltiple. The data is simply loaded like this widget = forms.CheckboxSelectMultiple, queryset = Product.objects.all (), required = False, ) This is a good solution when I create a new instance of the Component model. In the case of editing, however, it is a problem because some of the checkboxes can be filled. So I need to change the queryset for this field a little. I wanted to do it like prod = Product.objects.annotate (dupa = FilteredRelation ('product', condition = Q (product__component = 120))). Values ('short_name', 'name', 'dupa__component'), but it gets error django.db.utils.ProgrammingError: missing FROM-clause entry for table" t7 LINE 1: ... a ON ("epm_product". "Id" = ass. "Product_id" AND (T7. "Comp ...". Query returns : SELECT "epm_product "." Short_name "," epm_product ". "name", "epm_productitem_component". "component_id" FROM "epm_product" LEFT OUTER JOIN "epm_productitem" dupa ON ("epm_product". "id" = dupa. "product_id" AND (T5. "component_id" = 120)) LEFT OUTER JOIN "epm_productitem_component" ON (ass. "Id" = "epm_productitem_component". "Productitem_id") To test the data and how it is presented, I used the usual SQL query: "select pr.name, pr.short_name , (select count (*) from epm_productitem pi left join epm_productitem_component pic on pic.productitem_id = pi.id where pic.component_id = 120 … -
How to assign model fields to a custom variable in the view, and use it in context to pass to the template?
so I have a model in models.py, and it has a few fields. Next, I make a form in forms.py to make a creative form. Then I import that form from forms.py into views.py. In the views.py, I make the create view, with the creat form. But here's the problem. In the views.py, I have the model field space. now I want to do something with that field. I assign a custom variable to this space field and pass it in the context. But it gives an error called local variable not defined. models.py class NewJax(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=140) space = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_created'] verbose_name_plural = "New Jax" def __str__(self): return str(self.title) forms.py class CreateNewJaxForm(forms.ModelForm): class Meta: model = NewJax fields = ('title', 'description', 'space') widgets = { "title": forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'name your jax' } ), 'description': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'add a brief description for jax', 'rows': 4, } ), 'space': forms.Textarea( attrs={ 'class': 'form-control', } ) } views.py def create_new_jax(request): if request.user.username == "Assasinator": logout(request) return redirect('banned_user') if request.method == "POST": form = CreateNewJaxForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') … -
for < slides in python DJango templating
for x in range(1,slides): do something i want to write something like this in Django templating how's can I achieve that i searched a lot in google but could not find anything helpful kindly help me out -
How to allow only users associated with certain permissions to access certain urls in Django?
I am trying to figure out how to allow certain users who have a value: ifAdmin=True the ability to edit a project page. That being said, I have a model called uProjects that associates a user and a project with a uProjects, and I am currently trying to use the @wraps function, but would welcome a different approach, or a correction on my code because I am returned the HttpResponseRedirect when I am logged in with a user who has ifAdmin=True and I try to edit a project associated with the uProjects for that user. Here is my code: model: class uProjects(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) ifAccepted = models.BooleanField(null = True, blank=False, default=False) #ifLeader = models.BooleanField(null = False, blank=False) ifAdmin = models.BooleanField(null = True, blank=False, default=False) title = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.user.username + ',' + self.project.name views.py def admin_check(function): @wraps(function) def wrap(request, *args, **kwargs): user = request.user name = kwargs.get('name') if uProjects.objects.filter(title=name, user=user, ifAdmin=True).exists(): return function(request, *args, **kwargs) else: return HttpResponseRedirect('/') return wrap @admin_check def update(request): if request.method == "POST": pr_form = ProjectUpdateForm(request.POST, request.FILES, instance=request.project.name) if pr_form.is_valid(): pr_form.save() messages.success(request, f'This project has been updated.') return redirect('project') else: pr_form = ProjectUpdateForm(instance=request.user.profile) context = { … -
Why doesn't my form validation work in django?
I am trying to have user validation in my django social media/blog app. I do not understand why this code does not work. The problem: No matter what name I type in the form it says the user does not exist even though the user does in fact exist. Any help would be amazing. from django.shortcuts import render, redirect from sign_in.forms import SignInForm from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth.forms import forms from django.http import HttpResponseRedirect def sign_in(request): if request.method == "POST": form = SignInForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = User.objects.filter(username=username, password=password) if user.exists(): return HttpResponseRedirect("boom/") else: messages.error(request, f"User {user} does not exist.") else: form = SignInForm() return render(request, "sign_in/sign_in.html", {"form": form}) -
How to categorize content in Django ? Where is the problem with my work?
I wanted to categorize my site content. Show the category titles in the menu and the contents of each category in the body. I have used these codes. #urls path('category/<slug:slug>', views.category, name="category") #views def category(request, slug): context = { "categorys": get_object_or_404(Category, slug=slug, status=True) } return render(request, "blog/category.html", context) #models class PostManager(models.Manager): def published(self): return self.filter(status='p') class Category(models.Model): title = models.CharField(max_length=100, verbose_name="عنوان دسته بندی") slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس") status = models.BooleanField( default=True, verbose_name="آیا نمایش داده شود؟") position = models.IntegerField(verbose_name="پوزیشن") class Meta: verbose_name = "دسته بندی" verbose_name_plural = "دسته بندی ها" ordering = ['position'] def __str__(self): return self.title class Post(models.Model): STATUS_CHOICES = [ ('d', 'پیش نویس'), ('p', 'منتشر شده'), ] title = models.CharField(max_length=100, verbose_name="عنوان") slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس") category = models.ManyToManyField( Category, verbose_name="دسته بندی", related_name="postcat") description = models.TextField(verbose_name="توضیحات") thumbnail = models.ImageField( upload_to="imgpost", height_field=None, width_field=None, max_length=None, verbose_name="تصویر") publish = models.DateTimeField( default=timezone.now, verbose_name="زمان انتشار") created = models.DateTimeField( auto_now_add=True, verbose_name="زمان ایجاد") updated = models.DateTimeField( auto_now=True, verbose_name="زمان بروزرسانی") status = models.CharField( max_length=1, choices=STATUS_CHOICES, verbose_name="وضعیت") def __str__(self): return self.title class Meta: verbose_name = "پست" verbose_name_plural = "پست ها" objects = PostManager() #template {% for posts in categorys.postcat.published %} <p> posts.title </p> <p> posts.description </p> {%endfor%} The problem is that despite the filter I have set … -
Django - page not found with VueJS
I'm trying to create a SPA with Vue in my Django project, so that Django handles only authentication templates and the rest of the frontend is entirely Vue rendered by webpack-loader, so it's Django rendering the Vue app. I'm doing this in order not to lose the benefits of having authentication handled entirely by Django. So everything below /accounts/ will be handled by Django templates rendered by django views, while everything below /app/ will be handled by the Vue application. I have the following: urlpatterns = [ # Some standard django templates url here for authentication.. # ... # The Vue app: path('app/', views.vueApp, name='vueApp'), ] So when the user navigates to mysite.com/app, Vue will handle the whole frontend as a SPA with its routes: //main.js const router = new VueRouter({ base: '/app', mode: 'history', routes: [ { path: '/', component: Home }, { path: '/test1', component: testcomponent }, { path: '/test2', component: test2component } ] }) The problem with my code, is that if i click on a link to test1 or to test2 from inside the Vue app, i will get redirected to testcomponent (mysite.com/app/test1) and test2component (mysite.com/app/test2); instead, if i open my browser and i navigate directly … -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed when receiving webhook
I'm using dj-paddle for subscription payments in my django app and i'm experiencing a strange problem. After making the payment for a subscription plan, the subscription_created webhook from paddle.com isn't received in my app and i get this error on console. sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/djpaddle/views.py", line 60, in post signal.send(sender=self.__class__, payload=payload) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/djpaddle/models.py", line 214, in on_subscription_created Subscription.create_or_update_by_payload(payload) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/djpaddle/models.py", line 193, in create_or_update_by_payload return cls.objects.update_or_create(pk=pk, defaults=data) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 585, in update_or_create obj.save(using=self.db) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/transaction.py", line 232, in __exit__ connection.commit() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/asyncio.py", … -
django.urls.exceptions.NoReverseMatch: Reverse for 'board_topics' with arguments '('',)' not found
i am struggling with this error, please any help, i tried many solution for this error but nothing work views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse,Http404 from .models import Board # Create your views here. def home(request): boards = Board.objects.all() return render(request,'home.html',{'boards':boards}) def board_topics(request,board_id): # try: # board = Board.objects.get(pk=board_id) # except: # raise Http404 board = get_object_or_404(Board,pk=board_id) return render(request,'topics.html',{'board':board}) def new_topic(request,board_id): return render(request,'new_topic.html') def about(request): return HttpResponse(request,'yes') url.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('about/',views.about,name='about'), path('boards/<int:board_id>/', views.board_topics, name='board_topics'), path('boards/<int:board_id>/new/', views.new_topic, name='new_topic') ] new_topic.html {% extends 'base.html' %} {% block title %} creat new topic {% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"> <a href="{% url 'home'%}"> Boards </a> </li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}"> {{board.name}} </a> </li> <li class="breadcrumb-item active">New Topic</li> {% endblock %} Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated. -
Get a list of all the field values from a Foreign Key Table in Django
am new to Django and currently trying the Foreign Key concept. I have three models as shown below. class Basket(models.Model): basket_name = models.CharField(max_length=5, unique=True) def __str__(self): return self.basket_name class Product(models.Model): Grams = 'GM' Kilograms = 'KG' WeightBased = 'WPG' QuantityBased = 'CPG' PRODUCT_UNIT_WT_CHOICES=[ (Grams, 'Grams'), (Kilograms, 'Kilograms') ] PRODUCT_TYPE_CHOICES =[ (WeightBased, 'Weight Based Product'), (QuantityBased, 'Quantity Based Product') ] product_name = models.CharField(max_length=30, unique=True) product_description = models.TextField(max_length=300) product_price = models.DecimalField(max_digits=5, decimal_places=2) product_unit_weight = models.DecimalField(max_digits=5, decimal_places=2) product_unit_weight_units = models.CharField(max_length=2, choices=PRODUCT_UNIT_WT_CHOICES, default=Grams) product_type = models.CharField(max_length=3, choices=PRODUCT_TYPE_CHOICES, default=QuantityBased) product_image = models.ImageField(upload_to=imageUploadPath, null=True, blank=True) def __str__(self): return self.product_name class BasketProductMapping(models.Model): basket_reference = models.ForeignKey(Basket, on_delete=models.CASCADE) product_reference = models.ForeignKey(Product, on_delete=models.CASCADE) mapped_basket_name = models.CharField(max_length=5,null=False, blank=False) mapped_product_name = models.CharField(max_length=30, null=False, blank=False) Here are my serializers: class ProductSerializer(serializers.ModelSerializer): product = serializers.CharField(read_only=True) class Meta: model = Product fields = ['id', 'product_name', 'product_description', 'product_price', 'product_unit_weight', 'product_unit_weight_units', 'product_type', 'product_image'] class BasketSerializer(serializers.ModelSerializer): basket = serializers.CharField(read_only=True) class Meta: model = Basket fields = ('id', 'basket_name') class BasketProductMappingSerializer(serializers.ModelSerializer): basket_reference = serializers.CharField(source ='basket.basket_name', read_only=True) product_reference = serializers.CharField(source='product.product_name', read_only=True) class Meta: model = BasketProductMapping fields = ['id', 'basket_reference', 'product_reference', 'mapped_basket_name', 'mapped_product_name'] What I am trying to achieve is get a list of all the values in 'basket_name' and 'product_name' when I call the BasketProductMappingSerializer. But the output I … -
Django F() and ExpressionWrapper
I am trying to avoid DB hits on my views.py. If I used the F() and ExpressionWrapper, Am I doing a query on the database. I am trying to optimize my code and kind of confused when I read the documentation. Views.py from django.shortcuts import render from django.db.models import F, Q, Count, Sum, ExpressionWrapper, IntegerField from .models import Student, Subject, Enrollment def home(request): student = Student.objects.all() subject = Subject.objects.all() sem_score = Enrollment.objects.all().update(sem_score=ExpressionWrapper((F("prelim_score") + F("midterm_score") + F("final_score"))/3, output_field=IntegerField())) enrollment = Enrollment.objects.all() num_student = Enrollment.objects.all().count() context = {"student":student, "subject":subject, "enrollment":enrollment, "num_student":num_student} return render(request, 'core/home.html', context) -
How to categorize content in django ? Where is the problem with my work?
I wanted to categorize my site content. Show the category titles in the menu and the contents of each category in the body. I have used these codes. #urls path('category/<slug:slug>', views.category, name="category") #views def category(request, slug): context = { "categorys": get_object_or_404(Category, slug=slug, status=True) } return render(request, "blog/category.html", context) #models class PostManager(models.Manager): def published(self): return self.filter(status='p') class Category(models.Model): title = models.CharField(max_length=100, verbose_name="عنوان دسته بندی") slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس") status = models.BooleanField( default=True, verbose_name="آیا نمایش داده شود؟") position = models.IntegerField(verbose_name="پوزیشن") class Meta: verbose_name = "دسته بندی" verbose_name_plural = "دسته بندی ها" ordering = ['position'] def __str__(self): return self.title class Post(models.Model): STATUS_CHOICES = [ ('d', 'پیش نویس'), ('p', 'منتشر شده'), ] title = models.CharField(max_length=100, verbose_name="عنوان") slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس") category = models.ManyToManyField( Category, verbose_name="دسته بندی", related_name="postcat") description = models.TextField(verbose_name="توضیحات") thumbnail = models.ImageField( upload_to="imgpost", height_field=None, width_field=None, max_length=None, verbose_name="تصویر") publish = models.DateTimeField( default=timezone.now, verbose_name="زمان انتشار") created = models.DateTimeField( auto_now_add=True, verbose_name="زمان ایجاد") updated = models.DateTimeField( auto_now=True, verbose_name="زمان بروزرسانی") status = models.CharField( max_length=1, choices=STATUS_CHOICES, verbose_name="وضعیت") def __str__(self): return self.title class Meta: verbose_name = "پست" verbose_name_plural = "پست ها" objects = PostManager() #template {% for posts in categorys.postcat.published %} <p> posts.title </p> <p> posts.description </p> {%endfor%} The problem is that despite the filter I have set …