Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to filter value with category on detail page template in django?
i have video category in categories, i want to filter video category value in detail page like if i click on video category value then i want this code {% video object.video as my_video %}{% video my_video 'medium' %}{% endvideo %} in detail page. if i click other categories values then i want {% else %} part how can i do that? model.py class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey( User, on_delete=models.CASCADE) thumbnail = models.ImageField(default='def.jpg', upload_to=article_path) video = EmbedVideoField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) content = RichTextUploadingField(blank=True) category = models.ManyToManyField() def get_absolute_url(self): return reverse('news-detail', kwargs={'pk': self.pk}) views.py def NewsDetail(request, pk): obj = get_object_or_404(Article, pk=pk) context = { 'object': obj, } return render(request, 'news/detail.html', context) detail.html {% if cat in object.category > 'videos' %} {% video object.video as my_video %} {% video my_video 'medium' %} {% endvideo %} {% else %} <figure class="social-icon"> <img src="{{ object.thumbnail.url }}" /> </figure> <h2>{{ object.title }}</h2> <ul> {{ object.author.username }} {{ object.timestamp }} {% for cat in object.category.all %} {{ cat }} {% endfor %} </ul> {{ object.content|safe }} {% endif %} -
use json data in django template
I have a model that has one class that is made up of a number of others using OneToOneField. I would like to provide my template with nested data in json format and parse the json using template tags directly in my template. I have made some use of the Django rest framework. The following is a generic example of my codebase: models.py-------------------------------------- class Class1(models.Model): class_1_field_1 = models.CharField() class_1_field_2 = models.CharField() class Class2(models.Model): class_2_field_1 = models.CharField() class_2_field_2 = models.CharField() class MainClass(models.Model): field_1 = models.CharField() field_2 = models.IntegerField() field_3 = models.DateTimeField() class_1 = models.OneToOneField(Class1, on_delete=models.CASCADE,) class_2 = models.OneToOneField(Class2, on_delete=models.CASCADE,) class Class1Serializer(serializers.ModelSerializer): class Meta: model = Class1 fields = ('class_1_field_1', 'class_1_field_2') class Class2Serializer(serializers.ModelSerializer): class Meta: model = Class2 fields = ('class_2_field_1', 'class_2_field_2') class MainClassSerializer(serializers.ModelSerializer): class_1= Class1Serializer() class_2= Class2Serializer() class Meta: model = MainClass fields = ('field1', 'field2', 'field3', 'class_1', 'class_2') views.py------------------------------------- MainClassListView(ListView): context_object_name = 'mainclasses' model = MainClass serializer_class = MainClassSerializer def get_queryset(self): object_list = MainClass.objects.filter(user__in=[self.request.user]) return object_list def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) serializer = MainClassSerializer(MainClass.objects.filter(user__in=[self.request.user]), many=True) context['data'] = JSONRenderer().render(serializer.data) return context def dispatch(self, request, *args, **kwargs): return super(MainClassListView, self).dispatch(request, *args, **kwargs) index.html---------------------------------------------------- ... {{data}} ... This tag displays a string with the following format: b'[valid_json_is_displayed_here]', where the valid_json_is_displayed_here is a … -
Are Django STATIC_ROOT files fetched locally on the server or over an Http call?
I'm using the following line in my Django project to embed a logo image file on a PDF. It works fine, but I was just wondering, is the STATIC_ROOT file accessed from the server machine locally or are they fetched via an http call? (Just trying to speed up the pdf generation process as much as possible.) from proj.settings import STATIC_ROOT logo = Image.open(STATIC_ROOT + "img/" + "logo.png") -
How to create functional tests for Django view
In my Django app, I have a view which makes a request to an API server to retrieve data, then displays this data back in a template. I am completely new to testing, and am unsure about what functional tests I can create to test this view. I have created a test to assert that the popup loads and returns a HTTP response 200 (mocking out the API and using a pre-defined mock data set). How else can I test this view? How can I test whether the view is loading the correct data? -
Error when connecting Django project to mysql?
I'm using python 3 and I have tried to connect my Django project(django3) to MySQL but I keep getting this error even though I installed mysqlclient. I get this error when I'm trying to connect to MySQL Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/options.py", line 208, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) … -
While executing a Celery Task 'AsyncResult' object is not iterable
I am Using Celery to perform a task in the background on form submission. As soon as form is submitted during POST request, I have created a task to execute in the back ground using delay method. This task processes some click operations on some other web using selenium web driver and return two python lists after task execution. Based on list content I want to display pop up message. When I execute the task using celery and run the Django web development server on form submit , I am getting error message: 'AsyncResult' object is not iterable”. Please suggest how to resolve this issue and proceed further. Here is my code snippet: sample List content which obtained through selenium operations on web page is as shown below: board_not_used_list = ['16123','14960'] board_mgr_permissions_not_present_list = [ '23456','45678'] views.py: -------- def conclude_key_issue_form(request, id=None): if id: action = 'edit' model = get_object_or_404(ConcludeKeyIssues, pk=id) else: action = 'submit' model = ConcludeKeyIssues() message = "" if request.method == 'POST': form = ConcludeKeyIssuesForm(request.POST, instance=model) selected_model_name = request.POST.get('registered_model') if form.is_valid(): new_key_issue_request = form.save(commit=False) new_key_issue_request.integrator_id = request.user.username integrator_username = new_key_issue_request.integrator_id integrator_password = form.cleaned_data['integrator_pwd'] new_key_issue_request.integrator_pwd = integrator_password new_key_issue_request.save() form.save_m2m() created_pk = new_key_issue_request.pk if id is None: board_not_used_list, board_mgr_permissions_not_present_list = task_check_board_availability_and_permissions.delay(created_pk) … -
Django, How to validate year dependent on another class foreig key
In Django models i have two classes and I want to validate class Comment date to be less or equal class Report year. class Report(models.Model): year = models.PositiveIntegerField('year of report', default=date.today().year) and another class: class Comment(): report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='comment') date = models.DateField('date', validators=[year_validation]) How can i do this thnig? I discovered something like custom validators. I made a function and used it but how can i get acces to second class here? I wanted to do something like this but it doesn't work. def year_validation(self, value): if value.year > self.report.year: raise ValidationError('The year should be not later than: {}'.format(self.report.year)) -
Django url rendering
I am trying to build a simple django project but facing troubles with url related changes in case of second app. My first app is app1 and contains login, registration and few other things. urls.py in app1 url(r'^$', views.loginView, name='loginView'), url(r'^register/$', views.registerationView, name='registerationView'), url(r'^app2/', include('app2.urls')) urls.py in app2 url(r'^$', views.homeView, name='homeView'), After logging in, the user is successfully redirected to url http://127.0.0.1:8000/app2 which is what i want for the register too. Instead, it starts searching for the url http://127.0.0.1:8000/register/app2 which is non existent and gives me 404 error. I want to look for the same url as after login which is http://127.0.0.1:8000/app2. This is my views.py file for user register def registerationView(req): form = forms.registerForm() if req.method=='POST': form = forms.registerForm(req.POST) if form.is_valid(): form.save() return redirect('blog/') return render(req, 'register.html', context={'form': form}) -
How to unittest a method from a django class based view that does not deal with a request/response object?
I am trying to unittest the addition method inside of a class based view. The method I am testing does not deal with a request or response object. What is the easiest way to unit test this? When I look at django docs the unittests for class based views, seem to test the entire class rather than narrow in on testing individual methods. views.py class MathView(APIView): def addition(self): # how do i unittest this method? sum = 1+1 return sum def get(self, request, format=None): sum = self.addition() return Response(sum) -
Speed up tuning for many to many model
I have a model which has a few manytomany relationship class Article(models.Model): authors = models.ManyToManyField(Author) tags = models.ManyToManyField(Tag) genre = models.ManyToManyField(Genre) then I need to fetch more than 10000 rows by using ArticleSerializer. class ArticleSerializer(serializers.ModelSerializer): authorObjs = serializers.SerializerMethodField() tagObjs = serializers.SerializerMethodField() genreObjs = serializers.SerializerMethodField() class Meta: model = Article fields = ('id','authorObjs','tagObjs','genreObjs') def get_authorObjs(self,obj): res = [] for my in obj.authors.all(): res.append({ "id" : my.id, "name" : my.name }) return res def get_tagObjs(self,obj): res = [] for my in obj.tags.all(): res.append({ "id" : my.id, "name" : my.name }) return res def get_genreObjs(self,obj): res = [] for my in obj.genres.all(): res.append({ "id" : my.id, "name" : my.name }) return res It works well but it takes 20~30 sec. I want to speed up as much as possible. I checked around and thought fetching manytomany objects takes more time than fetching a normal column. At first I try to cache with @method_decorator in view. class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer @method_decorator(cache_page(None)) @method_decorator(vary_on_cookie) However new article is added every 10 min. so it's not appropriate. I am guessing there is still ways like 1.cache each row of Database.... 2.index key's tuning... Am I correct?? Is there any good idea to speed … -
Django-Channels AsyncConsumer not working
using SyncConsumer with below code works fine class BackgroundTaskConsumer(SyncConsumer): def create_users(self, message): number = message['number'] id = message['id'] UserFactory.create_batch(number, groups=(id,)) But when using AsyncConsumer with below code stop working class BackgroundTaskConsumer(AsyncConsumer): async def create_users(self, message): number = message['number'] id = message['id'] await UserFactory.create_batch(number, groups=(id,)) -
Error: Invalid hook call when using with redux
Sorry if i am asking a beginner's question. Im very new to React.js and recently i have been trying to grasps the concepts by following this tutorial : JustDjango What im trying to accomplish is creating a login form and it uses redux to store the states , my code is as follows : import React from 'react'; import { Form, Icon, Input, Button, Spin } from 'antd/lib'; import { connect } from 'react-redux'; import { NavLink } from 'react-router-dom'; import * as actions from '../store/actions/auth'; const FormItem = Form.Item; const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />; class NormalLoginForm extends React.Component { handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { this.props.onAuth(values.userName, values.password); this.props.history.push('/'); } }); } render() { let errorMessage = null; if (this.props.error) { errorMessage = ( <p>{this.props.error.message}</p> ); } const { getFieldDecorator } = this.props.form; return ( <div> {errorMessage} { this.props.loading ? <Spin indicator={antIcon} /> : <Form onSubmit={this.handleSubmit} className="login-form"> <FormItem> {getFieldDecorator('userName', { rules: [{ required: true, message: 'Please input your username!' }], })( <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" /> )} </FormItem> <FormItem> {getFieldDecorator('password', { rules: [{ required: true, message: 'Please input your Password!' }], })( … -
Expecting JSON object instead of JSON Array
In my django application with database engine djongo, I'm trying to return a JSON response by retrieving from my database. But, I'm receiving JSON array instead of JSON object. Currently, there is only one record in my database. Please see the code below. model.py class bloodDonors(models.Model): location=models.CharField(max_length=20) name=models.CharField(max_length=20) phone=models.IntegerField() address=models.TextField() bloodGroup=models.CharField(max_length=5) type=models.CharField(max_length=20) def __str__(self): return self.name views.py class bloodDonersView(viewsets.ModelViewSet): queryset = bloodDonors.objects.all() serializer_class = bloodDonorsSerializer JSON Reponse: [ { "id": 3, "location": "Delhi", "name": "Tony", "phone": 888, "address": "South street", "bloodGroup": "B+", "type": "blood-donation" } ] But, actually I needed the response as given below: { "id": 3, "location": "Delhi", "name": "Tony", "phone": 888, "address": "South street", "bloodGroup": "B+", "type": "blood-donation" } -
django : Once User fills form after login,whenever user login again he should not see form again that is been applied
I have an application where user login and where appears a form user fill the form and redirect to next page where he sees the status of his applied form, So now i am trying if user has filled the form whenever he logins he should redirect to status page and if user login and have not filled form he should get the form template. SO can anyone help me how to achieve these i am able to login user and get the form filled but again if same user is logging in , I am getting the form appear. -
How can I pass in multiple parameters in my Url
So I'm a developer noobie, and building my first project from scratch. I'm currently building a messaging system for my app. How it's supposed to work is that A user goes to a link that checks their current conversations, so conversations are displayed. Then FROM the conversations, there is a link that takes them to a page that displays the contents of that conversation. But I'm having a problem here, because when I try to get the other user's pk to display their messages, my code is instead getting request.user pk and getting ALL the messages that the current user has going on not exclusively between 2 users within that specific conversation. Now, when I manually, and by manually I mean typing the actual pk of the specific user I want to check on that has messages with my user, when I manually enter their pk number in the http, I am able to get the correct messages and exclusive messages. Currently, my href link is passing conversation.pk and I haven't figured out how to get the other users pk. Everything I have tried has kept passing my request.user pk. So I guess what I'm asking is how can I … -
Django use forloop for create multi objects
I have model : aa= Order.objects.get(Id="15") cc=Commission.objects.filter(maincommission__mainorder__id=aa.id) If cc come back with 3 results how can I create all three in CommissionHistory (models.model): percentage=cc.percentage Thx -
Vue Router router-link only changes the last section of url path
I am using Django alongside Vuejs, and I am serving vuejs from django using django_webpack_loader,but I have a problem with Vue Router, so first this is my Vue Router config file: Vue.use(VueRouter); export default new VueRouter({ mode:'history', routes:[ { path:'/', component:Home, }, { name:'dashboard', path:'/dashboard', component:Dashboard, }, { name:'categories', path:'/categories/add', component:Category, }, { path: '/dashboard/course/:uu_id/index', component:CourseIndex, name:'courseIndex', props:true }, { path: '/dashboard/course/:uu_id/posts/:post_id/edit', component:PostEdit, name:'PostEdit', }, ] }); so when I us router.push every thing is fine but when I am in /categories/add and I want to head to new page say dashboard using router-link component it takes me to /categories/dashboard, now if I again try to change path to '/categories/add' it takes me to categories/categories/add, it always replaces the last part of the path with my target path. what is the problem? -
how to iterate through an array and add an element to the end
I create a local site for myself . I have a form that creates a user in the database . Then you need to log in to your account so to speak and fill out the second form, we get an object from the database using name (field in the database ) = form. I want after getting this object, I went through the array and moved the object to the very end, so that I could then get it using -id[0] -
standard_init_linux.go:211: exec user process caused "no such file or directory"?
Dockerfile FROM python:3.7.4-alpine ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV LANG C.UTF-8 MAINTAINER Nurbek Batyrzhan "foto.nurbek@gmail.com" RUN apk update && apk add postgresql-dev gcc musl-dev RUN apk --update add build-base jpeg-dev zlib-dev RUN pip install --upgrade setuptools pip RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ #CMD ["gunicorn", "--log-level=DEBUG", "--timeout 90", "--bind", "0.0.0.0:8000", "express_proj.wsgi:application"] ENTRYPOINT ["./docker-entrypoint.sh"] docker-entrypoint.sh #!/bin/bash # Prepare log files and start outputting logs to stdout touch /code/gunicorn.log touch /code/access.log tail -n 0 -f /code/*.log & # Start Gunicorn processes echo Starting Gunicorn. exec gunicorn express_proj.wsgi:application \ --name express \ --bind 0.0.0.0:8000 \ --log-level=info \ --log-file=/code/gunicorn.log \ --access-logfile=/code/access.log \ --workers 2 \ --timeout 90 \ "$@" Getting Error standard_init_linux.go:211: exec user process caused "no such file or directory" Need help. Some saying to use dos2unix(i do not know hoe to use it.) -
Update a queryset in django
I need to update the data on the database once I get all the values of that data with current DateTime..i.e My Model: class Load_Balancing(models.Model): instance_name = models.CharField(max_length=100) instance_visit = models.DateTimeField(null=True) sequence = models.IntegerField() I want to get the value with the last sequence number inserted in the database and update its time to the current time. I tried: instances = Load_Balancing.objects.all().order_by("-sequence")[:1] a = Load_Balancing.objects.filter(sequence=instances.sequence).update(instance_visit= datetime.datetime.now()) But it's not working. -
Why is my form not being saved to admin database?
Hi I'm trying to develop a website for an online store using Django. I want to use Ajax to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being redirected to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: … -
Coloring specific values based on condition in Django thorugh CSS in html template
formula.py funct(): apple=[2.3,4.6,7.5] orange=[3.1,5.6,7.8] jam=list(map(lambda a,o: round((a/o),3) if o else 0, apple,orange)) return (apple,orange,jam) views.py def view(request): forma = SimpleForm(request.POST) if request.method == "POST": if forma.is_valid(): forma = forma.save() box = form.box garden=Garden.objects.get(fruit=box) formula=funct() context={'formla':formula,'garden':garden} template.html <table> <tr><th>Jam Recipe</th>{% for item in jam %}{% if item>2 %}<td class="green">{{ item }}</td> {% endif %}{% endfor %}</tr></table> css: .green {color: green;} I want to color the table in template.html in green color if values in list jame in the table more than 2. I wrote the above code, color it does not color my table some values in green. What is wrong and how to fix it ? What i am missing? Any help is appreciated. -
django formset error : "ManagementForm data is missing or has been tampered with"
I trying to do some crud using Django formset but I get this error "ManagementForm data is missing or has been tampered with", if I change the data management tag to {{ formset.management_form}} then the error is gone but nothing happens, I got no data displayed, so what to do? views.py : def view(request): achat = Achats.objects.all() form = formset_factory(AssociationForm,extra=1) formset = form(request.POST or None) if formset.is_valid(): for form in formset: print(form.cleaned_data) return render(request, 'html.html', {'Achats': achat, 'formset': formset}) forms.py : class AssociationForm(forms.ModelForm): class Meta: model = Association fields = ('Id_Achats', 'Id_Article', 'Prix_Unitaire', 'Quantite') html {% load widget_tweaks %} {% for form in formset %} <form method="POST" enctype="multipart/form-data"> {{ formset.management_data}} {% csrf_token %} <td>{% render_field form.Id_Achats class="form-control" %}</td> <td>{% render_field form.Id_Article class="form-control" %}</td> <td>{% render_field form.Prix_Unitaire class="form-control" %}</td> <td>{% render_field form.Quantite class="form-control" %}</td> <input type="submit" value="Submit"> </form> {% endfor %} -
Django - Reverse for 'processinglist' with arguments '('',)' not found. 1 pattern(s) tried: ['processing/(?P<pk>[0-9]+)/$']
I am learning Django by following some tutorials, along with Django official doc. I have an issue with reverse URL. It just does not seem to be working out for me, hence I'm looking for some help. Here's my models.py from django.db import models from django.urls import reverse class ProcessingActivityTopType(models.Model): type = models.CharField(max_length=200) def get_absolute_url(self): return reverse('processinglist', args=[str(self.id)]) def __str__(self): return self.type class ProcessingActivity(models.Model): class Meta: verbose_name_plural = 'Processing Activities' processing_toptype = models.ForeignKey(ProcessingActivityTopType, on_delete=models.CASCADE, related_name='processingactivities') processing_type = models.CharField(max_length=200) processing_purpose = models.CharField(max_length=200) processing_category = models.ManyToManyField('PersonalData', related_name='processing_category') processing_legalbasis = models.ForeignKey(LegalBasis, on_delete=models.CASCADE, related_name='legal_basis') processing_retention = models.CharField(max_length=200) processing_datasubject = models.CharField(max_length=200) processing_transfers = models.CharField(max_length=200) processing_security = models.CharField(max_length=200) def __str__(self): return self.processing_type Here's my views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from .models import ProcessingActivityTopType, ProcessingActivity class ProcessingActivityListView(generic.ListView): model = ProcessingActivityTopType class ProcessingListByTopType(generic.ListView): model = ProcessingActivity def get_queryset(self): id = self.kwargs['pk'] target_toptype=get_object_or_404(ProcessingActivityTopType, pk = id) return ProcessingActivity.objects.filter(processing_toptype=target_toptype) def get_context_data(self, **kwargs): context = super(ProcessingListByTopType, self).get_context_data(**kwargs) context['processings'] = get_object_or_404(ProcessingActivityTopType, pk = self.kwargs['pk']) return context Here's my urls.py from django.urls import path, include from . import views urlpatterns = [ path('processings/', views.ProcessingActivityListView.as_view(), name='toptypes'), path('processing/<int:pk>', views.ProcessingListByTopType.as_view(), name='processinglist'), ] Here's my html template <div class="row"> {% for i in processingactivitytoptype_list %} <div class="col-md-4"> <div class="card mb-2"> <div class="card-body"> … -
Django: NoReverseMatch error when trying to pass two url parameters
I am working on a project and I am a beginner in Django. In the project, the user can create product posts and other users can upvote it. I am working on the thing that the user can delete the post created by himself. I don't know what are the best practices for it but I am trying this method. this is usersposts.html {% for product in products.all %} {% if product.hunter.username == user.username %} #extra code here--- <a class="btn btn-md btn-outline-danger btn-block font-weight-bolder h5" href="{% URL 'deletepost' user.id product.id %}">delete</a> {% endif %} {% endfor %} this is urls.py urlpatterns = [ #more URLs here---- path('deletepost/<int:user_id>/<int:product_id>/', views.deletepost, name='deletepost'), ] this is the view function for deletepost @login_required(login_url="/accounts/signup") def deletepost(request, user_id, product_id): if request.method == 'POST': user = get_object_or_404(User, pk = user_id) if user.check_password(request.POST['password']): product = get_object_or_404(Product, pk = product_id) product.delete() messages.success(request, 'post deleted successfully!') return render(request,'products/home.html') else: messages.error(request, 'password is incorrect !') return render(request,'products/deletepost.html') else: return render(request,'products/deletepost.html') this should work I think but I don't know what I am doing wrong that I am getting this error NoReverseMatch at /products/deletepost/17/4/ Reverse for 'deletepost' with arguments '(17, '')' not found. 1 pattern(s) tried: ['products\\/deletepost\\/(?P<user_id>[0-9]+)\\/(?P<product_id>[0-9]+)\\/$'] Request Method: GET Request URL: http://127.0.0.1:8000/products/deletepost/17/4/ …