Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deal with "remaining connection slots are reserved for non-replication superuser"?
I am working on a Django app using PostgreSQL as the back-end database. As per my understanding so far, if we do many concurrent calls of save() method, it raises the error remaining connection slots are reserved for.... To avoid this, in my views.py, I have set a limit of 50 concurrent calls of save() method. But, I am still facing the same error. I know this question has no code associated with it, but I am looking forward to your suggestions on how to handle this error. Thanks -
Trailing slash at end of DRF URL give 401
I'm using Django with DRF, DRF Simple JWT for authentication. I have problem that endpoint posts/ shouldn't require authentication, and this don't require when I don't append slash to end of URL. But when slash is at end of URL, this require authentication and when user is not logged in. Most of browsers append slash to end of URL (I'm using React + Axios). How to make that when appending slash to end of URL this still works without authentication? -
Django EmailField model not checking invalid email in Model
I have been working with Django for quite some time, but I am surprised to see that Django EmailField doesn't validate email addresses before inserting data into my database. I am currently using Django Rest Framework and below is my code. This is HTTP request to the server: POST http://localhost:8000/contact/ HTTP/1.1 content-type: application/json { "email" : "bad--//sample@gmail.com", "name" : "hi", "message" : "Hello" } My Django model: from django.db.models import Model, TextField, DateTimeField, EmailField from smavity.helpers.fields import NameField # Create your models here. class Contact(Model): name = NameField(max_length=20) email = EmailField() message = TextField() date = DateTimeField(auto_now=True) My Serializer class: from rest_framework.serializers import ModelSerializer from .models import Contact class ContactSerializer(ModelSerializer): class Meta: model = Contact fields = '__all__' -
How can i use a python code which adds two numbers in a webpage or website
I Would like to know that i have a python code which adds two numbers so is there a way that i make a website which will use my python code to add to number Thanks In Advance For Reply -
I trying to upload photo and resume to aws through django but I m not able to upload and my site is appearing without css
The code i have written in setting.py is given below:- I am already using static for css pupose I dont understand how to do it with aws Plz help me out AWS_ACCESS_KEY_ID = '*************' AWS_SECRET_ACCESS_KEY = '*************' AWS_STORAGE_BUCKET_NAME = 'upload' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = None #STATIC_URL = '/static/' #STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '//%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'mysite.storage_backends.MediaStorage' # Media files MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' -
Cannot upload media files on CPanel (using django)
I am not able to upload my media files on Cpanel. Initially I was able to upload files but now it shows Error 404 URL Not Found. The same code was working few days back but now it shows this error. There is nothing wrong with my code or my url. I have checked for permissions of directory in my CPanel File Manager (its 0755). I have specified + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my urls.py file. My settings.py is: MEDIA_ROOT = '/my/path/public_html/media' MEDIA_URL = '/media/' I am using Django=2.1 and CPanel Shared Hosting I know its recommended to have a web server to store and serve media files in Production Environment but it would be helpful if I get a solution of this error. -
How to make custom 404 page for the Detail view with <int:pk>, if the instance not found?
so the error is Page not found(404) when I am requesting the instance that does not exist. I would like to customize the 404 page, instead of displaying the general error. Here is my new_wiki/urls from django.urls import path from . import views from .views import IndexView, InstanceView, AddPostView, EditPost urlpatterns = [ # path('', views.index, name="index") path('', IndexView.as_view(), name="index"), path('instance/<int:pk>', InstanceView.as_view(), name="instance"), path('create_post/', AddPostView.as_view(), name="create_post"), path('instance/edit/<int:pk>', EditPost.as_view(), name="edit_post") ] And my InstanceView class class InstanceView(DetailView): model = Post template_name = 'new_wiki/instance.html' I have tried to use the solution from Django documentation: def detail(request, post_id): try: p = Post.objects.get(pk=post_id) except Post.DoesNotExist: raise Http404("Poll does not exist") return render(request, 'new_wiki/instance.html', {'post': p}) but it is still returning the same 404 page. Thank you -
SSL cert for AWS domain?
I have a backend service i'm running in Fargate. I need this service to have an SSL cert on its load balancer so that it can talk to other HTTPS services. I've created the load balancer and it gives me an AWS domain (my-cool-app.us-east-1.elb.amazonaws.com). Now, when I try to request a certificate through acm, it fails and says "Additional verification required". So i'm not sure if it's possible to add an SSL cert to this load balancer without registering a custom domain? Also, this is a Django app and I haven't done anything other than keep it as runserver which I know isn't good for production but I just need to start by making it work as a dev environment. Do I need to change the way Django runs in order for SSL to work? Or is the load balancer sufficient? -
Is there any way to run Shiny app directly hosted in Github
I used to maintain a Shiny app which was hosted in a private VPS provider with a monthly subscription fee. However unfortunately I recently laid-off due to Covid-19 pandemic, so am no longer in position to maintain that private VPS, and need to transfer my Shiny-app files to a cheaper location. I am wondering if Github can be used to host a Shiny-app. I am well aware about shinyapps.io, but this is too expensive for paid version, and the free version comes with many restrictions. Given my App is calculation intensive, shinyapps.io may not be a good alternative. As far as I know, with Github I can upload my App as bundle but user needs to run that App in his own machine having R installed. This is not a good option for me as well. Is there any possibility that User can just run my App by typing the App-address in the Browser, just like having my App hosted in a VPS? Is there any alternatives available for my case although sad (given that I no longer able to maintain a paid VPS.) Or, I am even fine to transition to some other software package (like django) if it … -
django model find where count on filter is minimum
Hi there I have A model which I save ip in four column: class IPAbstract(Audit): first = models.PositiveSmallIntegerField(validators=[MinValueValidator(1), MaxValueValidator(254)]) second = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(254)]) third = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(254)]) forth = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(254)]) class Meta: abstract = True which All my ips are start with 10.0.0.0,20.0.0.0,30.0.0.0,40.0.0.0 I want find which my ip range has minimum rows, i can do this: IPAbstract.objects.filter(first=10).count() IPAbstract.objects.filter(first=20).count() IPAbstract.objects.filter(first=30).count() IPAbstract.objects.filter(first=40).count() and compare them to each other to find which has minimum rows. I want see if there is there another way to find my answer? -
Django - Enforce setting only one of multiple fields in model
I have a model that associates image files with articles that I have written. # models.py class Image(models.Model): """A table to hold images for articles""" image = models.ImageField(upload_to='article_images', default="resources/dndicon.png", max_length=400) name = models.CharField(max_length=400, null=True, blank=True, help_text='A name describing the image') character_article = models.ForeignKey('Character', null=True, blank=True, on_delete=models.CASCADE) creature_article = models.ForeignKey('Creature', null=True, blank=True, on_delete=models.CASCADE) encounter_article = models.ForeignKey('Encounter', null=True, blank=True, on_delete=models.CASCADE) item_article = models.ForeignKey('Item', null=True, blank=True, on_delete=models.CASCADE) location_article = models.ForeignKey('Location', null=True, blank=True, on_delete=models.CASCADE) organization_article = models.ForeignKey('Organization', null=True, blank=True, on_delete=models.CASCADE) An Image object shall always only be associated with 1 single article. I wish to enforce this by using django's CheckConstraint functionality, though I'm open to alternatives outside of using generic relations. I stumbled over this blogpost and it seems to go in the direction I want. However, the solution proposed here is to create a Q object for every possible allowed combination that I would want. This works for small amounts of fields (2-3) to check but becomes very ugly beyond that. In my case this would look roughly like this (code not actually tested): class Image(models.Model): [...] class Meta: constraints = [ models.CheckConstraint( name=f'{__name__}_Only_One_Article', check=( models.Q( character_article__isnull=False, creature_article__isnull=True, encounter_article__isnull=True, item_article__isnull=True, location_article__isnull=True, organization_article__isnull=True ) | models.Q( character_article__isnull=True, creature_article__isnull=False, encounter_article__isnull=True, item_article__isnull=True, location_article__isnull=True, organization_article__isnull=True ) … -
Django 3.1: Prepopulate a foreign key fiels using CreateView
There are many answers concerning this topic. None of them which I read, helped me to find a way out. Situation: I've a contact model and I wish to assign an email address. They reside in a table with a foreign key. Now, I'd like to add a button: "add e-mail" which opens a form. As I am in the detail view of the contact, I'd like to hand the id over into the form to either pre- or post-populate the email object (fk to contact) with the contact pk. The easiest way would from my point of view be to just add the pk to the url and use it in "form_valid". The view: class EmailCreateView(LoginRequiredMixin, CreateView): model = EmailAddress fields = ('scope', 'email',) # 'contact', template_name = 'contacts/contact_form.html' # initial = {'email': 'test'} def form_valid(self, form): form.instance.create_by = self.request.user.username form.instance.update_by = self.request.user.username # form.instance.contact = Contact.objects.get(self.kwargs['contact_pk']) <- not working return super().form_valid(form) The urlpattern: path('email/add/', EmailCreateView.as_view(), name='add_email'), The model: class EmailAddress(CommonInfo): scope = models.CharField('Bereich', max_length=2, choices=SCOPE_TYPES) contact = models.ForeignKey(Contact, verbose_name='Kontakt', on_delete=models.CASCADE) email = models.EmailField('E-Mail') def __str__(self): return '{}'.format(self.email) def get_absolute_url(self): return reverse('contacts:detail', kwargs={'pk': self.contact_id}) I really have no idea what I'm missing. As this is a standard case in … -
Accessing other model field when validating model field in Django
So I have a Django app auctions, which has 4 models: Users, Listings, Bids, Comments. When a user tries to place a bid on some listing, I want to check whether bid_amount field in Bid model is smaller than start starting_bid field in Listing model. Also, I wanted to ask, what is the best practice for this kinda stuff? AFAIK, you can validate a form field in forms.py. Thanks! models.py class Listing(models.Model): """Auction listing""" user = models.ForeignKey(User, verbose_name='user owner', on_delete=models.CASCADE, related_name="usr_listings") title = models.CharField(max_length=64) description = models.TextField(max_length=160) starting_bid = models.PositiveIntegerField() bids_number = models.PositiveIntegerField(default=1) img_url = models.URLField("Image URL", max_length=200, blank=True) category = models.CharField(max_length=64, blank=True) date_listed = models.DateTimeField(default=timezone.now) class Meta: verbose_name = 'auction listing' ordering = ['-date_listed'] def __str__(self): return self.title def get_absolute_url(self): print('loading... get_absolute_url') return reverse('listing_detail', kwargs={'pk': self.pk}) class Bid(models.Model): """Bids made on auction listing""" listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing_bids") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_bidder") bid_amount = models.PositiveIntegerField(default=None) class Meta: verbose_name = 'Bid' def __str__(self): return f'{self.bid_amount} by {self.user} on {self.listing}' def clean(self): super().clean() # do something to access Listing.starting bid, and Listing.user -
Why the Django extended user model is not able to show pre-populated data in while updating the fields?
I have written a program to update the User default fields(email with the help of UserCreationForm) and Extended User models(DOB, country etc). Below is the function: @login_required(login_url="/login/") def editUserProfile(request): if request.method == "POST": form = UserProfileUpdateForm(request.POST, instance=request.user) # default user profile update obj = UserProfile.objects.get(user__id=request.user.id) # custom User fields. form1 = UserProfileForm(request.POST or None, instance=obj) if form.is_valid() and form1.is_valid(): obj.Photo = form1.cleaned_data['Photo'] obj.dob = form1.cleaned_data['dob'] obj.country = form1.cleaned_data['country'] obj.State = form1.cleaned_data['State'] obj.District = form1.cleaned_data['District'] obj.phone = form1.cleaned_data['phone'] form.save() form1.save() messages.success(request, f'updated successfully') return redirect('/profile1') else: messages.error(request, f'Please correct the error below.') else: form = UserProfileUpdateForm(instance=request.user) form1 = UserProfileUpdateForm(instance=request.user) return render(request, "authenticate\\editProfilePage.html", {'form': form, 'form1': form1}) With the help of above method I am able to update the user data. However, the issue is when I click on the "update" button on my profile page the next page that I get to enter new data to the fields doesn't come with pre-populated data. i.e, the "email" field has the pre-populated data, but the custom fields like (country, dob, state) are blank, ideally it they should have existing data showing to the user after the user click on the "update" button from the profile page. Any idea. I hope I was able … -
Django application posted data not saving data to database ( sqlite3 ) Getting 200 but no QuerySet [ ]
I am getting a 200 POST but when I check in the Python shell >>> QuerySet [ ] is empty. Django 3 with the default forms. I was originally going to use one function to handle both requests but settled on handling them separately. <form method="POST" action="."> {% csrf_token %} <table border="2"> {{ form }} <input type="visible" name="email"> </table> <button type="submit" style="margin: 10px">Submit</button> </form> class HomeView(TemplateView): template_name = 'home.html' def get(self, request): form = ContactForm() return render(request, self.template_name, {'form': form }) def post(self, request): form = ContactForm(request.POST) # if request.method == 'POST': # return HttpResponse(request.POST['post']) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = ContactForm() return redirect('blog:blog') from django import forms from .models import Post class ContactForm(forms.ModelForm): post = forms.CharField() class Meta: model = Post fields = ('email',) from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) email = models.CharField(max_length=500, blank=True) -
How to render and dispaly variables and values from Django in HTML
I am experimenting with Django and templating system. At the moment I'd like to find the best way to render values from variables/objects in HTML. For example, I have a template tag like this: {{ single.title }} Now, rendering this is perfectly fine when I add it to templates. But I want to know how can I render this in WYSIWYG editor like django-summernote - even if I go and add this in HTML code. it still writes this as a string with curly braces but doesn't render the variable value. Basically, I want to be able to use these variables/values and render them in the WYSIWYG field (say a blog post content). I tried with {% autoescape off %} and number of other things but still ends up rendering this as a regular text. -
Not able to update database column with multiple values inside for loop
I am trying to update database based on user input : user input : val = [[2, 'Yes'], [11, 'No'], [12, 'Yes']] Code : if val is not None: for a in val: Model.objects.filter(id=a[0]).update(value=str(a[1])) return Response({"Success":"Updated"}, status= status.HTTP_202_ACCEPTED) else: return Response({"Error":"Updation Not Required"}, status=status.HTTP_417_EXPECTATION_FAILED) Problem am facing , the above code only updating single record(first record) in database, not updating remaining records([11, 'No'], [12, 'Yes']). Kindly suggest. -
How to get page access token using Django
I m trying to post on Facebook using Django.to do this I have to get Page access token and page id (pages of which user is the admin of). I m using Django==3.0.5,social-auth-app-django==4.0.0 and using PostgreSql for Database. Settings.py SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email, picture.type(large), link' } SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = [ ('name', 'name'), ('email', 'email'), ('picture', 'picture'), ('link', 'profile_url'), ] Questions: How to get a page access token. How to get a token from the database in views.py how to get page id in which user is the admin of. -
Storing Variables in Django RestAPI
I am trying to host a rest API using Django which takes in some parameters, processes it and returns a result. For this processing to happen, I have to use certain datasets which are loaded using excel, tiff, csv, and txt files. Loading these datasets and putting them in python variables (to use them, of course) takes a bit of time; the problem is that I don't want my backend to extract info from all these files everytime I get a request. The best way I could think of is literally copying the raw values from these files and putting them in python variables using the = operator, but that would be atleast a 100,000 lines of code then. Is there some way to pre-define certain variables in my backend? i.e. a variable that would get defined on a run and then every-time I get a request, I'll just use these pre-defined variables instead of loading them again. -
How do I change a Django view to display a different model element each day
I'm trying to change my home template in Django to display a random element from my database each day. Right now, I have about a thousand songs and albums loaded into my data base from Rolling Stone's top 500 entries for each: class Song(models.Model): rank = models.IntegerField() artist = models.CharField(max_length=100) title = models.CharField(max_length=100) cover = models.URLField() writers = models.CharField(max_length=100) producers = models.CharField(max_length=100) releaseInfo = models.CharField(max_length=100) description = models.TextField(max_length=3000) used = models.BooleanField(default=False) def __str__(self): return self.title class Album(models.Model): rank = models.IntegerField() artist = models.CharField(max_length=100) title = models.CharField(max_length=100) cover = models.URLField() label = models.CharField(max_length=100) year = models.CharField(max_length=20) description = models.TextField(max_length=3000) used = models.BooleanField(default=False) I essentially want to select every element where the "used" field = False (i.e it hasn't been displayed yet) and display its information on my app, while also changing the used field of the old display to True. Right now, my site just displays a random entry every time someone visits the page: def home(request): songChoice = randint(1,501) albumChoice = randint(1,501) song = Song.objects.filter(rank = songChoice) album = Album.objects.filter(rank = albumChoice) entry = {"ent":song,"entry":album} return render(request, 'rollingStone/home.html',entry) But I'd want behavior sort of like this, but occuring at midnight each day instead of when the user visits the page: … -
I keep getting a "command not found: django-admin" (I'm using zsh)
I'm new to programming and the terminal in general. I followed some instructions and changed my shell to Oh My zsh (to be honest, I don't know what shell means and what this is all about. It just looks better than the bash shell). When I'm trying to run the django-admin command, I keep getting an error. After googling around and reading other StackOverflow similar issues, I know it's something to do with my path, but I'm not experienced enough to know what exactly. Here are some screenshots of my setup. And here is my zshrc I've been tinkering around for a while now and can't seem to figure this out. Any help would be greatly appreciated. Thank you. -
'utf-8' codec can't decode byte 0x94 in position 15: invalid start byte
Estou rodando Django na porta 8000 quando eu no meu arquivo de templates quando eu escrevo um h1 ocorre tudo certo porém se coloco qualquer outra coisa da este erro UnicodeDecodeError at / 'utf-8' codec can't decode byte 0x94 in position 15: invalid start byte Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0x94 in position 15: invalid start byte Exception Location: C:\Users\Gurgel\AppData\Local\Programs\Python\Python38-32\lib\codecs.py, line 322, in decode Python Executable: C:\Users\Gurgel\Desktop\totalvoice\my-venv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\Gurgel\\Desktop\\totalvoice\\projeto', 'C:\\Users\\Gurgel\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\Gurgel\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\Gurgel\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\Gurgel\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\Gurgel\\Desktop\\totalvoice\\my-venv', 'C:\\Users\\Gurgel\\Desktop\\totalvoice\\my-venv\\lib\\site-packages'] Server time: Sun, 09 Aug 2020 15:10:39 +0000 -
Allign mouse-events opencv with Django
I am working on a project now where I am using python code to draw some stuff on videos using opencv. My idea is to incoorporate this in a django application. My question is whether it is possible to integrate the mousevents,which are necessary for the drawing part, as well. Hope that someone can help me out. -
Django Weasyprint bootstrap styling lost
I have a HTML template in Django that I am creating a PDF with using WeasyPrint. However, my bootstrap styling is lost when the PDF is created: html_string = render_to_string('index.html', {'data' : data, 'total' : total_price, 'cash' : cash_price, 'paid' : paid, 'hm_fees' : hm_fees, 'invoice_number' : invoice_number, 'total_sales' :total_sales}) html = HTML(string=html_string) result = html.write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=invoice.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response Any help is appreciated -
name 'LoginRequiredMixin' is not defined in django
My error is shown in below. name 'LoginRequiredMixin' is not defined class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'order_summary.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") How to import LoginRequiredMixin in django views.py file?. Please help me