Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
trying to create a second forms.py on my Django app to post on the same page
I have one forms.py set up to post onto my Django application successfully. I would like to set up a second forms.py which posts onto the same page but i cannot get it to work. The form comes up but it does not post. Here is my forms.py, the first one is the successful one: ''' from django import forms from . import models class CreatePost(forms.ModelForm): class Meta: model = models.Post fields = ['title', 'body','reverse_around_the_corner','speed_limit','watching_mirrors','centre_of_the_road','slug'] class CreateLearnerPost(forms.ModelForm): class Meta: model = models.LearnerPost fields = ['title', 'body', 'author', 'slug'] ''' Here is my views py, the LearnerPost view is the one i'm trying to create: ''' rom django.shortcuts import render, redirect from .models import Post, LearnerPost from django.contrib.auth.decorators import login_required from . import forms def PostList(request): posts = Post.objects.all().order_by('date') learner_posts = LearnerPost.objects.all().order_by('date') return render(request, 'logbook_index.html', {'posts':posts}, {'learner_posts':learner_posts}) def PostDetail(request, slug): post = Post.objects.get(slug=slug) return render(request, 'post_detail.html', {'post':post}) def LearnerPostDetail(request, slug): learner_post = LearnerPost.objects.get(slug=slug) return render(request, 'learner_post_detail.html', {'learner_post':learner_post}) def PostCreate(request): if request.method == 'POST': form = forms.CreatePost(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('/logbook/') else: form = forms.CreatePost() return render(request, 'post_create.html', {'form':form}) def LearnerPostCreate(request): if request.method == 'POST': form = forms.CreateLearnerPost(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) … -
Django REST Framework - paginate_queryset() takes 2 positional arguments but 3 were given
Really not sure what I have done wrong here, minus a few details, it's very similar to both examples on the REST framework website and almost a carbon copy of another Viewset I have. class ArtistViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ArtistSetPagination ): queryset = Profile.objects.all() permission_classes = [permissions.AllowAny,] pagination_class = ArtistSetPagination serializer_class = ProfileSerializer def get_queryset(self, *args, **kwargs): return Profile.objects.all().prefetch_related( 'user' ) # Artwork List & List Filtering API View: def list(self, request, *args, **kwargs): parameters = {key: request.GET.get(key) for key in dict(request.GET).keys()} queryset = self.get_queryset().annotate( first_name_len=Length('user__first_name'), last_name_len=Length('user__last_name') ).filter( first_name_len__gt=0, last_name_len__gt=0, ).filter( **parameters ).order_by( '-created' ) page = self.paginate_queryset(queryset, self.request) if page is not None: serializer = ProfileSerializer(page, context={'request': request}, many=True) data = paginated.data paginated = self.get_paginated_response(data) else: serializer = ProfileSerializer(queryset, context={'request': request}, many=True) data = serializer.data response = standardized_json_response( message='Artist Objects Has Been Successfully Listed', timestamp=datetime.datetime.now(), data=data ) return Response(data=response, status=status.HTTP_200_OK) All I can see that is different is the use of the annotation for Length()... If anyone has any pointers I would gladly accept. N.B. The standardised_json_response() is just a wrapper which takes a few variables and returns a dict() object, just injecting some extra meta such as the timestamp of the request and the success status (True/False) -
How i display specific page for specidfic logged in user in django
i want to display specific tasks for specific people....like if raj is logged in then tasks of raj should display not others. so please give me some solution... views.py(home fn) def home(request): username=request.session['username'] for username in username: todo_items=TODO.objects.all().order_by("-created_date") return render(request,'main/index.html', {'todo_items':todo_items,'username':username}) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class TODO(models.Model): user=models.ForeignKey(User,on_delete=models.SET_NULL, null=True) created_date=models.DateTimeField() text=models.CharField(max_length=200) -
How to send an error to user that already add book to favorite
I'm trying to make a user stop adding a book into favorite when they already added and show the message into template. Here's my class django python: class User(models.Model): fname = models.CharField(max_length=255) lname = models.CharField(max_length=255) email = models.EmailField() password = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() class Book(models.Model): title = models.CharField(max_length=255) description = models.TextField() uploaded_by = models.ForeignKey(User, related_name="book_uploaded", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = BookManager() class Like(models.Model): u_like = models.ForeignKey( User, related_name="user_like", on_delete=models.CASCADE) b_like = models.ForeignKey( Book, related_name="book_like", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) And here's my views.py: def book_info(request, id): user_who_like = Book.objects.get(id=id).book_like.all() context = { 'book': Book.objects.get(id=id), 'user': User.objects.get(id=request.session["user_id"]), 'user_who_like': Book.objects.get(id=id).book_like.all(), 'user_uploaded': Book.objects.first().uploaded_by, } return render(request, 'book_info.html', context) def like(request, id): book = Book.objects.get(id=id) user = User.objects.get(id=request.session["user_id"]) like = Like.objects.create(u_like=user, b_like=book) return redirect(f"/books/{book.id}") Appreciate all your help! Thank you -
How to setup Google Cloud Storage as a media backend for Django?
I am using Django Storages [google] https://django-storages.readthedocs.io/en/latest/backends/gcloud.html I deployed my app to App engine using no-promote so that I test it out but everytime i upload an image, I get this error Cannot determine path without bucket name.'. Please note am using Django admin to make the upload and my service account key is at the root of my project. My bucket name is 'kyimages' and in models.py, image = models.ImageField(upload_to='kyimages/', blank=True, null=True) -
Creating a progress bar by using django-background-tasks
How can I create a progress bar with django-background-tasks library? I have researched many things but i could not find anything about that. All of the examples are about Celery. Can anyone help me? -
specify list of certain allowed values in char field
i want to specify list of values in CharField and make my serializer to accept the incoming json only if the value of this field is exactly like one of the values in the list. this is an example of what i have in mind. class UserSerializer(serializers.Serializer): username = serializers.CharField() first_name = serializers.CharField() last_name = serializers.CharField() gender = serializers.CharField(allowed=["male", "female", "other"]) is there a way to that? -
Best practices for extending Custom User Model in django
I have a Custom User model in my app class User(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, unique=True) email = models.EmailField(_('email address'), db_index=True, unique=True) and this AUTH_USER_MODEL = 'users.User' in my settings file. Now I want to create a model on the top of this custom user model(User), lets call it Agent, this model will have three columns: user_uuid #Foreign Key Refernce(OnetoOne) to the Custom User Model uuid # unique identifier for Agent model scope # CharField specific to Agent model What is the best way to do that? -
soup.find_all() returns empty dictionary
i have a code up here in my django and it is supposed to return all the resultRows class and it does not. It is not a problem with the module cause it returns 'a' tags, when asked alone. Here is the website im trying to access : https://ras-al-khaimah.locanto.ae/q/?query=computer . . Please someone help :) def new_search(request): search = request.POST.get('search') models.Search.objects.create(search=search) final_url = BASE_CRAIGSLIST_URL.format(quote_plus(search)) print(final_url) response = requests.get(final_url) data = response.text soup = BeautifulSoup(data,features='html.parser') post_titles = soup.find_all('a',{'class':'result-row'}) print(post_titles) stuff_for_frontend = { 'search':search, } return render(request,'my_app/new_search.html', stuff_for_frontend) -
Dynamically create Django settings variables
I have two settings files: settings_commons.py which holds the variables that are common for all instances settings_prod.py prod instance-specific vars settings_dev.py dev instance-specific vars I have multiple variables that set paths for logs, uploads and etc. These paths depend on MNT_DATA_DIR which is different for every instance (dev, prod, etc). I don't want to have these paths duplicated in every instance settings file. What I do in settings_commons.py MNT_DATA_DIR_DEPENDENT_VARS = ( ('FILE_DIR', os.path.join('{MNT_DATA_DIR}', "file_root")), ('LOG_DIR', os.path.join('{MNT_DATA_DIR}', "logs", "lab")), ... ) FILE_DIR_DEPENDENT_VARS = ( ('IMPORT_DATA_DIR', os.path.join('{FILE_DIR}', "Import")), ('REMOTE_DATA_DIR', '{FILE_DIR}'), ... ) And then in the instance-specific file from .settings_commons import * MNT_DATA_DIR = '/mnt/dir' for item in MNT_DATA_DIR_DEPENDENT_VARS: globals()[item[0]] = item[1].format(MNT_DATA_DIR=MNT_DATA_DIR) for item in FILE_DIR_DEPENDENT_VARS: globals()[item[0]] = item[1].format(FILE_DIR=FILE_DIR) Could this approach cause any problems? What about using setattr() instead of globals()? Is this the right approach? -
Django update database using edit form
I am a newbie to Django, and this is my first Django web-app. I have created a student management system where admin can add students. I have created a form at index page where student can enter their enrollment id and date of birth and will be redirected to a edit form page. Now I want to know that how to update the record with new values provided by user, I have no idea where to write the SQLite queries ( I have not changed any db setting and I red that Django uses SQLite db by default ) or how to handle the request. Any help would be appreciated. models.py class Student(models.Model): gender_choices = [('M', 'Male'), ('F', 'Female')] enrollment_no = models.CharField(max_length=10, primary_key=True, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) father_name = models.CharField(max_length=50) mother_name = models.CharField(max_length=50) address = models.CharField(max_length=200) dob = models.DateField('date of birth') gender = models.CharField(choices=gender_choices,max_length=1,default=None) def __str__(self): return (self.first_name +" "+ self.last_name) STUDENT LOGIN FORM (index.html page) <form action="{% url 'students:detail' %}" method="get"> <div class="form-group"> <label for="enrollmentid">Enrollment ID: </label> <input type="text" class="form-control" name="enrollmentid" id="enrollmentid" placeholder="Enter enrollment id" required> </div> <div class="form-group"> <label for="dob">Date of Birth: </label> <input type="text" class="form-control" name="dob" id="dob" placeholder="Enter dob (YYYY-MM-DD)" required> </div> <button class="btn … -
Django, form hidden based on conditional statement
I'm new in django. I have the following models.py class Prodotto(models.Model): name = models.CharField() class Sottoprodotto(models.Model): prodotto=models.ForeignKey(Prodotto) name = models.CharField() class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.IntegerField() prodotto=models.ForeignKey(Prodotto) sottoprodotto=models.ForeignKey(Sottoprodotto) And my forms.py class LavorazioneForm(forms.ModelForm): class Meta: model = Lavorazione fields = "__all__" A "Prodotto" element could have a "Sottoprodotto" or not. I want to have the possibility in my form (created utilizing crispy) to hidden the Sottoprodotto's box when a Prodotto don't have a Sottoprodotto related. It's possible? -
Not able to use django-storages to fetch static files
I am trying to use django storages to fetch static files for Django admin. I am facing a strange behavior that I am not able to understand clearly. I am having two different buckets, one for static files and other for some other purpose. If I comment out the AWS_S3_CUSTOM_DOMAIN keep everything else as it is (the way it is posted below), everything works. But if I uncomment AWS_S3_CUSTOM_DOMAIN and override the custom domain in my storage backend StaticStorage, it starts giving me 403. I know that I am missing something, just not able to figure out what. settings.py S3_BUCKET = os.environ.get('S3_BUCKET') S3_FILE_LOCATION = os.environ.get('S3_FILE_LOCATION') AWS_ACCESS_KEY_ID = os.environ.get('S3_STORAGE_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.environ.get('S3_STORAGE_SECRET_ACCESS_KEY', '') AWS_STORAGE_BUCKET_NAME = os.environ.get('S3_BUCKET', '') AWS_S3_CUSTOM_DOMAIN = f"{os.environ.get('S3_BUCKET', '')}.s3.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = None AWS_S3_VERIFY = False AWS_S3_USE_SSL = False # s3 static settings STATIC_FILE_BUCKET = os.environ.get('STATIC_FILE_BUCKET') STATIC_LOCATION = 'static' STATIC_S3_CUSTOM_DOMAIN = f"{os.environ.get('STATIC_FILE_BUCKET', '')}.s3.amazonaws.com" STATIC_URL = f'https://{STATIC_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' STATICFILES_STORAGE = 'apps.utils.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'apps.utils.storage_backends.PrivateMediaStorage' storage_backends.py class StaticStorage(S3Boto3Storage): location = 'workflow' default_acl = 'private' def __init__(self, *args, **kwargs): kwargs['bucket'] = settings.STATIC_FILE_BUCKET # self.custom_domain = settings.STATIC_S3_CUSTOM_DOMAIN super().__init__(*args, **kwargs) -
Multi settings in Django
I've created in my project settings folder, where I handle development and production. I've added an extra application in production file: INSTALLED_APPS += [ 'google_analytics'] Now I need to add re_path('djga/', include('google_analytics.urls')) to main urls.py. How i can add it when settings are in production mode? -
ValueError: The 'cover' attribute has no file associated with it
I uploaded image from admin panel and it get stored in media/img.I want to display posted image in my index.html but i get this ValueError: The 'cover' attribute has no file associated with it.I think I am making mistake in url or view ..I am new to django. app url.py urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.post_detail, name='post_detail'), ] project url.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("blog.urls"), name="blog-urls"), path("summernote/", include("django_summernote.urls")), views.py class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 3 models.py class Post(models.Model): cover = models.ImageField(upload_to='image/', default='') title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) index.html <img src={{ post.cover.url }} alt="{{ post.title }}" width="160px" height="220px"> -
Django Query Sets - Finding Percentage between two QuerySets
I have got two query sets - >>> region_carrier_groupby_total = <QuerySet [{'region_carrier': 'tc2 - rc2', 'DID_Count': 2}, {'region_carrier': 'tc1 - rc1', 'DID_Count': 16}]> >>> region_carrier_groupby_available = <QuerySet [{'region_carrier': 'tc2 - rc2', 'DID_Count': 1}, {'region_carrier': 'tc1 - rc1', 'DID_Count': 14}]> The objective here is to find the available percentage grouped by region_carrier for DID counts. For instance - region_carrier : tc1-rc1, Percent DID_Count = (14/16)*100 region_carrier : tc2 - rc2, Percent DID_Count = (1/2)*100 -
Django use a column as keys another as values and return dictionary
In Django I have a table within a model like: key value a 1 a 2 a 3 b 4 b 5 I would like to return: {'a': [1, 2, 3], 'b': [4, 5]} or: [{'key': 'a', 'values': [1, 2, 3]}, {'key': 'b', 'values': [4, 5]}] This can be done in Python easily by just iterating through all entries of the table. But since I discovered Aggregation | Django documentation | Django, I wonder if this can be done in Django directly, without writing Python loops? -
How to skip or remove password field in simplejwt token authentication in django rest framework?
My requirement is, I don't wanted to enter password in simplejwt token authentication. I have added one extra field in the authentication by inheriting the init() method of TokenObtainPairSerializer as per my requrements. Currently, I am passing None as in password field but still its showing to user (djnago admin portal). What I want is, I don't wanted to show the password field to user while authentication using simplejwt. below is my code, class CustomSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField() self.fields['password'] = PasswordField(default=None) self.fields['extra'] = serializers.CharField() def validate(self, attrs): pass Is there any ways to set PasswordField as unusable so it wont show to user? -
Django - How to pass varibale to Mixin
Let's say I have the following function-based view, where I pass the argument fofname to the view: def illiquid_reporting(request, fofname): ... If I want to make a class-based view out of it, is the below way the correct method to pass the argument: class IlliquidReporting(TemplateView) def get_context_data(self, fofname **kwargs): context = super().get_context_data(**kwargs) ... -
nginx.conf settting for django
On my ubuntu server i would setting nginx.conf for work with my django app I setup che nginx.conf file like this: user root; worker_processes auto; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; index index.html index.htm; server { listen 80 default_server; listen [::]:80 default_server; server_name 34.233.212.246; root /usr/share/nginx/html; #root /home/ec2-user/carrera/podium/static; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { proxy_pass http://127.0.0.1:8000; #proxy_set_header X-Forwarded-Host $server_name; #proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; add_header P3P 'policyref="/w3c/p3p.xml", CP="IDC DSP COR ADM DEVi TAIi PSA PSD $ } # redirect server error pages to the static page /40x.html # error_page 404 /404.html; location = /40x.html { } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { } } … -
How to create dynamic route for file paths in flask app
In my application I have a file browser. The file names are urls for a detail page, wich takes as argument the bucket and the object name. @app.route("/object_info/<string:bucket_name>/<string:object_name>/", methods=["POST", "GET"]) def object_info(bucket_name, object_name): Like this: http://localhost:5000/bucket_name/Grain_08.tif/ This is working fine, but I cannot display the files in subfolders like in 1aaaa, because if I click to the 2. row the url is: http://localhost:5000/bucket_name/1aaaa/Grain_11.tif and so the url pattern for the object_info route is not working. I have tried solutions like optional routes, but the depth of the subfolders are not limited. Thats mean there can be a file in 4 subfolders. So I need some dynamic stuff so I can display the objects in the deeper folders. -
Is there something called quote_plus from request.compat?
I;m trying to import request.compat.quote_plus but they say cannot find reference in compat.pyi. Is there a fix to this? -
Django/Python3: Convert complex inner join query to
I am developing a book sales application on Django and I need to get a list of the most popular book categories from the books sold. Models: Category (id, name) BookCategory (id, category[FK], book[FK]) Sales(id, book[FK]) Book(id, name) The following SQL is the equivalent of my requirement but I have no idea how to use this using Django models and filtering. sql = "SELECT c.* FROM category c INNER JOIN book_category bc ON c.id = bc.category_id INNER JOIN sales s ON s.book_id = bc.book_id GROUP BY c.id ORDER BY count(s.id) DESC" I have used the following lines of code to execute this but get an error. categories = Category.objects.raw(sql) Object of type 'RawQuerySet' is not JSON serializable How can I accomplish this? -
Can't access /admin in Django in AWS EC2
I deployed my project in AWS EC2 instance, but I can't access the admin site, on going to /admin URL, it gives 404 Error. -
How do I get an AJAX callback function to render a Django url or html template with parameters?
I am a beginner and working on an app where I want to redirect the user to a checkout-basket (Django url via POST? Or render html template with variables?) after checking if anything is saved in localStorage. So I check that and use AJAX to send that data to my Django url in order to render that template passing on the variables in localStorage as JSON. But return render(request, "pizza/prebasket.html", context) in views.py doesn't work: even though the data is recieved, prebasket.html is not rendered. I read that that's because AJAX doesn't allow that and instead I need to post through AJAX's callback function. But how do I do that via POST and how do I pass on the parameters to my view or directly to my html template? (window.location.href only handles GET requests, so I guess that doesn't work). Here's my JavaScript and my views.py: function previous_selection () { if (localStorage.getItem("preselection") != null) { const data = new FormData(); data.append("preselection", preselection); const request = new XMLHttpRequest(); request.open('POST', '/prebasket'); const csrftoken = getCookie('csrftoken'); request.setRequestHeader("X-CSRFToken", csrftoken); console.log("DATA IS: ", data); request.send(data); console.log("PRESELECTION IS: ", preselection); request.onload = () => { // HOW DO I CALL MY URL WITH PARAMETERS HERE? }; …