Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Internal Server Error: AssertionError: Expected a `Response`, `HttpResponse` to be returned from the view, but received a `<class 'NoneType'>`
code The above image has the code and below one is the erorr which I am getting, if i am using post man to test my API seperatly it's working prorperly. AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> -
pika.exceptions.AMQPConnectionError in Django with Docker
I'm using docker to run two django services. RabbitMq is installed in the host not in a container. When I run the django development server without the container rabbitmq connection works. But when I use the docker-compose up it gives pika.exceptions.AMQPConnectionError error. I restarted the rabbitmq but it doesn't resolve the problem Dockerfile FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8000 Dockercompose.yml version: '3.3' services: blog_writer: build: context: . dockerfile: DockerFile ports: - 8001:8000 volumes: - .:/app Producer.py import json import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', heartbeat=600, blocked_connection_timeout=300)) channel = connection.channel() def publish(method, body): properties = pika.BasicProperties(method) channel.basic_publish(exchange='', routing_key='blogs', body=json.dumps(body), properties=properties) RabbitMq Status sudo systemctl status rabbitmq-server.service [sudo] password for navanjane: ● rabbitmq-server.service - RabbitMQ broker Loaded: loaded (/lib/systemd/system/rabbitmq-server.service; enabled; vend> Active: active (running) since Sat 2022-01-15 18:51:40 +0530; 1 day 5h ago Main PID: 1105 (beam.smp) Tasks: 28 (limit: 9342) Memory: 105.7M CGroup: /system.slice/rabbitmq-server.service ├─1105 /usr/lib/erlang/erts-12.1.5/bin/beam.smp -W w -MBas ageffcb> ├─1170 erl_child_setup 32768 ├─1556 /usr/lib/erlang/erts-12.1.5/bin/epmd -daemon ├─1588 inet_gethost 4 └─1589 inet_gethost 4 ජන 15 18:51:35 navanjane-Ubuntu rabbitmq-server[1105]: Doc guides: https://r> ජන 15 18:51:35 navanjane-Ubuntu rabbitmq-server[1105]: Support: https://r> ජන 15 18:51:35 navanjane-Ubuntu rabbitmq-server[1105]: Tutorials: https://r> ජන … -
Cannot assign "2": "OrderProduct.product" must be a "Product" instance
**Hi everyone I want to move the Cart Items to Order Product Table after payment First, the products are get from the card item model. Product number is multiplied by product price ,and I got the order model for got the order total My Cart item were not moved to Order Product table How Can I move them? I got this error ValueError at /go-to-gatewey/** enter image description here ValueError at /go-to-gatewey/ Cannot assign "2": "OrderProduct.product" must be a "Product" instance. Request Method: GET Request URL: http://127.0.0.1:8000/go-to-gatewey/ Django Version: 3.2.9 Exception Type: ValueError Exception Value: Cannot assign "2": "OrderProduct.product" must be a "Product" instance. Exception Location: E:\English Projects_I Do it\Second_Project\GreatKart_Persian\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 215, in set Python Executable: E:\English Projects_I Do it\Second_Project\GreatKart_Persian\venv\Scripts\python.exe payment function: def go_to_gateway_view(request,total=0, quantity=0): cart_items = CartItem.objects.filter(user=request.user) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity tax = (2 * total) / 100 grand_total = total + tax form = OrderForm(request.POST) data = Order() data.order_total = grand_total data.tax = tax # Generate order number yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr, mt, dt) current_date = d.strftime("%Y%m%d") # Like this : 2021 03 05 order_number = current_date + str(data.id) data.order_number = order_number … -
Django - TypeError __init__() missing 1 required positional argument when uploading a file
I want to set an initial value "test" to the field name when I'm uploading a file with a Django. Here is what I tried in views.py: class UploadFile(CreateView): form_class = UploadFileForm template_name = "tool/upload.html" success_url = reverse_lazy('tool:index') fields = ['file',] def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(self.success_url) else: return render(request, self.template_name, {'form': form}) And in forms.py: class UploadFileForm(forms.ModelForm): class Meta: model = CheckFile fields = ['file', ] def __init__(self, file, *args, **kwargs): file = kwargs.pop('file') super(UploadFileForm, self).__init__(*args, **kwargs) if file: self.fields['name'] = "test" But I end up having the following error: TypeError: UploadFileForm.__init__() missing 1 required positional argument: 'file' I don't understand why I keep having this error. Could you please help me? Thanks! -
How do I register and log-in a User in django-rest-framework?
I have no idea how to do it. I just want to know the best way to register and/or log-in a User through rest API. I would be thankful for any code snippets or documentatnion links. -
trying to deploy django to heroku - error message
I tried to deploy my django to heroku and i get this error. -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app ! No default language could be detected for this app. HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. See https://devcenter.heroku.com/articles/buildpacks ! Push failed please help... -
ElasticSearch tutorial: Getting ValueError from bulk_indexing
I am following this tutorial. https://medium.com/free-code-camp/elasticsearch-with-django-the-easy-way-909375bc16cb#.le6690uzj Tutorial is about using elasticsearch with django app. I am stuck when it ask to use bulk_indexing() in shell. I am getting this error ** raise ValueError("You cannot perform API calls on the default index.") ValueError: You cannot perform API calls on the default index.** >>>python manage.py shell Python 3.10.0 | packaged by conda-forge | (default, Nov 10 2021, 13:20:59) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from elasticApp.search import * >>> bulkIndexing() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\jatin.kumar.in\Documents\JK\Project\elasticApp\search.py", line 17, in bulkIndexing ArticleIndex.init() File "C:\Users\jatin.kumar.in\Miniconda3\envs\Project\lib\site-packages\elasticsearch_dsl\document.py", line 156, in init i.save(using=using) File "C:\Users\jatin.kumar.in\Miniconda3\envs\Project\lib\site-packages\elasticsearch_dsl\index.py", line 298, in save if not self.exists(using=using): File "C:\Users\jatin.kumar.in\Miniconda3\envs\Project\lib\site-packages\elasticsearch_dsl\index.py", line 414, in exists return self._get_connection(using).indices.exists(index=self._name, **kwargs) File "C:\Users\jatin.kumar.in\Miniconda3\envs\Project\lib\site-packages\elasticsearch_dsl\index.py", line 134, in _get_connection raise ValueError("You cannot perform API calls on the default index.") ValueError: You cannot perform API calls on the default index. >>> Help me in solving this error. -
Django models adding member to a project
Trying to figure out how to create a Project class for an app I am making. I am bringing inn a Profile from another app, containing username, names and avatar. Then i need a project name and i want to be able to bring inn members, to the specific project, but don't know how to go forward with that. models.py from django.db.models.deletion import CASCADE from django.db import models from profiles.models import Profile class Projects(models.Model): user = models.ForeignKey(Profile, on_delete=CASCADE) project_name = models.CharField(max_length=55, null=True, blank=True) members = how to get members inn this? Will add tasks, notes and a chat as seperate classes then bring them inn to the project as foreignkey, think that would be correct. But how to deal with the members and get them added to the project? -
Not Found The requested resource was not found on this server
I follow this address and I set DEBUG = False in appartement/settings.py in my project. I changed /etc/apache2/sites-available/000-default.conf: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /media /var/www/b9/appartement/cdn/cdn_medias Alias /static /var/www/b9/appartement/cdn/cdn_assets <Directory /var/www/b9/appartement/cdn/cdn_medias/> Require all granted </Directory> <Directory /var/www/b9/appartement/cdn/cdn_assets/> Require all granted </Directory> <Directory /var/www/b9/appartement/appartement> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess appartement python-path=/var/www/b9/appartement:/var/www/b9/django-virtualenv_b9/lib/python3.8/site-packages WSGIProcessGroup appartement WSGIScriptAlias /appartement /var/www/b9/appartement/appartement/wsgi.py </VirtualHost> but when i run django project, i got Not Found error about statics files and it can not found CSS files -
If any are null, do something
I have a view that performs some basic calculations, but sometimes not all fields have values added, so the calculations fail due to trying to do calculations that do exist. Is there a way to say if any fields contain null or blank then pass or do i need to write a if for every one? if QuestionnaireResponse.objects.filter(project_name_id=project_id, questionnaire_id=1).exists(): dist_resp = QuestionnaireResponse.objects.get(project_name_id=project_id, questionnaire_id=1) artist_percent = QuestionnaireAnswer.objects.get(question_id=3,response=dist_resp) marketing_percent = QuestionnaireAnswer.objects.get(question_id=4,response=dist_resp) advisers_percent = QuestionnaireAnswer.objects.get(question_id=5,response=dist_resp) community_percent = QuestionnaireAnswer.objects.get(question_id=6,response=dist_resp) team_percent = QuestionnaireAnswer.objects.get(question_id=7,response=dist_resp) partners_percent = QuestionnaireAnswer.objects.get(question_id=8,response=dist_resp) reserve_percent = QuestionnaireAnswer.objects.get(question_id=9,response=dist_resp) artist_percent_allocation = ((project.project_total_supply / 100)*(artist_percent.answer)) marketing_percent_allocation = ((project.project_total_supply / 100)*(marketing_percent.answer)) advisers_percent_allocation = ((project.project_total_supply / 100)*(advisers_percent.answer)) community_percent_allocation = ((project.project_total_supply / 100)*(community_percent.answer)) team_percent_allocation = ((project.project_total_supply / 100)*(team_percent.answer)) partners_percent_allocation = ((project.project_total_supply / 100)*(partners_percent.answer)) reserve_percent_allocation = ((project.project_total_supply / 100)*(reserve_percent.answer)) I have set a if on the first line which works, but sometimes that if can return true, but the lines below could be null. marketing_percent_allocation = ((project.project_total_supply / 100)*(marketing_percent.answer)) advisers_percent_allocation = ((project.project_total_supply / 100)*(advisers_percent.answer)) community_percent_allocation = ((project.project_total_supply / 100)*(community_percent.answer)) team_percent_allocation = ((project.project_total_supply / 100)*(team_percent.answer)) partners_percent_allocation = ((project.project_total_supply / 100)*(partners_percent.answer)) reserve_percent_allocation = ((project.project_total_supply / 100)*(reserve_percent.answer))` Is this possible? Thanks -
Can't connect MPTT with django.parler
I do e-commerce in django. I have Category model that I want to work with both django.parler and django-MPTT, because I want to make subcategories for category. I've done everything like in django-parler documentation to connect these two packages the right way. After saving the model, the following error appears: ImproperlyConfigured at /pl/admin/store/category/ TreeQuerySet class does not inherit from TranslatableQuerySet And I'm not sure why. My Category model: models.py class Category(MPTTModel, TranslatableModel): parent = TreeForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=200, db_index=True, unique=True, blank=True, null=True, default='') translations = TranslatedFields( name=models.CharField(max_length=200, db_index=True, blank=True, null=True, default=''), ) class Meta: unique_together = ['slug', 'parent'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def get_absolute_url(self): return reverse('store:product_list_by_category', args=[self.slug]) admin.py @admin.register(Category) class CategoryAdmin(TranslatableAdmin, MPTTModelAdmin): list_display = ['name', 'slug', 'parent'] search_fields = ['name'] def get_populated_fields(self, request, obj=None): return {'slug': ('name',)} -
ForigenKey in django preselected when creating a modelform for a a relation table
I want to have the Forgienkey to be preselected of it's relation table id, in example i want to create a job for a specific component with the component being already chosen. my view.py : def create_job(request, pk): component = Component.objects.all() component_id = Component.objects.get(id=pk) obj = Job.objects.get() obj.component_id(id=pk) instance = JobModelForm(instance=obj) form = JobModelForm() if request.method == 'POST': form = JobModelForm(request.POST,) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) context = { 'components': component, 'component_id': component_id, "form": form, "instance":instance, } return render(request, 'create_job.html', context) the form template : <form method='POST' action=''> {% csrf_token %} <span class="component-label-text">Job name</span> {% render_field form.name class="component-form-data-inputs" %} <span class="component-label-text">Job description</span> {% render_field form.description class="component-form-data-inputs" %} <span class="component-label-text">Job type</span> {% render_field form.type class="component-form-data-inputs" %} <span class="component-label-text">Check if Job is critical</span> {% render_field form.is_critical %} <br> <span class="component-label-text">Job interval</span> {% render_field form.interval class="component-form-data-inputs" %} <span class="component-label-text">Job Due date</span> {% render_field form.due_date %} <br> {% render_field instance.component class="component-form-data-inputs" %} <input type="submit" class="button1" value='Create Job' /> </form> -
Django Allauth: Duplicate Key Value Violates Unique Constraint: Key (username)=() already exists
I have been troubleshooting an issue with my custom allauth Django user model for some time. I only want to use email, first name, last name, and password as part of my user signup form, and I can get it to work once, but when a second user signs up, it says that the username already exists. I have seen others with a similar issue, but unfortunately their solutions do not work. If I remove the custom account form, then it does, but I need to include first name and last name in my signup form, so not sure how to work around that. Any help is appreciated! settings.py AUTH_USER_MODEL = 'accounts.CustomUser' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None # I have also tried ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' and 'email' ACCOUNT_FORMS = { 'signup': 'accounts.forms.CustomUserCreationForm' } models.py class CustomUser(AbstractUser): email = models.EmailField(max_length=256) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'first_name', 'last_name') -
How to get instance from global id in Django with Graphene Relay
graphql_relay has a function from_global_id which returns the model_name and the instance_id. However, it seems that to retrieve the model from the name of the model, we need to know in which app the model is, such as answers in the question asking how to get the model from its name. Is there a way to know the name of the app from the global id? Or is there any other way to retrieve the instance? -
Django and stripe handle successful payment
I am trying to handle successful payment using stripe webhook, in my stripe dashboard I see that the events are triggered and the payment_intent is successful but the order is not created views.py : from django.shortcuts import render from django.http import JsonResponse from django.http import HttpResponse import stripe import json from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from article.models import Order endpoint_secret = '1wwww' @require_POST @csrf_exempt def my_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None # Try to validate and create a local instance of the event try: event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'payment_intent.succeeded': checkout_session = event['data']['object'] # Make sure is already paid and not delayed _handle_successful_payment(checkout_session) # Passed signature verification return HttpResponse(status=200) def _handle_successful_payment(checkout_session): payed_order = Order.objects.create(order_id='test22') return payed_order -
Django - Could not parse the remainder: '++_RS' from 'annovar.GERP++_RS'
I have a JSON value that comes directly from a DB that has this label GERP++_RS This is part of a big dictionary and I need to display the correspondent value on a HTML page, but Django gives me this error Could not parse the remainder: '++_RS' from 'annovar.GERP++_RS' What would be best strategy to retrieve the value from this key? Would I need to process it before it gets to the template? Thanks in advance -
how to run django in pycharm in https
I need to run a python Django project with Pycharm IDE locally in HTTPS so that other services can talk with my service without any errors. I don't manage to run it locally in HTTPS -
Passing and using the request object in django forms
I'm trying to user the request object to create a dynamic dropdown list in my form using the following code: view: form = TransactionForm(request.user) form: class TransactionForm(forms.Form, request.user): # Payment methods get_mm_details = MMDetails.objects.filter(username=request.user) get_card_details = CardDetails.objects.filter(username=request.user) payment_meth = [] # form fields trans_amount = forms.IntegerField(label="Amount", min_value=0) payment_method = forms.CharField( label='Payment method', widget=forms.Select( choices=payment_meth ) ) is there a way of using the request object in a form? -
Django --- how to get pdf model upfront in a html download button?
I would like to create a HTML button where it loads the pdf file from the database. Do you know how to create the button to upload the latest pdf file from the model? Below is my code so far from the model: class PdfLoad(models.Model): file = models.FileField(upload_to='Portfolios/') Code for admin.py: admin.site.register(PdfLoad) Code HTML code: <!-- Download link --> <section class="about section" id="CV"> <h2 class="section-title">Curriculum Vitae</h2> <div class="d-flex justify-content-center"> <a href ="{{pdf.file}}"><button type="submit" class="cv__button" onclick="blank">CV</button></a> </div> </section> do I have to do something for the setting.py file ?? -
Filter Dataset Based on Account Log In
I'm trying to filter the dataset shown in my table based on the user that logged in within the previous page. My app is set up in a way that it's a simple log-in screen where you put a username and password, and then there's a single dataset feeding two screens: 1 = Week, 2 = Picks. On the first screen, you select which week you'd like to select picks for, and once you click into a week you can change your picks. When I've built apps in different solutions, my idea was to store username or week as a variable and then filter the dataset to just records pertaining to that criteria, but I'm not sure how to do that in Django. Thoughts? I have the following code: views.py class PickList(LoginRequiredMixin, CoreListView): model = Pick def user_picks(request): Pick.objects.filter(submitter={{ request.user.get_full_name|default:request.user }}) return render(request, 'app/pick_list.html', {'Pick': Pick}) app urls.py urlpatterns = [ path('', home, name='home'), path('picks/', PickList.as_view(), name='pick-list'), path('pick/<int:pk>/', PickDetail.as_view(), name='pick-detail'), path('picks/<str:submitter>', user_picks(), name='pick-list'), path('weeks/', WeekList.as_view(), name='week-list'), path('weeks/<int:pk>/', WeekDetail.as_view(), name='week-detail'), ] account urls.py urlpatterns = [ path('login/', views.LoginView.as_view(template_name='account/signin.html', authentication_form=AuthenticationForm, extra_context={ 'title': 'Login', 'extra_title': 'Please sign in', }), name='login'), path('logout/', views.LogoutView.as_view(next_page='account:login'), name='logout'), ] models.py class Pick(models.Model): submitter = models.CharField(max_length=50, verbose_name='Submitter', null=True, blank=True) … -
Custom User return empty get_all_permissions()
I'm just trying start work with Permissions to learn how thats work. In shell i have empty set() result. I see this question, is the same of that, but i can't find what is missing im my code: I creared Custom User from AbstractBaseUser, so my model is like: settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ] AUTH_USER_MODEL = 'users.User' AUTHENTICATION_BACKENDS = [ 'users.backends.CustomModelBackend', ] models.py class UserManager(BaseUserManager): def create_user(self, email, username, phone, password = None): ... def create_superuser(self, email, username, phone, password = None): ... class User(AbstractBaseUser, PermissionsMixin): ... objects = UserManager() ... def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True backends.py class CustomModelBackend(backends.ModelBackend): def user_can_authenticate(self, user): return True In shell i try something like: >>> from users.models import User >>> user_test = User.objects.get(email="user@example.com") >>> user_test.get_all_permissions() set() That user is superuser. What is needed to check that permissions? -
Filter for several items of the same field Django
I have a view like this: class ProductViewSet(viewsets.ModelViewSet): ... filter_class = ProductFilter and ProductFilter: class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = ['brand'] the problem is that when I send a GET /products/?brand=Adidas+Nike, I get an error [ "Select a valid choice. Nike Adidas is not one of the available choices." ] How can I fix it that it will filter for several items of the same field. -
django filter a prefetch_related queryset
I am trying to use prefetch_related with a model with foreign key because I then need to query the database within a loop. models.py class SelfEvaluatedStatement(models.Model): evaluation_statement = models.ForeignKey(EvaluationStatement, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default=0) views.py queryset = SelfEvaluatedStatement.objects.prefetch_related( 'evaluation_statement__sku__topic__subject', 'evaluation_statement__sku__level' ).filter( evaluation_statement__sku__topic__subject=subject, evaluation_statement__sku__level=level ) for student_user in student_users: red_count = queryset.filter(user=student_user, rating=1).count() However, this hits the database with a new query each time I iterate through the loop. Is it possible to filter a queryset which has been prefetched, or am I thinking about this incorrectly? -
Getting and Resuming from Process ID in Python 3
I am developing a testapp in django for internal computing usage. I am using Octave (open source version of Matlab). The idea is to give the user a web interface, where user will type commands, and the commands will go to backend, get executed in octave, and return the results. And the key is to remember the values of all variables that the user has set previously without any recourse to database as octave does it automatically. The problem I am facing is that once I return from backend, I loose the parameter values. In essence, I create a shell process in django view using import subprocess; subprocess.run('a=2'). I capture the output and send it back to UI. And lets say user sends another command subprocess.run('a = a + 2'). But this time when I try to execute in backend, I am going to get error, because the value of parameter a is lost!! To make matters worse multiple users can access this app at the same time with their own set of data and operations. Now my question how can I get process ID of shell created using python, and resume later on using the same process ID and … -
Ajax url with parameter. The current path didn’t match any of these
I'm new in django. I try to delete element from database by ajax call. My ajax call send url with parameter which is pk of element to delete. Url looks fine but browser raise error that url pattern doesn't match to any of urlpatterns in my url.py. I have done similar project before and everything workerd good so I'm confused why it does't work now. Any Idea? urls.py: urlpatterns = [ path('', views.home,name='home'), path('mojerec',views.mojeRec,name='mojerec'), path('dodajrec',views.dodajRec,name='dodajrec'), path('receptura/(<int:receptura_id>)',views.receptura,name='receptura'), path('formJson/<str:skl>/', views.formJson, name='formJson'), path('receptura/formJson/<str:skl>/', views.formJson, name='formJson'), path('receptura/dodajskl/<str:sklId>/', views.dodajsklJson, name='dodajsklJson'), path('receptura/aktualizujTabela/<str:sklId>/', views.aktualizujTabela, name='aktualizujTabela'), path('receptuta/delSkl/<int:id>/', views.delSkl, name='delSkl'), ] views.py def delSkl (request,id): deletedElement=Skladnik.objects.filter(pk=id) response=serializers.serialize("python", deletedElement) deletedElement.delete() print('response', response) sys.stdout.flush() return JsonResponse({'response':response}) myjs.js function usuwanieSkladnika (pk){ $.ajax({ type: 'GET', url: `delSkl/${ pk }/`, success : function(response){console.log('sukces ajaxa z del'); cardBox.innerHTML='' tabelaDocelowa.innerHTML=''; updateTable() },//koniec sukcesa error : function (error){console.log('brak sukcesu ajaxa z del')}, }) } log: Page not found (404) Request Method: GET Request URL: http://localhost:8000/receptura/delSkl/13/ Using the URLconf defined in recipe.urls, Django tried these URL patterns, in this order: admin/ [name='home'] mojerec [name='mojerec'] dodajrec [name='dodajrec'] receptura/(<int:receptura_id>) [name='receptura'] formJson/<str:skl>/ [name='formJson'] receptura/formJson/<str:skl>/ [name='formJson'] receptura/dodajskl/<str:sklId>/ [name='dodajsklJson'] receptura/aktualizujTabela/<str:sklId>/ [name='aktualizujTabela'] receptuta/delSkl/<int:id>/ [name='delSkl'] users/ The current path, receptura/delSkl/13/, didn’t match any of these.