Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change url within get_queryset of django ListView
I'm trying to change the browser url in get_queryset() in a django ListView. Actually I'm trying to hide query params after i use them i found no solution. Please help me with the best method for this purpose I tried to redirect but queryset can't return a HTTPResponseRedirect. I also tried to use a javascript function but it's also not performing well on submit button. I'm recently start development with python and django. Thank you for your support My ListView's queryset: def get_queryset(self): query = self.request.GET.get('q') author_name = self.request.GET.get('a') btn_clicked = self.request.GET.get('m_btn') if btn_clicked: data_to_use = self.request.GET.get('m_paper') # here i tried to change the url using pop but not work self.request.GET._mutable = True self.request.GET.pop('m_paper') self.go_for_mindmap(data_to_use) if query: return Paper.objects.filter(title__icontains=query) if author_name: my_papers = Paper.objects.all() new_paper_list = [] for my_paper in my_papers: if author_name.casefold() in my_paper.get_author_fam().casefold(): new_paper_list.append(my_paper) return new_paper_list else: return Paper.objects.all() HTML Template <form action="#" method="GET" class="float-right"> <input type="hidden" value="{{ p.title }}" name="m_paper"> <!-- javascript function (onclick) also not working. --> <button type="submit" class="btn btn-success" value="Click" name="m_btn" onclick="myFunction();">Go</button> </form> I accept to the there is no more paramters in url -
Can PAM module authenticates users against Django login credentials?
I have a Django web application running on Server1 with around 9000 users. Now i would like to create a vsftpd server on Server2 and enable all the 9000 users to access their own home folders using credentials of web-app on Server1. I want to have a PAM authentication on server2 where users are validated against webapp on server1. If a user is deleted or updated his password on server1, FTP access has to be allowed/denied accordingly. i.e User Authentication server has to be my webapp only. Is django logins by default SSO compliant? Can i have LDAP server inside Django with the same users&passwords? -
Do I need to install NPM in server to host a website built with Django Rest API and Vue JS?
I am newbie to Django. I have created a website ( similer to Quora) using Vue JS that consume Django REST API, I have used the Vue through Vue CLI. Do I need to install NPM in Heroku server to host the Vue CLI ? I think the server may need large amount of space to host the NPM. Also running NPM may impact the server speed. Should I consider CDN link of Vue JS instead of hosting in server ? -
Navigation bar side by side in Django?
I'm trying to build a navigation bar for practice but running into an issue. I'm trying to get information from views.py to share on website through html but not working very well. It displays the content perfectly but it is not showing them in one line. I included a picture of the rendered website. HTML Code: <!doctype html> <html> <style> ul{ width : 100%; float : left; display: inline-block; list-style-type: none; background-color: blue; } </style> <head> <title>Coding for fun</title> </head> <body> <ul class="navBar"> {% for my_sub in my_test %} <li> {{ my_sub}} </li> {% endfor %} </ul> </body> </html> -
Should I use an internal API in a django project to communicate between apps?
I'm building/managing a django project, with multiple apps inside of it. One stores survey data, and another stores classifiers, that are used to add features to the survey data. For example, Is this survey answer sad? 0/1. This feature will get stored along with the survey data. We're trying to decide how and where in the app to actually perform this featurization, and I'm being recommended a number of approaches that don't make ANY sense to me, but I'm also not very familiar with django, or more-than-hobby-scale web development, so I wanted to get another opinion. The data app obviously needs access to the classifiers app, to be able to run the classifiers on the data, and then reinsert the featurized data, but how to get access to the classifiers has become contentious. The obvious approach, to me, is to just import them directly, a la # from inside the Survey App from ClassifierModels import Classifier cls = Classifier.where(name='Sad').first() # or whatever, I'm used to flask data = Survey.where(question='How do you feel?').first() labels = cls(data.responses) # etc. However, one of my engineers is saying that this is bad practice, because apps should not import one another's models. And that instead, … -
Django migrations for second model
Django doesn't respond to making the migrations to the model in the new app. I deleted the app then made a new one, but still doesn't respond. I deleted the old migration and makemigrations, Django only respond to the first model which I have done before this problem (venv) F:\My site>python manage.py makemigrations No changes detected (venv) F:\My site>python manage.py makemigrations blog No installed app with label 'blog'. -
Creating a lot of numbered URLs easily
I have a list of Hospitals on a web page and each Hospital has a link with it that should open a new page which shows all the reviews and feedbacks that people fill in the feedback form. The problem is that the list goes on for about 70-80 hospitals and creating a URL and a view for each one is a very tiring and long job. Also the number of hospitals may vary later on and then that new entry would require a new URL and view. I want to know if there's any easy way to create those 80 URLs without having to actually create even those 80 URLs (like maybe a loop or something). I'm very new to Django, Python and HTML so an easily understandable way is much appreciated. I'm using PyCharm community and Python 3 for this project. Thank you. -
Removing class name removes my HTML a tag without which I cannot perform AJAX
I'm learning from this tutorial: AJAX and Django Where I'm using the below code. <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!-- Assume appropriate django template code here --> <a class="btn btn-primary btn-lg" id="like{{ post.id }}" href = "#" data-catid="{{ post.id }}">Like</a> <!-- Assume appropriate django template code here --> <script type="text/javascript"> $('.btn').click(function() { var id; id = $(this).attr("data-catid"); $.ajax({ type:"GET", url:"like", data:{ post_id: id }, success: function(data) { $( '#like' + id ).removeClass('btn btn-primary btn-lg'); $( '#like' + id ).addClass('btn btn-success btn-lg'); } }) }); </script> If I put the likebutton in class of like below, the like button doesn't show. I do not understand it as stackoverflow's run snippet shows a like button, but my browser (firefox latest) doesn't. <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!-- Assume appropriate django template code here --> <a class="likebutton btn btn-primary btn-lg" id="like{{ post.id }}" href = "#" data-catid="{{ post.id }}">Like</a> <!-- Assume appropriate django template code here --> <script type="text/javascript"> $('.likebutton').click(function() { var id; id = $(this).attr("data-catid"); $.ajax({ type:"GET", url:"like", data:{ post_id: id }, success: function(data) { $( '#like' + id ).removeClass('btn btn-primary btn-lg'); $( '#like' + id ).addClass('btn btn-success btn-lg'); } }) }); </script> Screenshots … -
How to access data(which is in html form) which has been passed to another html inside views.py?
While rendering the '/form/' in my py_upload function I am passing a parameter 'data' which contains the code of an html form(by form I mean some text boxes where I can enter some information and not the element of html) which I have obtained using selenium. This html is displayed in my /form/ url where it will be filled and I want to perform some operation on the filled form on pressing the submit button (inside my py_form function). How can I use the filled html code inside my py_form function? I tried replacing the 'data' element in my form.html with the html code inside 'data' and then I could access it but the problem is that the html code in 'data' is not constant so I can not hardcode that html in my form.html. Below are the files form.html and views.py <div class="container"> {% if data %} {{data | safe}} {% endif %} <form action="" method="post"> {% csrf_token %} <input type="submit" name="Submit" value=" </form> </div> def py_upload(request): if request.method == 'POST': #some selenium code to get some html data in 'data' return redirect ('/form/',{'data':data}) return render(request,'upload.html') def py_form(request): if request.method == 'POST': ##access the filled html data return redirect('/response/',{'flag': … -
How to set a field constant in a django model
I have a custom user model and a company model: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() company = models.ForeignKey( Company, null=True, blank=False, on_delete=models.SET_NULL) class Company(models.Model): company_name = models.CharField( default='', max_length=128, blank=True, null=True) In settings.py I also have a customer_name constant: CUSTOMER_NAME = os.environ.get('CUSTOMER_NAME') How can I add a condition in my user model so that if the user is_staff boolean is TRUE then the company_name is fixed to be the CUSTOMER_NAME constant? -
How to Make Background iamage URL Static
I want to make this URL static as like this <img src="{% static 'images/beach.svg' %}" > {% load static %} <div class="background_image" style="background-image:url(images/home_slider.jpg)"></div> What/How I can do? -
how to use custom model user in django-rest-framework-simple-jwt
simple-jwt currently issues token using superuser but, i wanna use my custom User Model. (i defined custom User model as below.) class User(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=10, unique=True, blank=False) password = models.CharField(max_length=128) def __repr__(self): return self.__class__ class UsersSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("name", "password") my question is that could i receive token using custom user model at simple-jwt? if simple-jwt uses custom User model, please tell me how to use custom User model. -
I can't seem to troubleshoot this code( python crash course)
I'm very new to Python and Django in particular and I"m working my way through the Python Crash Course(1st ed) book by Eric Matthes. Everything has been running fine up until chapter 19 when I am adding functionality for the user to add entries to topics. Basically its a web app that working kind of like a journal to log things you learn about certain topics. I've thrown in some print statements to try and figure out where the exactly problem lies and from what I can tell it seems to be with the if statement in def new_entry function in views.py. I can't figure out where to really go from here. out of the print statements i have in the current code only the one right below the first if statement executes print("this is requesting a new form") my views.py file with relevant entry def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if request != 'POST': # No data submitted; create blank form form = EntryForm() print("this is requesting a new form") else: print("else statment runs?") # POST data submitted; process data. form = EntryForm(data=request.POST) print("The else statment is running") if form.is_valid(): print("the … -
CORS issue with Django backend and React frontend
I'm getting a CORS issue and this is my first CORS experience (Yay!). I've been researching for over a week and just cannot figure this out. Here is the pre-flight GENERAL Request URL: http://gsndev.com/gsndb/all/uploadcsv/ Request Method: OPTIONS Status Code: 200 OK Remote Address: 104.18.39.141:80 Referrer Policy: no-referrer-when-downgrade RESPONSE HEADER access-control-allow-headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with access-control-allow-methods: DELETE, GET, OPTIONS, PATCH, POST, PUT access-control-allow-origin: * access-control-max-age: 86400 CF-RAY: 4f964ff0deb1c7c1-DEN Connection: keep-alive Content-Encoding: gzip Content-Type: text/html; charset=utf-8 Date: Sat, 20 Jul 2019 16:29:08 GMT Server: cloudflare Transfer-Encoding: chunked vary: Origin x-envoy-upstream-service-time: 4 REQUEST HEADER Provisional headers are shown Access-Control-Request-Headers: authorization Access-Control-Request-Method: POST Origin: http://localhost:3000 Referer: http://localhost:3000/manage-data/upload User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 Here is where the error comes in: GENERAL Request URL: http://gsndev.com/gsndb/all/uploadcsv/ Request Method: POST Status Code: 500 Internal Server Error Remote Address: 104.18.39.141:80 Referrer Policy: no-referrer-when-downgrade RESPONSE HEADER Provisional headers are shown Accept: application/json Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxOCwidXNlcm5hbWUiOiJoYW5uYWgiLCJleHAiOjE1NjM2NDIwOTMsImVtYWlsIjoiIn0.puGSSGtLXOzVjW63OQozv-DDoZcNi_eW5uTT1LKFG50 Content-Type: multipart/form-data Origin: http://localhost:3000 Referer: http://localhost:3000/manage-data/upload User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 REQUEST PAYLOAD [object Object] And I'm getting this error in the console: Access to fetch at 'http://gsndev.com/gsndb/all/uploadcsv/' from origin 'http://localhost:3000' has been blocked … -
WCDN cache policy in the http response header
I deployed a django project on a server, and have some unexpected cache of data on http response. some of my pages should have changed after adding some data in the panel, but it's changing after a while. here is my response header: WCDN-Cache-Policy: SMART WCDN-CacheID: ... I use nginx, gunicorn and supervisor on my server. How can I disable this cache system? -
Storing tenant-specific constants when using Docker to deploy a multi-tenanted Django app
I am using this approach to build a multi-tenanted app in Django and isolate the tenants using Docker. For those not familiar, it essentially redeploys the same code base in a different container for each different customer, allowing them to exist on the same server. I like this as it's the best form of isolation I've seen without spinning up new machines, requires little new code, and I don't mind manual config in Docker to onboard a customer. However, when previously I was building a single-tenant app I saved constants like the customer's name in CUSTOMER_NAME = 'My Customer' in settings.py I can no longer do this, as the code base is shared each time I deploy in Docker. What would be the alternative best practice? Should I create a customer model with one entry to store this data? It feels like I am overlooking something. -
ImportError: cannot import name 'load_strategy'
I am setting up a django rest api and need to integrate social login feature.I followed the following link Social Auth with Django REST Framework After setting up when try to run server getting following error from social.apps.django_app import load_strategy ImportError: cannot import name 'load_strategy' Is there any package i missed? i cant figure out the error. -
Extend djoser login method to get user roles
Djoser login api returns the user token, I also want to return user roles. How to implement such a case? Here is the method of logging on: def login_user(request, user): token, _ = settings.TOKEN_MODEL.objects.get_or_create(user=user) if settings.CREATE_SESSION_ON_LOGIN: login(request, user) user_logged_in.send(sender=user.__class__, request=request, user=user) return token My goal is to achieve something like: def login_user(request, user): token, new_user = settings.TOKEN_MODEL.objects.get_or_create(user=user) if not new_user: token_and_roles = { token: token, roles: [for group.lower() in User.objects.get(user).groups] } return token_and_roles if settings.CREATE_SESSION_ON_LOGIN: login(request, user) user_logged_in.send(sender=user.__class__, request=request, user=user) return token How to overwrite djoser api login method? -
Complex prefetch_related
There is a request which returns a list of several Lists with their movies. I want to use prefetch to Lists to optimize db calls. I have several models: class List(models.Model): name = models.CharField() class ListMovie(models.Model): list = models.ForeignKey(List) movie = models.ForeignKey(Movie) class Movie(models.Model): title = models.CharField() Is there a way to prefetch movies from List object with prefetch_related? -
permission_classes doesn't work whats going wrong?
I made acustom permission which make only advertise creator can delete or edit it ,though permissions have no effect and alraedy deleted another user advertise what;s going wrong here? views.py: from rest_framework import permissions,generics from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from .permissions import IsOwnerOrReadOnly from advertise.serializers import AdSerializer class AdListGeneric(generics.ListCreateAPIView): permission_classes([permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly],) queryset=Advertise.objects.all() serializer_class=AdSerializer # @permission_classes([permissions.IsAuthenticatedOrReadOnly],[IsOwnerOrReadOnly]) class AdDetailgeneric(generics.RetrieveUpdateDestroyAPIView): permission_classes([permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly],) queryset=Advertise.objects.all() serializer_class=AdSerializer ,,, permissions.py: from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ create custom permission allow only owner to edit it """ def has_object_permission(self, request,view, obj): #read allowd to all users #so we always allow GET, HEAD, OPTioNS if request.method in permissions.SAFE_METHODS: return True #write permissions only for allwed users: return obj.publisher == request.user ,, , -
Django PostgresqlJSONField custom decoder
Providing a custom encoder is easy, as we can give set the encoder parameter, but using a custom decoder seems not possible. How would I go about using a custom decoder for Django PostgresqlField? -
How to make a range from textarea in django
I create a simple website that allow user to place their favorite word and search for a capital and one by one processing it at the backend. for example: <form method="POST" action="/search> {% csrf_token %} <textarea></textarea> <button type="submit">Submit</button> </form> Now I want to submit a text for example Python Django Flask I want to manually split that text and one by one process it (FOR EXAMPLE CODE) {% for x in textarea_tag %} {{ validate_function() }} {% endfor %} Sorry for any wrong format, if there is. -
How to reassign a model to a different app for display only purposes in Django Admin
I know I can change the display title for a model in Django Admin using class Meta: verbose_name='Custom Model Name Here' However, is there a way to display which app heading a model is displayed under? For example, if I create a custom user model Users in a new app also called users then the default user model goes from Authentication and Authorization > Users to Users > Users. I would like to retain it under the original heading Authentication and Authorization > Users. I have read this answer which suggests changes the app verbose_name, however it only changes the verbose name of the app associated with the model. I want to show the model in a different group on the admin panel. You can see the issue that approach takes here: -
Reverse accessor clashes in Django when adding custom user. Adding AUTH_USER_MODEL in settings.py doesn't work either
I got reverse accessor clashes error when trying to use a custom user model. I added AUTH_USER_MODEL in settings.py but still get the same error. I am writing a Django project (Django version 2.2.2) when at a point I want to change to use the custom user model. There are already a couple of models, but it's fine to clear the database to start over at this stage, so I have deleted the sqlite3.db and all the migrations. So to have a custom user model as per django documentation, I added: in models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass ... # other models in settings.py: AUTH_USER_MODEL = 'polls.User' After that, python .\manage.py makemigrations should just work. But it doesn't. It showed the same message as if I didn't add AUTH_USER_MODEL in settings.py at all: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. polls.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: … -
How to change app a model is displayed under in Django Admin interface
I know I can change the display title for a model in Django Admin using class Meta: verbose_name='Custom Model Name Here' However, is there a way to display which app heading a model is displayed under? For example, if I create a custom user model Users in a new app also called users then the default user model goes from Authentication and Authorization > Users to Users > Users. I would like to retain it under the original heading Authentication and Authorization > Users.