Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin App permissions don't restrict user?
I'm really confused about the permissions in the Admin app in Django. At first glance, it looks like if you restrict a user in the app, then I would expect the user to not be able to post or edit in that particular model. This is however not the case with my site, I have set up a test user, and restricted this user from a whole area of the site, yet I am still able to post, edit and delete with this user. Is this not what the Admin App is for? if it is, how do you stop a user from posting if they are logged in? -
How do I access an S3Boto3StorageFile in Django for uploading to other locations?
I am trying to upload files to Pipedrive, our CRM, when a lead is being submitted. Everything below here works according to plan, except my views.py when it calls the lead_file_upload() function. I get the following error: expected str, bytes or os.PathLike object, not S3Boto3StorageFile I am assuming this is a result of me using AWS S3 Storage and the file_data = default_storage.open(file.file.file, 'rb') on an S3Boto3StorageFile object. How do I open an S3Boto3StorageFile object which can then be passed on to the lead_file_upload() function? models.py: class Lead(models.Model): lead_name = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True) comments = models.TextField(blank=True) submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return self.lead_name class LeadFile(models.Model): file = models.FileField(upload_to="lead/%Y/%m/%d", blank=True) lead = models.ForeignKey(Lead, on_delete=models.CASCADE) forms.py: from django import forms from django.forms import ClearableFileInput from .models import LeadFile class LeadForm(forms.Form): coop_name = forms.CharField(max_length=50, label = "Name of lead") comments = forms.CharField(max_length=2000, widget=forms.Textarea({}), required=False) class LeadFileModelForm(forms.ModelForm): class Meta: model = LeadFile fields = ['file'] widgets = { 'file': ClearableFileInput(attrs={'multiple': True}), } labels = { 'file': 'Add files', } views.py: def lead(request): title = 'Submit lead' user = request.user if request.method == 'POST': form = LeadForm(request.POST) fileform = LeadFileModelForm(request.POST, request.FILES) files = request.FILES.getlist('file') if form.is_valid() and fileform.is_valid(): lead_name = form.cleaned_data['lead_name'] … -
How to use slug with a ForeignKeymodel of another app.model
Error : Cannot resolve keyword 'slug' into field. Choices are: air_date, id, title, video, video_id, #models.py class Video(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=200, unique=True) year = models.CharField(max_length=4) category = models.CharField(max_length=3) trailer = models.URLField(default='') def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("video.html", kwargs={"slug": str(self.slug)}) class Episode(models.Model): video = models.ForeignKey(Video, related_name='episodes', on_delete=models.CASCADE) title = models.CharField(max_length=512) air_date = models.DateField() videolink = models.URLField(default='') def __str__(self): return self.title The slug is not present in Episode model so, it is giving FieldError. so, how can i get that slug field. # urls.py urlpatterns = [ path('video/<slug:slug>/', views.VideoDetail.as_view(), name='videos'), ] # view.py class VideoDetail(DetailView): model = Episode template_name = 'video/video.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Episodes'] = Episode.objects.all() return context -
TypeError: 'BasePermissionMetaclass' object is not iterable in django rest framework
i looked at other questions regarding this issue and their problems were in the REST_FRAMEWORK = ... values in settings.py file . is there any error in mine ? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api_basic',# this is my app that uses authtokens 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } -
Page not found in the admin when i click save button, everything is okay
At first i tried installing mysqlclient via the terminal only to get gcc permission denied, contacted the admin pertaining the domain but to no assistance. I decided to use SQLite instead, everything worked fine, to my surprise no migrations were requested. Now when i wanted to add a product in the admin page, when i click the save button i get an error that page not found. Everything works fine in development also when i request the same page while online in the admins page it loads fine. Kindly help Here is the gcc permission denied Got this error when i tried pip install mysqlclient in cpanel terminal This is the product page while at the admin page This the error i get when i tr to save the product -
Django renaming model field without ALTER TABLE on the database
I'm trying to rename a model field name without any impact on the DB using db_colum. My model before: class Foo(models.Model):: old_name = models.CharField() My model after: class Foo(models.Model):: new_name = models.CharField(db_column="old_name") I generated a migration and Django guessed that I have renamed the field. The migration looks like: class Migration(migrations.Migration): dependencies = [ ("fooapp", "0001_bar"), ] operations = [ migrations.RenameField( model_name="foo", old_name="old_name", new_name="new_name", ), migrations.AlterField( model_name="foo", name="new_name", field=models.CharField(db_column="old_name"), ), ] Everything is working fine. I try the migration and it is ok. But if I take a look at the SQL generated (with ./manage.py sqlmigrate), I see: -- -- Rename field old_name on foo to new_name -- ALTER TABLE "fooapp_foo" RENAME COLUMN "old_name" TO "new_name"; -- -- Alter field new_name on foo -- ALTER TABLE "fooapp_foo" RENAME COLUMN "new_name" TO "old_name"; I don't get why the migration does that instead of doing nothing. Is there a way to avoid that? -
Django carousel display 2 images at a time
Currently I have only been able to get 1 image with this code to be active on the carousel using Django. However I want to display 3 images. <div class="carousel-inner"> {% for item in page.plant_images.all %} {% image item.image fill-10000x10000 as img %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ img.url }}" class="d-block w-100" alt="{{ img.alt }}"> <div class="imageCounter"> <img src="/media/original_images/camera.png" id="display"> {{ forloop.counter }} of {{ page.plant_images.all.count }} </div> </div> {% endfor %} </div> How am I able to manipulate this so i can get the extra images? -
Django + React The resource was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
Developing a django app with frontend react and serving the react build files with django. project structure is as everything works fine when in settings.py I have DEBUG=True However when I change it to DEBUG=False i get the following errors for static files in the console The resource from “http://localhost:8000/static/js/2.285a2b2f.chunk.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “http://localhost:8000/static/css/main.dde91409.chunk.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “http://localhost:8000/static/js/main.eade1a0b.chunk.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “http://localhost:8000/static/css/2.03372da4.chunk.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “http://localhost:8000/static/js/2.285a2b2f.chunk.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). in my setting.py file I have also set the following TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontend')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'frontend', "build", "static"), # update the STATICFILES_DIRS ) PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') Everything works fine except when DJango DEBUG is False Please can someone help me since I dont want to deploy the app with DEBUG=True -
How to have a like/dislike mechanism with Django model
I have implemented a comment model with my Django application. Now I want to associate it with a CommentLike model where I intend to keep track of like/dislike reaction from the user. Should I keep a track of like/dislike in the CommentLike model, or should I have another model CommentDislike ? What is the best way to have a like/dislike model and keep this in a structured way ? class Comment(models.Model): uuid = models.UUIDField(max_length=255, default = uuid.uuid4) description = models.CharField(max_length=5000, default="") likes = models.PositiveIntegerField(default=0) uploaded_at = models.DateTimeField(null=True, blank=True) commentinguser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) video = models.ForeignKey(Video, on_delete=models.CASCADE) class CommentLike(models.Model): likinguser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) -
dynamiclly count vs database record
I have a post model as below, now I use number_of_likes to record the liked post number. If so, I have to manually maintain the number_of_likes field. class Post(models.Model): number_of_likes = models.IntegerField() class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) I would like to know which method is better, using Like.objects.filter(user=user).count() or maintain a new field such as number_of_likes, is choose later, what is the best way to maintain this field -
Django doesn't load with PostgreSQL where in another server
this first time to migrate data from SQLite to PostgreSQL ( in another server not in local server as Django loaded) its migration successfully ( i see the tables on PostgreSQL already) but when i run-server i get following error WSGI application 'resarch_apllications_site.wsgi.application' could not be loaded; Error importing module. this is my setting.py file """ Django settings for resarch_apllications_site project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os #import middleware # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$95n@$y!7-45(!9cj*!1%gf!%y1p@4)%-*l9@#aow5ezr8gwx9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'document_control' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', ] ROOT_URLCONF = 'resarch_apllications_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION … -
Why does i get the error Pillow not found?
I have made a model with ImageField() so i Installed Django. But whenever i run python manage.py it says you need to install pillow.ERRORS: sho.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". -
How do I use webcam on django page with opencv support?
I have created a simple webpage using django framework. I want to include opencv in the project such that i can display the webcam feed along with face detection on the page. I have also created a simple opencv project to display webcam feed with object detection(outside django). Now I would like to integrate both the projects and display it in a single webpage. I am a beginner in programming world, so any sort of help is appreciated. -
Sorting a queryset by @property calculated field .. update() not working
I have sorted the queryset by using num_left field which is @property field in my models which returns a calculated value num_left. class ABC(models.Model): @property def num_left(self): //some code return num_left def get_queryset(): //some code queryset = sorted(queryset, key=lambda t: t.num_left, reverse=True) return queryset Whenever i try to return a sorted queryset update returns the following .It works when i try to return the unsorted queryset. What am i missing? { "detail": "Not found." } def update(self, request, *args, **kwargs): instance = self.get_object() print(instance) -
Binding files to forms
I'm working on a project in django and I have a form in which I take files as input. In the documentation it says I'm supposed to bind the file to the form. What does it mean to bind the files to a form? -
Improving SEO on Django React SPA
I am looking for some help in this area as new to it. Basically I have a react front-end that receives product information etc from Django via a rest api. I have a list of products that I will continue to add and won't delete any old products. How can I optimise the SEO in this setup? -
pop-up screan doesn't get visible if it's activated by button click
{% if i.content %} <button onclick="show('{{i.id}}')" class=title-holder> <p class=nomnom3>{{i.user}}</p> </button> <div class="overlay" id={{i.id}}> <div id=fullscrean2> <p class=content-holder>{{i.content}}</p> </div> </div> {% else %} <button class=title-holder> <p class=nomnom3>{{i.user}}</p> </button> {% endif %} The html above have two conditions, if there is a user comment it creates a hidden full screan pop-up which I want to activate by button click, else it just displays the user. css for pop-up: .overlay{ position: fixed; top:0; height: 100vh; width: 100%; z-index: 1; background-color: rgba(0,0,0,0.4); display: none; } I have two functions to make it work: $("body").click(function () { $(".overlay").each(function(){ $(this).css("display", "none") $('body').css('overflow', 'scroll'); }) }); The one above hides the pop-up screan on any click. function show(id){ $("#"+id).css("display","block"); } This one gets triggered on button click, but doesn't display the pop-up, only blurs a portion of the screen. But pop-up screen and the first function works fine if pop-up's display is block on pageload. -
Django Plugin for document template creator
I would like to develop a document template creator app with django and was wondering if there are any reusable package doing the same thing at the moment. The idea is to enable/disable section of a document to only print the part we need. Here is an example, from a website done in php. https://docular.net/pages/try Many Thanks, -
How to create a a checkbox/radiobutton for every choice of an attrubute using django-filter
I have a model Property class Property(models.Model): PROPERTY_CATEGORIES = ( ('flat/apartment 1BHK','flat/apartment 1BHK'), ('flat/apartment 2BHK','flat/apartment 2BHK'), ('flat/apartment 3BHK','flat/apartment 3BHK'), ('house','house'), ('pg/hostel +1 mate','pg/hostel +1 mate'), ('pg/hostel +2 mate','pg/hostel +2 mate'), ('pg/hostel +3 mate','pg/hostel +3 mate'), ('pg/hostel +4 mate','pg/hostel +4 mate'), ) name = models.CharField(max_length=200) proptype = models.CharField(max_length=100, choices=PROPERTY_CATEGORIES) and my filters.py looks like this import django_filters from .models import Property from django.db import models from django import forms class PropertyFilter(django_filters.FilterSet): PROPERTY_CATEGORIES = ( ('flat/apartment 1BHK','flat/apartment 1BHK'), ('flat/apartment 2BHK','flat/apartment 2BHK'), ('flat/apartment 3BHK','flat/apartment 3BHK'), ('house','house'), ('pg/hostel +1 mate','pg/hostel +1 mate'), ('pg/hostel +2 mate','pg/hostel +2 mate'), ('pg/hostel +3 mate','pg/hostel +3 mate'), ('pg/hostel +4 mate','pg/hostel +4 mate'), ) proptype = django_filters.ChoiceFilter(choices=PROPERTY_CATEGORIES) class Meta: model = Property fields = ['proptype'] filter_overrides = { models.CharField:{ 'filter_class' : django_filters.ChoiceFilter, 'extra' : lambda f: { 'widget' : 'forms.CheckboxInput' } } } and my html file is {% block content %} <form method="get"> <!-- {{ filter.form.as_p }} --> {% for choice in filter.form.proptype %} {{ choice.choice_label }} <span class="radio">{{ choice.tag }}</span> {% endfor %} <input type="submit" /> </form> {% for obj in filter.qs %} {{ obj }} <br /> {% endfor %} {% endblock %} I want to display the choices like as radiobuttons or checkboxes like a list … -
Django and React app ERR_CONNECTION_REFUSED
I'm runing specfic configuration. I got django runing on apache on address localhost:8001 and react app running on nginx on localhost:8005. Also I use ngingx to route proxy. My biggest problem is when I try to call DRF API by React (calling http://127.0.0.1:8001/api-token-auth/ so I got / at the end of the endpoint for sure) I'm getting POST http://127.0.0.1:8001/api-token-auth/ net::ERR_CONNECTION_REFUSED Backend is running fine, I can use endpoint from HTTPie or POSTMAN When I call backend by external domain name in React like 'example.com/api-token-auth/' it's working just fine. How can I solve this? -
Django. Error when trying to set the seller of a product when customer adds product to cart
Hey guys I am quite new to Django, I am having trouble with adding and saving the name of the seller along with the orderitem in the database. This is my model class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True,) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1, blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) view def cart(request): user = request.user order, created = Order.objects.get_or_create(user=user, complete=False) orderitem = OrderItem.objects.filter(order=order) #print(orderitem) items = order.orderitem_set.all() context = { 'items': items, 'order':order, } return render(request, 'store/cart.html', context) What I am trying to do is, when a customer adds a product from a seller to his cart, along with the product title and quantity, I want the name/username of the seller to be added at the same time to the OrderItem model. How can I achieve this? Help would be much appreciated. Thanks PS. I can add the order model, if its necessary. -
Protect AWS media files using Django permissions
I have a Django project which is currently protecting media files by using a view which checks user permissions before using sendfile to serve the media (which is hosted on my webserver) via nginx. I want to move the media to AWS (from my webserver) but if I do that, how do I continue to protect access to the files via Django? The only options I've seen so far have been to get Django to check the permissions, then download the file and serve it to the user but that's not ideal and it's why I'm using sendfile in the first place! Is there a way to use sendfile to serve AWS files maybe? I've also read about AWS presigned URLs but, whilst they do have an expiry date, surely that URL could (before it expires) be available to users that shouldn't be able to see the file? -
save image from django form to model
I am beginner in django and i am facing a problem that is how to save image from django form to database but image=check.cleaned_data.get('pro_image') return None(ImageField). forms.py class Up(forms.Form): STATUS=( ('Sale','Sale'), ('Rent','Rent'), ) status=forms.ChoiceField(choices=STATUS) pro_image=forms.ImageField(required=False) views.py def create(request): form=Up() context={ 'form':form } check=Up(request.POST or None) if request.method == 'POST': if check.is_valid(): image=check.cleaned_data.get('pro_image') status=check.cleaned_data.get('status') print(image) print(status) try: up=Uploaded() if image==None: up.image='/media/default/item_default.png' else: up.image=image up.status=status up.save() except ObjectDoesNotExist: return render(request,"create.html",context) return render(request,"create.html",context) return render(request,'create.html',context) modles.py class Uploaded(models.Model): image=models.ImageField(upload_to='media/test') status=models.CharField(max_length=10) -
How do i control static directory resources
<script src="./home/static/js/2.d754fc32.chunk.js"></script> Currently my html file points to this. What static variable django setting.py do I declare to make the HTML point to <script src="./home/static/static/js/2.d754fc32.chunk.js"></script> currently in setting.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../frontend/build') ] STATIC_ROOT = '/var/www/web/home/static/' STATIC_URL = 'home/static/' My build folder contains a static file inside as well. -
Conditional redirection in Django
I would like users to be conditionally redirected to different urls based on their email. So users who login with a specific email are redirected to page A and others to page B. With the code i have currently, all users are redirected only to page A (google.com) This is what I have in views.py @login_required @student_required @check_is_allow def messages(request): emails = ['aaa@gmail.com', 'aab@gmail.com', 'aac@gmail.com', 'aba@gmail.com', 'abb@gmail.com', 'abc@gmail.com'] if request.user.email in emails: return render(request, 'https://www.google.com/') else: return render(request, 'https://www.facebook.com/') My urls.py ... path('messages', students.messages, name='messages'), ... and html ... <li><a href="{% url 'students:messages' %}">Messages</a></li> ...