Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
400 (Bad Request) on an Ajax POST request using Django Rest Framework
I thought I'd ask this here as I'm not too sure where I am going wrong. I am trying to do a POST request via AJAX using Django Rest Framework Class. However, I am getting the following error whenever the event fires: OST http://127.0.0.1:8000/api/uservenue/ 400 (Bad Request) This is what is appearing in the Stack Trace: {"list":["This field is required."],"venue":["This field is required."]} Context I am trying to make it so when a user clicks an "add-to-list" button it sends a cafeName (and eventually other details) to a user defined list. I'm wondering if someone could take a look at my code and give me some guidance as to where I am going wrong? The Code Here is the relevant model: class UserVenue(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) list = models.ForeignKey(UserList, on_delete=models.PROTECT) Here is the relevant serializer.py class UserVenueSerializer(serializers.ModelSerializer): class Meta: model = UserVenue fields = ['list', 'venue'] Here is the relevant URLs router = DefaultRouter() #need help understanding router register router.register('userlist', views.UserList) router.register('uservenue', views.UserVenue) Here is the relevant views.py class UserVenue(viewsets.ModelViewSet): serializer_class = UserVenueSerializer queryset = UserVenue.objects.all() @ensure_csrf_cookie def get_queryset(self): cafeName = self.request.GET.get('cafeName', None) print(cafeName) return UserVenue.objects.all() And, finally, here is the ajax call with the CSRF code incl. var … -
Django admin panel does not have a standard form
Django admin panel does not have a standard form I'm trying to deploy my site on VPS - debian 10, django 3.1, but the admin panel does not have a standard form -
How can i write an API about listing something between two dates in django?
probably it's quite simple but i've never write an api before so i am stucked. I've 2 datepicker area to choose dates like this; <div> <label>Starting Date</label> <input id="startDatePicker" type="text" class="form-control datepicker" autocomplete="off"> </div> <div class="mx-2"> <label>Ending Date</label> <input id="endDatePicker" type="text" class="form-control datepicker" autocomplete="off"> </div> <a onclick="???" class="btn btn-info" href="javascript:void(0);"> Show <i class="fas fa-caret-right"></i></a> And my models: class Fund(models.Model): name = models.CharField(max_length=500, null=False, blank=False, verbose_name="Fund Name") code = models.CharField(max_length=5, null=False, blank=False, verbose_name="Fund Code") management_price = models.CharField(max_length=15, null=True, blank=True, verbose_name="Management Price") performance_price = models.CharField(max_length=15, null=True, blank=True, verbose_name="Performance Price") explanation = models.TextField(max_length=1000, null=True, blank=True, verbose_name="Explanation") class FundData(models.Model): fund = models.ForeignKey(Fund, on_delete=models.CASCADE, related_name="data_of_fund", verbose_name="Fund") date = models.DateField(auto_now_add=False, editable=True, blank=False, verbose_name="Date") price = models.FloatField(max_length=15, blank=False, verbose_name="Fund Price") Here is my table needs to be fill: <table id="fundReturnsTable" class="table table-striped table-bordered mt-2" style="width:100%; display:none"> <thead> <tr> <th>Fund Code</th> <th>Fund Name</th> <th>Starting Date Price</th> <th>Ending Date Price</th> </tr> </thead> <tbody> <tr> <th>example.FundCode</th> <th>example.FundName</th> <th>example.FundreturnEnterdateprice</th> <th>example.FundreturnNowdateprice</th> </tr> if nothing shows up <tr> <th colspan="6">There are no datas between this dates.</th> </tr> </tbody> What i am trying to do is, user will choose dates and see which fund has what price in that dates. Ask any detail you need to know i'm quite newbie on asking things here, … -
Django Rest Framework GET request returning Unathorized on React Frontend
it's my first question of SO. please, point out where I need to clarify at any point. Im building a django back-end, react front-end app. I have this view that returns a 401 response whenever I try to directly access it on the front-end, even when a user is logged in. I have access to my other views but this one. It works fine in the drf browsable API. I'm using both Session and TokenAuthentication in my default authentication classes. -
How do I stop all of my projects redirecting to a specific URL?
I have been trying to learn Django to build a personal website where I can host some machine learning stuff I've made for others to use. In the process, I found this tutorial by Mozilla. I think what created the issue was the part saying RedirectView.as_view(url='catalog/', permanent=True). I was trying to make a simple function grapher for my site, so I used 'grapher/' instead of 'catalog/'. Now, that worked for what I was trying to do. Then I created a new django project to try some things from a different tutorial, and now when I try to run "py manage.py runserver" and go to http://localhost:8000, I still get redirected to http://localhost:8000/grapher/. This happens in all of my django projects, new and old. Now, the really mysterious part to me was that when I tried deleting those projects AND the virtual environments I was using, then making a new virtual environment and project, I still get redirected http://localhost:8000/grapher/. I have also tried adding "path('', RedirectView.as_view(url='', permanent=True))," to my project.urls.py file which did not work. If there are some commands I can run to give more information, I would love to. I just don't know what other detail I can post since … -
How do I convert .md files from zip files to url links in django using markdown2?
I'm working on how to convert .md files that I extracted from a folder for a project where I create a Wikipedia webpage (with search engine). I have been trying to use markdown on .md files and convert them to viewable and working url links on the webpage, but have had little success. How should I convert them so that they fit in the "a href" tag properly? I'm wondering what it should look like when I convert and if I should use the Path: C:\Users\17346\Desktop\CS50Project01\wiki\entries\Python.md or the Relative path: entries\Python.md ? -
can a django app in development be used directly onto production
Being a newbie to django and python, i managed to create a small project. I understand this way is the development phase. If i wish to put this work from development phase into production, would Django's inbuilt server capable enough to handle the requests? Is it not mandatory to keep development and production separate? -
Django heroku app still presenting SMTPauthentication error yet gmail access to less secure apps is on
I made sure my gmail credentials to use for smtp are correct and allow access to less secure apps is turned on but I am still facing SMTPauthentication error. on doing some research on other similar questions asked I came across this: but how do I visit the DisplayUnlockCaptcha URL shown in the screeshot above from my Heroku app IP so that gmail can recognize it and stop blocking it ? -
Django Form ignores translation and falls back to default
I have recently introduced translation (i18n) to my django app. It works fine for all templates and error messages. Not for forms unfortunately. It always falls back to English, even if the rest of the page is shown in German. settings.py: LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = True forms.py: from django import forms from django.utils.translation import gettext as _ from django.conf import settings from django.core.validators import DecimalValidator, MaxLengthValidator, EmailValidator, MinLengthValidator class AccountCompanyNameForm(forms.ModelForm): # adding some default validators phone = forms.CharField(validators=[MinLengthValidator(10)], error_messages={'invalid': _("Bitte geben Sie eine gültige Rufnummer an.")}) name = forms.CharField(label=_("Vorname Nachname"), validators=[MinLengthValidator(3)], error_messages={'invalid': _("Bitte geben Sie Ihren Vor- und Nachnamen ein.")}) company = forms.CharField(label=_("Firma"), validators=[MinLengthValidator(3)], error_messages={'invalid': _("Bitte geben Sie den Namen Ihrer Firma an.")}) birthdate = forms.DateField(label=_("Geburtsdatum"), error_messages={'invalid': _("Bitte geben Sie das Datum im Format 01.01.1990 ein.")}) terms = forms.BooleanField() Template code: {% load i18n %} {% load widget_tweaks %} ... {% render_field form.company placeholder=form.company.label class+="form-control" %} ... {{ form.company.label }} Even the form.company.label is in English. German translation is there and correct. Any help is appreciated. -
DJANGO use of static files in combination with paths references
I've posted something similar earlier without being able to find a suitable solution. One of the things I am struggling with is the ability to serve static path / file references within DJANGO html templates. Hopefully, by posting another question I will be able to understand how this works. Done quite some research and read through the DJANGO documentation without being able to find something covering my scenario. Here we go: Within my model I use a path reference field class Product_images(models.Model): product = models.ForeignKey(Products, on_delete=models.SET_NULL, blank=True, null=True) path_to_image = models.CharField(max_length=150,null=True, blank=True) name = models.CharField(max_length=50,unique=False,blank=True) class Meta: verbose_name = 'Product Image' verbose_name_plural = 'Product Images' def __str__(self): return '{} - {} - {}'.format(self.pk, self.product, self.name) The value of this field is set to (example): static\images\Product\PowerBI\Receivables\Receivables 6.png The files are physically stored within the app Main/static/.... My setting file contains: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'Main/') MEDIA_URL = '/Main/' Then I have two templates within the app where I want to serve these images. One page uses a custom context processor in the following way: {{ product_section }} Which returns html including: html_value += u'<img class="d-block w-100" src="{}" width="400px" height="250x" alt="{}">'.format(productimages_obj.path_to_image,productimages_obj.name) This context processor tag is … -
Django channels: Save messages to database
I'm a newbie to channels and I made a chatroom application by following their official documentation. Now I'm trying to save the chat messages. All I know is I can create a model but Idk how to save it from the consumers.py into my database. I added username along with the message. A little help would be appreciated. My Consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): username = self.scope["user"].first_name name = self.scope['user'].username text_data_json = json.loads(text_data) message = text_data_json['message'] message = (username + '(' + name + ')' + ':\n' + message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): username = self.scope["user"].username message = event['message'] name = self.scope["user"].username # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, "username": username, "name": name })) My model to save the msgs: class Message(models.Model): author = models.ForeignKey(User, related_name='messages', on_delete=models.CASCADE) context … -
Deployment Django Ideas
I developed an Social Media app using Django. I want a good way to deploy it so that it would work well no matter of number of the users using it, or the media uploaded. What's an good way do deploy it ? -
how do i edit other users profile on django
i have two separate users, i want some users to be able to modify other users profile. The problem i am facing now is how to get the users id. i have a 2 views involved in this. The profile view, the edit profile view. i tried to wrap the entire profile html in a form, i am not sure that will work. most of the examples only show how to edit current(logged in) user's profile. the link to a specific users profile (http://127.0.0.1:8000/dashboard/profile/dfrtgy-ehehh/16) the profile page has a link to the edit profile page. profile html <li> <a href="{% url 'editprofile' %}"><img class="nav-items" src="{% static 'images/lab.svg'%}" alt=""><span>Edit profile</span> </a> </li> views.py def edit_profile(request): if request.method == 'POST': profile = Profile.objects.get(pk=pk) form = EditProfileForm(request.POST, instance=request.user.profile) if form.is_valid(): form.save() return redirect(f'/dashboard/profile/{request.user.profile.slug}/{request.user.pk}') else: form = EditProfileForm(instance=request.user.profile) args = {'form': form} return render(request, 'core/editprofile.html', args) def profile(request, slug, pk): profil = Profile.objects.get(slug=slug) profile = Profile.objects.get(pk=pk) context = {'profile': profile, 'profil': profil} return render(request, 'dashboard/profile.html', context) urls.py urlpatterns = [ path('', dashboard, name='dashboard'), path('profile/', profile, name='profile'), path('profile/<str:slug>/<int:pk>', profile, name='profilepk'), path('edit_profile/', edit_profile, name='editprofile'), -
how to improve the rendering time of a PDF file?
I have a django web platform hosted on digital ocean, the platform works fine, but rendering large pdf files (average 100MB) takes a long time (average 1:30 min) These are the resources in digital ocean: -2 vCPUs 4GB/80GB Disk How can we improve rendering time? This is how it looks when it takes time to render the pdf (disable the main menu of the pdf to avoid downloads) -
Heroku throughput extremely high for no reason
I have developed a very basic site for a hosting an online cryptic hunt. Used Django and deployed it on heroku. It went live a couple days ago and just recently it went down and the logs mentioned an h11 error - "backlogs too deep". I checked the metrics and noticed a massive spike in the throughput. It read that the requests were exceeding 200k. Why is this happening? I've tried upscaling the dynos but it's going to get really expensive. We barely have 30-40 users but the metrics show that we're getting over a million requests in a day. The site just won't come out of the application error. -
Django - Can I delete apps static files after running collectstatic
From this answer, collectstatic is a ready-made script that prepares this directory for you, so that you can connect it directly to your deployment script. After running the collectstatic command, all static files in my apps are copied to a static folder in the root of my project. Can I delete the static folder in my apps? Since they are copied already. I kind of felt like it's just duplicating and costing me file size or am I missing something? I deleted the static folder in my apps but it does not work anymore. Why duplicating my static files then or can I delete them after going live? -
Docker running manage.py results in segmentation fault
I am running Django in a docker on a raspberry pi 4b with 8gb ram. When docker runs my startup script that includes some commands with python3 manage.py ... Django crashes with a segmentation fault AFTER executing the command successfully. The simplest way of recreating this behaviour is: Log into docker shell: docker exec -it django_backend /bin/bash Go into venv and then run: python3 manage.py This lists all the options for manage.py as expected and then immediately after results in a segfault. Output: Type 'manage.py help ' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser ... Segmentation fault (core dumped) Memory is definitely not the issue, less than 20% of the available memory is in use. I tried multiple resets of the whole system. I also tried this on two other machines with 8GB ram and there I don't get a segfault. Any ideas what could be the reason for this or how I could test for possible reasons? -
Django DetailView queryset returns an empty list
DetailView queryset returns on full name which I suspect is coming from the model's __str__ method. class EmpDetail(DetailView): template_name = 'users/emp_detail.html' model = Employee context_object_name = 'employee' I tried this and it gets me what I need but the id is hard coded in, I don't have access to kwargs: def get_object(self, queryset=None): employee = Employee.objects.filter(user=self.request.user, id="1").values('full_name', 'val2', 'val3', ... ) return employee Then I tried this but it returns an empty list. def get_context_data(self, **kwargs): context = super(EmpDetail, self).get_context_data(**kwargs) pk_= self.kwargs.get("id") context['employee'] = Employee.objects.filter(pk=pk_).values('full_name', 'val2', 'val3', ... ) return context How do I make a query in DetailView and pass it to template? -
how to override error_message in model or model form?
Sorry for my English. Unfortunately, I can't find a solution on the forum and in google. I ask you to help me figure out how you can override error_mesage in ModelForm or Model. It is necessary that instead of the standard message during validation, it shows the message that I define. I constantly get a message instead of mine "Please fill out this field". Don't be too harsh, I'm a beginner. Please, if possible, explain in detail and with an example. Thanks! Below is the code that I used. Form class PersonForm(ModelForm): class Meta: model = Person fields = ('name', 'mood') error_messages = {'name': {'invalid': 'Мое сообщение об ошибке', 'blank': 'Мое сообщение ' 'об ошибке', 'null': 'Мое сообщение об ошибке'}} Views def exp_index(request): if request.method == 'POST': pForm = PersonForm(request.POST) if pForm.is_valid(): pForm.save() persons = Person.objects.all() pForm = PersonForm() add_message = 'Можете добавить еще одну запись!' context= {'person': persons, 'form': pForm, 'add_message': add_message} return render(request, 'exp/exp_index.html', context) else: persons = Person.objects.all() error_message = 'Неверно указали данные, попробуйте еще раз!' context= {'person': persons, 'form': pForm, 'error_message': error_message} return render(request, 'exp/exp_index.html', context) else: pForm = PersonForm() person = Person.objects.all() context= {'person': person, 'form': pForm} return render(request, 'exp/exp_index.html', context) Model class Person(models.Model): l=[[None, … -
how create a view class include all function in django view
For example i have a admin app in a django project. I have 2 view function in views.py like as views.py from django.shortcuts import render, redirect from .models import Manager def admin_home(request): manager = 'manager' context ={ 'manager':manager, } return render(request, 'home/index.html', context) def admin_show(request): manager = Manager.objects.all() context ={ 'manager':manager, } return render(request, 'home/index.html', context) But i want to write both function in a class. like as from django.shortcuts import render, redirect from .models import Manager from django.views import View class AdminPart(View): def admin_home(request): manager = 'manager' context ={ 'manager':manager, } return render(request, 'home/index.html', context) def admin_show(request): manager = Manager.objects.all() context ={ 'manager':manager, } return render(request, 'home/index.html', context) Isn't it possible in django like as python class. please help me.... -
How to determine particular page types for a wagtail default search?
The regular wagtail search, included by default, searches over all pages of the project. How can i determine particular Pages for the search indexing? -
How to get total count of many to many field to a Django model?
This is a Blog model, how do I get the total count of likes from overall blog objects? class Blog(models.Model): title = models.CharField(max_length=160) ... likes = models.ManyToManyField( User, related_name='likes', blank=True, default=None) In the template, I can use user.likes.count and it will return total like count of a single user but how I do I get total like count from all users. Thank You -
Removing Django notification by disconnecting signal in django-notifications-hq
I am intending to remove a notification in the django-notifications-hq package by disconnecting the signal in my views after a signal is created: As an example: def view1: notify.send(sender=user, recipient=other_user, verb=message, target=object) return redirect('app:page') def view2: notify.disconnect(sender=user, reciever=other_user) return redirect('app:page2') user and other_user are the same users in this example This will disconnect all signals between user and other_user, what I intend to do is to only disconnect the signal created between those users for that specific object. I have already looked into the source code and I cannot find how I can manage to do such a thing. For your reference, the GitHub link is: https://github.com/django-notifications/django-notifications Also this is the Signals file in that package: ''' Django notifications signal file ''' # -*- coding: utf-8 -*- from django.dispatch import Signal notify = Signal(providing_args=[ # pylint: disable=invalid-name 'recipient', 'actor', 'verb', 'action_object', 'target', 'description', 'timestamp', 'level' ]) -
Select2 passing only one select to the form in Django
I'm using Select2 for a multiple select for tags. I'm using Taggit for the tags. The problem is that if a user chooses more than one tag, then just one is passed to the form. My select HTML: <select class="custom-select js-example-basic-multiple form-control " id="select-tags" name="usertags" multiple="multiple"> {% for tag in userTags %} <option value="{{ tag }}" data-id="{{ tag.color }}" class="options">{{ tag }}</option> {% endfor %} </select> My form: class FileUploadForm(forms.ModelForm): class Meta: model = Uploaded fields = ( 'name', 'file', 'usertags', ) Views.py if request.method == 'POST': form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user user = request.user form.save() -
django pagination error: AttributeError: 'WSGIRequest' object has no attribute 'Get'
I am having a hard time with django pagination. Can someone help me out with this? This view is returning an error: def view_homePage(request, user): if user == 'all': posts = Post.objects.order_by("-timestamp").all() paginator = Paginator(posts, 2) ERROR ---> page_number = request.Get.get('page') or 1 page_obj = paginator.get_page(page_number) return JsonResponse([post.serialize() for post in page_obj], safe=False) The error I am getting is: AttributeError: 'WSGIRequest' object has no attribute 'Get' If I remove the line and just set page_number = 1 for testing I have a new set of issues. How do I actually pass the page number to the view from the html page? I tried adding this for testing, but it does not work: <nav aria-label="..."> <ul class="pagination"> <li class="page-item"><a class="page-link" href="?page=3">3</a> </li> </ul> </nav> On the above code I hard coded page 3 just for testing, but it does not get into the view. How do I go about this? The django documentation is lacking in this regard.