Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the propper way to debug gunicorn?
I am trying to deploy my very first Django applicatin on heroku. Gunicorn gives me this error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> In this answer https://stackoverflow.com/a/55623889 command gunicorn app:application --preload -b 0.0.0.0:5000 is said to give detailed error message, but as its comments state it is not clear what words to replace with what. For instance somewhere I saw something similar called with <name of my app>.wsgi. To make matter worse name of my Django app in local is different from the one on Heroku. Also it is not clear to me should this be called strait from terminal (within virtual env) or should I be using some sort of gunicorn CLI. So what is the actual propper way to figure out what is failing gunicorn? -
display templates for each user Django
I have a side bar made up of 2 nav-items, during authentication I want parts of it to be visible to users, for example: user1: can see only the management part user 2: can see only the prediction part user3: can see only the management and prediction part I tried using pemrissions but that didn't work. but I think that's not what I'm looking for (permissions are related to models) I have no idea how to do it this way, An idea? -
How to use fetch data in another query
I transfer data from js to django by means of fetch post. I accept this data in a separate function. def fetch_post(request): context = { 'data': request.body } return HttpResponse() I need to pass this view data and create a context with the data from another function. class OrderTicketView(TemplateView): template_name = 'train_app/order_ticket.html' form = OrderTicketForm def get(self, request): context = { 'form': self.form, } return render(request, self.template_name, context=context) def post(self, request): context = { 'req': request.POST } return render(request, self.template_name, context=context) How to do it? -
how do I send a POST request via the command line in windows
I'm following this TUTORIAL for JWT in DJANGO here: https://www.geeksforgeeks.org/jwt-authentication-with-django-rest-framework/ I'm stuck because we are to make a POST request vial the command line. The tutorial is for Linux. How do I make an equivalent call on Windows via command line using the following $ http post http://127.0.0.1:4000/api/token/ username=spider password=vinayak I know in windows we would start with curl, but then I've tried multiple things such as curl -X POST .... and get errors. such as: Invoke-WebRequest : A parameter cannot be found that matches parameter name 'X'. At line:1 char:6 Thank you -
Django Rest Framework reverse serializer
Please I need a little help. I have a model like below class Person(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) class Employee(models.Model): person = models.ForeignKey(Person, related_name='employee') code = models.CharField() In my EmployeeSerializer, how can I add the Person field Something like: class EmployeeSerializer(serializer.ModelSerializer): person = # Something the get **Person** instance code = serializers.IntegerField class Meta: model = Employee fields = [ 'id', 'person', 'code' ] -
Django - Edit referer when redirect
I'm using django3.1 with python3.6 I want to add a referer when redirecting URL. I'm using this code now, however, there is noting in referer. response = HttpResponseRedirect(target_url) response.set_cookie('name', name, max_age=9999, domain=None, samesite='None', secure=True) response['HTTP_REFERER'] = 'https://example.com' return response Is there any problem with my code? or it is impossible to add referer? -
RabbitMQ with Django Project and Scrapy to Push and Comume Message's
I've Django application that is working with Celery and using RabbitMQ as message broker. I've separate project for scrapy from where I scraped data and want to push this scrapped data into rabbitMQ then django will consume this RabbitMQ message's through celery. I need help to consume the message that pushed in rabbitMQ from scrapy project. code snippet. scrapy def process_item(self, item, spider): publish_message(item) return item def publish_message(data): import pika connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost', port=5672)) channel = connection.channel() channel.basic_publish(exchange='topic', routing_key='scrapy', body='Hello From scrapy!') connection.close() In django app, consumers.py import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', heartbeat=600, blocked_connection_timeout=300)) channel = connection.channel() def callback(ch, method, properties, body): print(" data =============== ", data) # I will call celery task here once code print the data to make sure its running. unfortunately its not running. :( return channel.basic_consume(queue='scrapy', on_message_callback=callback, auto_ack=True) print("Started Consuming...") channel.start_consuming() connection.close() celery.py from kombu import Exchange, Queue os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings.development') celery_app = Celery('my_project', broker='amqp://guest:guest@rabbit:5672', backend='rpc://0.0.0.0:5672') celery_app.config_from_object(f'django.conf:settings', namespace='CELERY') celery_app.autodiscover_tasks() celery_app.conf.update( worker_max_tasks_per_child=1, broker_pool_limit=None ) default_exchange = Exchange('default', type='topic') scrapy_exchange = Exchange('scrapy', type='topic') celery_app.conf.task_queues = ( Queue('scrapy', scrapy_exchange, routing_key='scrapy.#'), ) -
posts.models.Blog.DoesNotExist: Blog matching query does not exist
i am trying to use slug to navigate. here's the html tag <a href="{% url 'blog_details' blog.slug|slugify %}">Read More</a> urls.py path('details/<slug:slug>/', views.blog_details, name='blog_details'), models.py slug= models.SlugField(max_length=264,unique=True,null=True,allow_unicode=True) this is how i am creating auto slug def Creating_blog(request): form=BlogForm() if User.is_authenticated: if request.method=='POST': form=BlogForm(request.POST,request.FILES) if form.is_valid: blog_obj=form.save(commit=False) blog_obj.author=request.user title=blog_obj.blog_title blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4()) blog_obj.save() return redirect('index') return render(request,'blogs/creatingblog.html',context={'form':form}) this is the view of the blog details page def blog_details(request, slug): if User.is_authenticated: blog = Blog.objects.get(slug=slug) already_liked = Likes.objects.filter(blog=blog, user= request.user) if already_liked: liked = True else: liked = False comments=Comment.objects.filter(blog=blog) commet_form=CommentForm() if request.method=='POST': commet_form=CommentForm(request.POST) if commet_form.is_valid(): comment=commet_form.save(commit=False) comment.user=request.user comment.blog=blog comment.save() return HttpResponseRedirect(reverse('blog_details',kwargs={'slug':slug})) return render(request,'blogs/blogdetails.html',context={'blog':blog,'comment_form':commet_form,'comments':comments,'like':liked}) else: HttpResponseRedirect(reverse('login')) the problem is must be in C:\Users\ITS\Desktop\blogger\Blog\posts\views.py, line 51, in blog_details blog = Blog.objects.get(slug=slug) if i use pk=id instead of slug, it works. But whenever i am trying to catch with the slug the error rises. i am stuck for days here i can't find what's wrong. -
audio controls doens't appear while pass file from local storage - DJANGO
i want to pass audio file to template html from url. but when i add source, the audio controls doesn’t work or appear. so please help me to fix this. at my terminal and console, there’s no error message. i was using models to get the file to local storage. and here's my code: html: {% for record in rec %} <audio controls> <source src="{{record.audio.url}}" type="audio/mp3"> </audio> {% endfor %} views.py : def mp3_audio(request): rec = Audio_store.objects.all() return render(request, 'homepage.html' , {'rec': rec } ) models.py : from django.db import models from django.core.files.storage import FileSystemStorage from django.forms import widgets fs = FileSystemStorage(location='media/mp3') fss = FileSystemStorage(location='media/txt') class Audio_store(models.Model): password=models.FileField(storage=fss, null=True) audio=models.FileField(storage=fs, null=True) -
How to customize default user model fields django
I want to extend Django's User Model to include the fields DOB, Gender, Address and PhoneNo. This is what my Serializers.py file looks like: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings class UserSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) # DOB = serializers.DateField( # required=True # ) # address = serializers.CharField( # required=True, # max_length=60 # ) # contactNo = serializers.IntegerField( # required=True, # # max_length=11 # ) password = serializers.CharField( required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model = User fields = ( 'token', 'username', 'password', 'first_name', 'last_name', 'email', # 'DOB', # 'gender', # 'address', # 'contactNo', 'id' ) As you can see, I tried doing it through it, but that didn't work.. I also tried using OneToOneField() in models.py file to include the extra fields (it was empty and had no code) … -
How to fail a custom data migration?
I have written a data migration that initializes new tables with some rows. The objects have foreign keys to other tables, so I have to check that the foreign ids exist. If they don't, I would like to stop the migration with a error message. I have written two functions: forward and reverse. What is a recommended way of stopping a migration from within forward? def forward(apps, schema_editor): ... def reverse(apps, schema_editor): ... class Migration(migrations.Migration): dependencies = [ ("my_app", "0001_initial"), ] operations = [ migrations.RunPython(code=forward, reverse_code=reverse) ] -
django migration throws date format error
Trying to migrate using the following models.py from django.db import models from django.utils.text import slugify from django.utils import timezone # Create your models here. CATEGORY_CHOICES = ( ('action','ACTION'), ('drama','DRAMA'), ('comedy','COMEDY'), ('romance','ROMANCE'), ) LANGUAGE_CHOICES = ( ('english' , 'ENGLISH'), ('german' , 'GERMAN'), ) STATUS_CHOICES = ( ('RA' , 'RECRNTLY ADDED'), ('MW' , 'MOST WATCHED'), ('TR' , 'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') banner = models.ImageField(upload_to='movies_banner') category = models.CharField(choices=CATEGORY_CHOICES , max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES , max_length=10) status = models.CharField(choices=STATUS_CHOICES , max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() created = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank=True, null=True) def save(self , *args , **kwargs): if not self.slug : self.slug = slugify(self.title) super(Movie , self).save( *args , **kwargs) def __str__(self): return self.title LINK_CHOICES = ( ('D' , 'DOWNLOAD LINK'), ('W' , 'WATCH LINK'), ) class MovieLinks(models.Model): movie = models.ForeignKey(Movie, related_name='movie_watch_link', on_delete=models.CASCADE) type = models.CharField(choices=LINK_CHOICES , max_length=1) link = models.URLField() def __str__(self): return str(self.movie) views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.dates import YearArchiveView from .models import Movie, MovieLinks # Create your views here. class HomeView(ListView): model = Movie template_name = 'movie/home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['top_rated'] … -
Django : customizing FileField's current file in templates
I am rendering a simple form with a file field. class ReviewForm(forms.ModelForm): class Meta: model = Review fields = [ 'file', ] widgets = { 'file': forms.FileInput(attrs={'class': 'form-control'}), } While rendering, the form shows Current file - xyz.pdf besides the file input. However, I do not allow direct access to the files. All requests goes through the analytics_logger function before loading the file. So, I want to customise the Current file html from Current file - <a href="{0}">{1}</a> to Current file - <a href="{% url 'analytics_logger' {0} %}">{1}</a> How can I do it in Django 3.x? -
How to check validation on put method in django DRF
How to Perform Object-level validation in Django DRF PUT Method POST method It is working perfectly def validate(self, data): if len(data['name']) == len(data['discription']): raise serializers.ValidationError("Movie name and Discription are equal!") elif len(data['name']) > 10 : raise serializers.ValidationError("name is too big") return data -
Toggle nav-link active state in django
For changing the .nav-link activate state I wrote $(".nav-link").on("click", function(){ $(".nav-link.active").removeClass("active"); $(this).addClass("active"); }); But this won't work because the page reloads when clicking on the .nav-link. I can do something like var current_url = location.href; if (current_url == https://xyx.com/home) { $('.nav-link.home').addClass('active'); } else { $('.nav-link.home').removeClass('active'); } But when I was looking for another method I found this <li class="nav-item"> <a href="{{ route('home') }}" class="nav-link dropdown-toggle {{ request()->routeIs('home') ? 'active' : '' }}">Home</a> </li> <li class="nav-item"> <a href="{{ route('about') }} " class="nav-link {{ request()->routeIs('about') ? 'active' : '' }}">About</a> </li> This is Laravel code but I am looking something like this for Django. -
Handling JsonResponse in Django template
I'm trying to make a webpage in which you can specify a number of vectors, then insert modulus and angle for each one, and it will calculate the sum. My code can do the calculation, but I can't properly display the result on my template. views.py: def sum_view(request): if request.method == "POST": message = '' for j in range(2,12): if not request.POST.get(f'vector_mod_{j}'): num_vett = j - 1 result = Vector(0, 0) for i in range(num_vett): mod = float(request.POST.get(f'vector_mod_{i+1}')) ang = float(request.POST.get(f'vector_ang_{i+1}')) result += Vector(mod, ang) message = f'Modulus: {result.modulus}, angle: {result.angle}°' return JsonResponse({'message': message}) return render(request, 'vectsum/sum.html') The problem is that when I submit I see a sort of firefox developer tools view with a menu including 'JSON', 'Raw Data', 'Headers', and the correct message displayed in a console-like way. Here is the ajax part of my template: $(document).on('submit','#calculate',function(e){ e.preventDefault(); $.ajax({ type:'POST', headers: {'X-Requested-With': 'XMLHttpRequest'}, url:'/vectorialsum/', data: $('#calculate').serialize() success:function(data){ var mess = JSON.parse(data)['message'] document.getElementById('result').innerHTML += mess } }) }); How do I show the message in my page? -
Using the URLconf defined in myapp.urls, Django tried these URL patterns, in this order
I think I went through every available answer to this error but they all reference some other tutorial and a views.py which I do not have. After running the tutorial from here I get this 404 error. Using the URLconf defined in myapp.urls, Django tried these URL patterns, in this order: admin/ ^$ [name='home'] ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, market_data/, didn’t match any of these. The urls.py has the following code: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.urls import re_path as url from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='templates/static_pages/index.html'), name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) The root directory structure of this project is ~/market_data/myapp ~/market_data/myapp/static_media ~/market_data/myapp/static_files ~/market_data/myapp/static_files/admin ~/market_data/myapp/templates ~/market_data/myapp/templates/static_pages Thank you for any tips! -
The current path, search/, didn’t match any of these
I can't find the source of this error. all my routes and view functions work except this one. ---- urls.py path('search/', views.search, name='search'), --- views.py def search(request): return HttpResponse('test search page') even when I use def search(request): return render(request, 'store/store.html') I still have the same error I've been struggling with this problem for several days. Here is the error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/search/ Using the URLconf defined in config.urls, Django tried these URL patterns, in this order: admin/ [name='home'] store/ cart/ ^media/(?P<path>.*)$ The current path, search/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. here is the complete code of my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.store, name='store'), path('category/<slug:category_slug>/', views.store, name='products_by_category'), path('category/<slug:category_slug>/<slug:product_slug>/', views.product_detail, name='product_detail'), path('search/', views.search, name='search'), And the complete code of my views.py from django.shortcuts import render, get_object_or_404 from category.models import Category from .models import Product from cart.views import _session_id from cart.models import CartItem, Cart from django.http import HttpResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # Create your views here. … -
Django rest elasticsearch filter range in url query params
I am using elasticsearch with django rest framework.I am using this lib: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/ I am trying to filter by price range according to this docs: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/ This is my views: class TestAPIView(DocumentViewSet): document = TestDocument serializer_class = TestSerializer queryset = TestModel.objects.all() filter_backends = [ FilteringFilterBackend ] filter_fields = { 'price': { 'field': 'price', 'lookups': [ LOOKUP_FILTER_RANGE, LOOKUP_QUERY_IN, ], }, } and this is my document.py file @registry.register_document class TestDocument(Document): price = fields.IntegerField(attr='price') class Index: name = 'TestModel' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } class Django: model = TestModel fields = [ 'id', ] When i hit on browser this url: http://127.0.0.1:8000/search/api/v1/test-model/?price=12 It works very well, even when i try with this url : http://127.0.0.1:8000/search/api/v1/test-model/?price=55 it works, I am facing problem to filter by range, like i want to filter price 12 to price 90, in this case how can i pass query paramter for the range? can anyone help me in this case? -
How i can convert csv file to ofx file in django application using python
i want to do a small application to convert my ".csv" files to ".ofx" files using django, where i can upload a file".csv" then press a button to convert it to ".ofx" with the same filename of the csv imported . this is my models.py: class Blog(models.Model): csv = models.FileField() filename = models.CharField(max_length=20) this is my views.py: from .forms import BlogForm import itertools as it from meza.io import read_csv, IterStringIO from csv2ofx import utils from csv2ofx.ofx import OFX from csv2ofx.mappings.default import mapping def UploadFile(request): if request.method == 'POST': form = BlogForm(request.POST,request.FILES) if form.is_valid(): form.save() ofx = OFX(mapping) records = read_csv('/home/mariana/virtualenv/django_project/mycsv.csv', has_header=True) groups = ofx.gen_groups(records) trxns = ofx.gen_trxns(groups) cleaned_trxns = ofx.clean_trxns(trxns) data = utils.gen_data(cleaned_trxns) content = it.chain([ofx.header(), ofx.gen_body(data), ofx.footer()]) myfield = form.cleaned_data.get("filename") print(myfield) print("saved") response = HttpResponse(content_type='application/ofx') response['Content-Disposition'] = 'attachment; filename=myfield.ofx' return response else: form = BlogForm() print("not saved") context = { 'form':form, } return render(request, 'pages/Upload.html', context) enter image description here after pressing the button(convet) there was a file downloaded('myfield.ofx') but it's empty that's mean the csv file doesn't converted to ofx file... Thanks in advance. -
static/rest_framework/css/bootstrap.min.css” does not exist
I got with Django rest framework problem when I deployed Django project in production mode if I go to http://127.0.0.1:8000/myproj/api/v1/persons.json everything is displayed correctly if I go to https://example.com/myproj/api/v1/persons.json?format=api - layout breaks in the page code I see: link rel="stylesheet" type="text/css" href="/static/rest_framework/css/bootstrap.min.css" if I navigate to the path https://example.com/static/rest_framework/css/bootstrap.min.css I see this error in the browser: Page not found (404) “/data/Projects/myproj_dev/Django/myproj/static/rest_framework/css/bootstrap.min.css” does not exist Request Method: GET Request URL: https://example.com/static/rest_framework/css/bootstrap.min.css Raised by: django.views.static.serve Using the URLconf defined in myproj.urls, Django tried these URL patterns, in this order: admin/ myproj/ ^static/(?P<path>.*)$ The current path, static/rest_framework/css/bootstrap.min.css, matched the last one. I tried to find the file bootstrap.min.css and found it along this path: /data/Projects/myproj_dev/Django/myproj_venv/lib/python3.8/site-packages/rest_framework/static/rest_framework/css/bootstrap.min.css, but I don’t know what to do with it Unfortunately, I was unable to solve this problem. If anyone knows what to do I would be grateful for advice P.S. Django Newb -
Search functionality using ajax with django
I want to search username in search box.When click on the button submit it should display the matched records without page load.How to implement this in django.Also here is pagination functionality.View is function based.It works fine with page reload.But I want to implement this using ajax call. -
Problem separating the repository into two independent projects on git
I made a mistake at the starting of a project, and that was to write a kivy project and the backend written with django rest in a same folder and repository (meaning the required libraries are both in the same venv too) and now that I want to deploy Django project I do not know how to separate these two projects (which includes libraries) and I do not see any solution. For example, is it possible to create two separate branches for it? And if so, how? And how do I manage and distribute the requirements.txt libraries?(Because the number of libraries is very large and about 200 libraries and the project size is huge. I do not know if more explanation is needed but I am very confused and really need help. Thankful -
python loop until length
so I'm having trouble getting some data to my DB. I'm not that good with python and trying to learn. so this is the data I'm sending to the Django server: as you can see I'm getting FILES called doc[i] to the server and I want to save the name of the file in the DB. but I don't know how to loop through it. that's what I'm doing for now: def submit_quality_dept_application(request, application_id): doc0 = request.FILES['doc0'] length = request.data['length'] application = Application.objects.get(id=application_id) application_state = application.application_state application_state['doc0'] = doc0.name Application.objects.filter(id=application_id).update( application_state=application_state) return Response(length, status=status.HTTP_200_OK) that way it's working for doc0 and I can save its name in the DB. but I want to loop through every doc[i] and save it in DB. any suggestions? -
Retrieve data from models having reverse relationship in django rest
I have 3 models where model A has foreign key of another in reverse order like:- class Book(models.Model): name = models.CharField(max_length=100) img=models.CharField(blank=True) category=models.CharField(max_length=100,null=True) class Section(models.Model): book= models.ForeignKey(Book, related_name='books', on_delete=models.PROTECT) title= models.TextField(null=True) class SubSection(models.Model): section=models.ForeignKey(Section, related_name='sections', on_delete=models.PROTECT, null=True) sub_title= models.TextField(null=True) I am trying to fetch all sections and subsections on the basis of book id. Before I was using nested serializer but nested serializer slow down its response. i am trying to achieve it with select_related can anyone help me with view query and serializer class. I want response like: data=[ "section": "A", "title": "intro", "subsection": [ { "id": 1, "sub_title": "title" } ] ]