Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to put a link in ModelChoiceField empty_label?
I'm working on an app, with a form that is a ModelForm. I have select boxes for the model foreign keys that display all the objects of the related tables. Since ther are many objects in the table, I would like to display only a few and have an exta option that when clicked on displays a kind of modal with the list of all objects of the table. My form.py: class ltaForm(ModelForm): def __init__(self, *args, **kwargs): super(ltaForm,self).__init__(*args, **kwargs) self.fields['idagent'] = ModelChoiceField(queryset = Agent.objects.all()[:7], empty_label="<a>Plus</a>") self.fields['idagent'].widget.attrs.update({'class': "form-control m-1 d-inline-block"}) class Meta: model = Lta fields = '__all__' My template: <form> ... <div class="row m-1"> <div class="col-5"> <label for="{{ ltaform.idagent.id_for_label }}">Emmetteur</label> {{ ltaform.idagent}} <button type="button" class="btn btn rounded rounded-circle float-start bg-light" data-bs-toggle="modal" data-bs-target="#agentModal" id="agentVolModalButton"> <i class="fa-solid fa-plus text-secondary"></i> </button> </div> </div> ... </form> What I would like is to have an extra option that triggers that modal or popup that I described, so I was wondering if I could set a link in the ModelChoice empty_label to do that. But the way I do it here it just displays as plain text in the html. Is there a way to achieve what I want to achieve ? Thanks in advance -
How to solve <Request 400> Error in django?
I tried to make a request from my Django project. This is my code: st_data = {"documentId": 1388, "type": 1, "useAsMain": True } headers2 = { 'Authorization': 'Bearer ' + token_key, "Content-Type": "application/json" } statement = requests.post(url_statement, headers=headers2, data=json.dumps(st_data)) The response of this request is <response 400> And the error code is: {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-0bbcfce14dfc2146b553c2d98c323b3d-80f72a6fe60f18 4c-00","errors":{"$":["The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[Otc.Data.Objects.StatementDTO]. Path: $ | LineNumber: 0 | BytePositionInLi ne: 1."]}} But when I send request from Swagger UI like; It returns <response 200> Where is my mistake? -
In django admin panel permissions given to the users by group not working
In Django admin panel I create groups and give permission to them. eg: Create a Student Group and give it permission to view the student model. Create a Teacher Group and give it permission to view the student model and add the student model. create user using API and added to those groups, and also staff status checked for each user. When users log in on the admin panel that shows Site administration You don’t have permission to view or edit anything. How to solve it. -
Django Admin filter then exclude products
When i am filtering, i am getting all the products name , that i am not expecting also those products are not assigned to any country just list of name products. i made this query to exclude but not working. admin.py def formfield_for_manytomany(self, db_field, request, product_name=None, product_name__isnull= True, **kwargs): if db_field.name == "product_name" : kwargs["queryset"] = models.ProductName.objects.filter(product_name == request._user_country).exclude(product_name__isnull == True) return super().formfield_for_foreignkey(db_field, request, **kwargs) model.py class Product(models.Model): name = models.ManyToManyField( ProductName, verbose_name=_("Products Name") country = models.ForeignKey(Country, on_delete=models.CASCADE, verbose_name=_("Country")) -
Move static and media files to Azure storage account and now broken
I set up an Azure storage account to serve my static files and media, but now all my links from within my templates which are referencing the static path are broken. From what I can tell it's missing a / after the {% static '' %} which means the path is now https://#################.blob.core.windows.net/static/mediaassets/plugins/owl-carousel/owl.carousel.css but should be https://#################.blob.core.windows.net/static/media/assets/plugins/owl-carousel/owl.carousel.css containing the / before assets/ I've literally change every reference to static files within my settings.py but it doesn't seem to make any difference. STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR,"static_root") DEFAULT_FILE_STORAGE = 'app.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'app.custom_azure.AzureStaticStorage' STATIC_LOCATION = "static" Within all my templates I have the following syntax <link href="{% static '' %}assets/plugins/gallery/gallery.css" rel="stylesheet"> Other than going through every single template and adding the / before the assets does anyone know how this path is being formed so that i can just make a single change? -
how to setup an implicit condition for unique=True in django orm
i am using Django along with DRF, and I am using many tables and complex relationships, using soft delete (that is only marked deleted_at and not actually deleting anything) on my models from the begging didn't hurt much, but now we are making some new changes and deleted instances are growing. so unique db constraints started giving errors, I know and implemented two possible solutions, one is unique_together in metaclass, with deleted at and every other unique value, the other is: class Meta: constraints = [UniqueConstraint(fields=["name"], condition=Q(deleted_at != True))] yet what I want is quite different, I want to avoid repeating all this and create a flag of uniqueness like this: something_id = models.CharField(null=False, blank=False, max_length=256, unique_undeleted=True) notice the unique_undeleted parameter, i know doing this directly requires changes in the library which is obviously bad, but i have a parent model that i use in all others, i thought of making a customized Constructor that will check every unique value, and make the unique on condition addition, or i could use this also class MySpecialModel(parentModel): somethingboolean= models.BooleanField(default=True, null=False) something_id = models.CharField(null=False, blank=False, max_length=256) something_unique_too = models.CharField(null=False, blank=False, max_length=256) unique_undeleted_fields = ["something_id", "something_unique_too""] and iterate in the parent model and create … -
For loop in django views
def lead_unassigned(request): unassigned = Agent.objects.all() for i in range(0,len(unassigned)): team_unassigned=profile_candidate.objects.exclude(Reference_Mobile = (unassigned[i])) return render(request, 'leads/lead_list_unassigned.html', {'team_unassigned':team_unassigned}) I am a beginner This is my views.py code, profile_candidate is my mode, refrence_mobile one of the field Agent is my another model which contains the list of agents, here my task is to display the list of profile_candidates in which the refernce_mobile is not matching with any of the agents available in agent table i tried with the above but it is checking only the last agent in the Agent model. it is not checking all the users available in the agent model. {% for i in team_unassigned %} <tr> <td>{{i.Name}}</td> <td>{{i.DOB}}</td> <td>{{i.highest_qualification}}</td> <td>{{i.online_exam_status}}</td> <td> <a class="btn btn-sm btn-success" href="{% url 'lead_detail' i.pk %}">View</a> <a class="btn btn-sm btn-success" href="{% url 'lead_update' i.pk %}">Update</a> </td> </tr> {% endfor %} </table> this is my template displaying the list. Can any one help me in achieving this, -
How can I POST a form having ObjectId? Getting 'object of type ObjectId is not JSON serializable' error
I tried this on django with djongo and restAPI. I made two models like this. from djongo import models class User(models.Model): _id = models.ObjectIdField() u_name = models.TextField(default="홍길동") u_email = models.EmailField(default="aaaaa@aaa.com") inactivated_date = models.DateField(null=True) class Meta: db_table = "user" def __str__(self): return ""+self.u_name+", "+self.u_email class Manager(models.Model): u_id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, db_column="u_id") m_tel = models.TextField(default="010-0101-1010") class Meta: db_table = "manager" And, when I tried to POST the manager, the 'object of type ObjectId is not JSON serializable' error happened. I tried as many things to avoid it, but couldn't. Is there any way to POST a model that has OneToOneField with having ObjectId as 'PK'? -
Get related object via `token` table from dj_rest_auth
I use DRF token authentication as auth backend for my React app. Now I've set up a new endpoint to retrieve the user instance of model UserProfile which is a 1-1 relation to the built-in BaseUser. The endpoint is fed with the token of the user once logged in and DRF holds the token in a table Token. How can I now use the token to query the correct user instance? return UserProfile.objects.get(user__token=token) this returns django.core.exceptions.FieldError: Related Field got invalid lookup: token The token makes it just fine to the view which I checked via print(token). # views.py class UserDetail(APIView): def get_object(self, token): try: return UserProfile.objects.get(user__token=token) # doesn't work except UserProfile.DoesNotExist: raise Http404 def post(self, request): token = json.loads(request.body.decode('utf-8')) user = self.get_object(token) serializer = UserProfileSerializer(user) return Response(serializer.data) # models.py class UserProfile(models.Model): """ Extends Base User via 1-1 for profile information """ # Relations user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) # Roles is_ta = models.BooleanField(default=False) # indicates if user is part of TA department def __str__(self): return F'{self.user.first_name} {self.user.last_name}' -
Get List of FCM unsubscribe topics
Is anyone have an idea how to get a list of an unsubscribed topic from Firebase. Is there any REST API? Thanks in advance! -
How to get the count of fields that are either None ot empty in a row using ORM Django?
I have a model, class personal_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) picture = models.ImageField(default='pro.png', upload_to='profile_image', blank=True) designation = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=255, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) language = models.CharField(max_length=255, blank=True, null=True) linkedin_url = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.pk) I want to get the number of field's count which are either None or "". personal_profile.objects.get(custom_user=some_user_id) By the above query, I can get the queryset of that specific user. Now I want to check all the fields belongs to that custom_user. For example, picture, desgination. gender, date_of_birth, language, linkedin_url Thanks -
Django html button to import csv into pandas/model and show imported data in the same html
Beginner question here: How to use an html button on a page (in Django's templates folder: C:...\demo\demo\templates\page.html) for the user to click and import a csv file into pandas (and/or the model? to save as SQLite3 later) and then show the imported file as a table in that very same html page? It has to be an html page instead of a form because I want to add the web design later and the user can check/navigate on what he has imported. This figure shows what I am looking for: enter image description here Would you mind, please, providing a simple yet complete example? I have tried these links but with no success: How can I transform an html button link to a pandas dataframe? Python - How can I read a CSV created by a HTML5 Export Button into a Pandas DataFrame? Django import csv HTML What's the easiest way to Import a CSV file into a Django Model? import CSV as database Django -
Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed. Request aborted
the issue occurred just after updating the version of django there is no chaanges in settings of django. Image Given below of error error image -
Get user instance in React from Django `dj_rest_auth`
Once a user logs into my app I want to fetch the user instance and return this as well to the client. Therefor I've set up a new endpoint with method POST to send the token from local storage to the view to then query the object from db. My idea was to use the token as param in the view. However, my current approach returns TypeError: post() missing 1 required positional argument: 'token' for post method def post(self, request, token) or TypeError: 'Request' object is not iterable for post method def post(self, token) // React function export const getUser = (token) => { console.log('getUser triggered') console.log(token) fetch('http://127.0.0.1:8000/api/user/object/', { method: 'POST', body: JSON.stringify(token), headers: { 'Content-Type': 'application/json', } }) .then(res => res.json()) .then(data => { console.log(data); }); }; // Django view class UserDetail(APIView): """ Retrieve a User instance """ def get_object(self, token): try: return UserProfile.objects.get(user__tokens=token) except UserProfile.DoesNotExist: raise Http404 def post(self, request, token): print('test2') user = self.get_object(token) serializer = UserProfileSerializer(user) return Response(serializer.data) -
Better way to do the django api response
I have tried to create a model to represent a situation like this. each question row can have a multiple question column. there are multiple types of question column class QuestionRow(models.Model): report_question = models.CharField(max_length=200) report_group = models.CharField(max_length=20) class QuestionColumn(models.Model): header_text = models.CharField(max_length=100) data_type = models.CharField(max_length=10) class QuestionItem(models.Model): column = models.ForeignKey(QuestionColumn) row = models.ForeignKey(QuestionRow) My objective is to find the optimized way to query and return the response [{ "report_group": 1, "question_row": "1a. Alarm system not active or not sufficient?", "question_columns" : [ { "header_text": "Yes/No", "data_type": "Bool" }, { "header_text": "Risk Score", "data_type": "" } ] }, { "report_group": 1, "question_row": "1b. Notification system not active or inactive?", "question_columns" : [ { "header_text": "Yes/No", "data_type": "Bool" }, { "header_text": "Risk Score", "data_type": "" } ] }] -
Does Model.update method in django locks the table before saving the instances?
I have a scenario in which I need to copy the values of one column into an another column. I am trying to do Model.objects.select_related('vcsdata').all().update(charging_status_v2=F('charging_status')) Does using F expression along with the update to copy the values would create any downtime? does it locks the table while performing the operation? related_question_for_more_context -
Django Model objects not displaying in my template
I am new to Django. I have problem in displaying model objects into my template here is my models.py: from django.db import models from django.contrib.auth.models import User class Employee(models.Model): username = models.TextField(max_length=100) email = models.CharField(max_length=100) password = models.TextField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.username here is my views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Employee @login_required def home(request): context ={ 'employee': Employee.objects.all() } return render(request, 'newusers/home.html', context) here is my template code: {% extends "users/base.html" %} {% load crispy_forms_tags %} {% block content %} <article class="media content-section"> <div class="media-body"> <div class="card"> <a class="mr-2" href="#">{{ employee.username }}</a> <small class="text-muted">{{ employee.email }}</small> </div> </div> </article> {% endblock content %} -
ImportError: win32 only when deploying a django app on heroku
The error : from asyncio.windows_events import NULL File "/app/.heroku/python/lib/python3.10/asyncio/windows_events.py", line 6, in raise ImportError('win32 only') ImportError: win32 only please how can i fix this ? -
The view main.views.view didn't return an HttpResponse object. It returned None instead
In my def post(self, request, pk, *args, **kwargs): generic view function I wrote return JsonResponse(object.username, safe=True) and The ajax doesn't work because I get the error: The view main.views.view didn't return an HttpResponse object. It returned None instead. I submit the form with htmx: hx-post="{% url 'main:view' object.pk %}" -
django-filter with paginations
I use django 2.2 and the django-filter package to search my list view. I would like to adjust it with my pagination but I don't know how to adapt it. I tried to make it so that when the search is entered and if we change the page then we add ?page=1 to the url. But I couldn't make it work. Here is my view: def log_list(request): page = request.GET.get('page', 1) eventlog = Log.objects.all().order_by('-id') filtered_qs = LogFilter(request.GET, queryset=eventlog) paginator = Paginator(filtered_qs.qs, 15) try: list_items = paginator.page(page) except PageNotAnInteger: list_items = paginator.page(1) except EmptyPage: list_items = paginator.page(paginator.num_pages) return render(request, 'appli/log/log_list.html', {"list_items": list_items, 'filtered_qs': filtered_qs}) My template pagination: {% load static %} {% load custom_query %} <nav aria-label="Page navigation example"> {% if list_items.has_other_pages %} <ul class="pagination justify-content-center mt-2"> {% if list_items.has_previous %} <li class="page-item"> <a class="page-link text-typo2" href="?page={{ list_items.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% if list_items.number > 3 %} <li class="page-item"> <a class="page-link text-typo2 active" href="?page=1">1</a> </li> {% if list_items.number > 4 %} <li class="page-item disabled"> <a class="page-link text-typo2">...</a> </li> {% endif %} {% endif %} {% endif %} {% for num in list_items.paginator.page_range %} {% if list_items.number == num %} <li class="page-item disabled"> <a class="page-link text-typo2"><span aria-hidden="true">{{ num }}</span></a> … -
How can i add jars in jvm path after starting
What am doing: Using jpype and jaydebeapi in django to connect with different databases (mysql, postgresql, sql server, oracle etc) using jdbc jars. Currently i have placed all my jdbc jars in one folder and setting its path in jpype.startJVM jpype.startJVM(<jvm_path>, '-Djava.class.path=postgresql.jar:mysql.jar') Problem Statement in my current scenario if i need to add another jar in my jars folder then i need to restart my django server so that jvm should be reinitialize to pick new jars but i don't want to restart my django server when i add new jar, obvioulsy restarting server will not work in production enviornment. I checked jpype documentation and noticed that jar file path needs to be set before jvm start and after start if we add new jar then it will not be picked by jvm, also we can't stop/start jvm as it will cause issues (https://jpype.readthedocs.io/en/latest/userguide.html#class-paths) So is their a way to add new jars in jvm without restarting django server? -
How to get the user object in Django REST via React frontend
So once a User logs into the dashboard I want to also retrieve the user object to populate the dashboard with data accordingly. Right now the login using DJ_rest_auth works just fine, but I don't know how to further fetch data. My approach: User logs in On success the fetch handler calls another fetch getUser that uses the newly set token from local storage to make another API request to get the user instance In Django I have a 1-1 UserProfile model linked to the BaseUser. Also dj_rest_auth stores the token 1-1 to the BaseUser model. Right now the util getUser isn't called at all in the fetch response callback. Also I'm not sure if this is a feasable approach at all. // React Login Component const Login = () => { // Set reducer with empty dicitonary as initial value const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [errors, setErrors] = useState(false); const [loading, setLoading] = useState(true); useEffect(() => { if (localStorage.getItem('token') !== null) { window.location.replace('http://localhost:3000/dashboard'); } else { setLoading(false); } }, []); const submitHandler = event => { event.preventDefault() const user = { username: username, password: password }; fetch('http://127.0.0.1:8000/api/user/auth/login/', { method: 'POST', body: JSON.stringify(user), headers: … -
Best practice for starting and running django server without terminal
Im developing a django erp application and want to run it without stop. If we do runserver from a terminal it may be stopped at a point of time automatically. So what i seek for is to tell the os to run django as it boot up. Can subprocess of python a good idea to call from cron at startup ? -
Django password reset with email using REST APIs
I'm developing a website using DjangoRest and Flutter and I want to add password reset using email. I know that django.contrib.auth has views that help with password reset (PasswordResetView, PasswordResetDoneView, etc). But as long as I see, they return HTML files as a response when you call them in Postman. Is there any way to use the same easy-to-use views but instead of getting HTML files, get an HTTP response so it can be called by the Flutter app? -
Weasyprint img and font not loading correctly
The font config and static image need fixing I'm trying to link the Poppins google font to the rendered pdf. I had it working at one point during a test but now I have progressed further and I can't seem to get the font to load. Also, I have managed to place images in the pdf that are passed through as context from a mode, but the static image and logo that I have placed at the bottom of the template isn't appearing and I can't seem to link it correctly. template <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Foodstah - {{title}}</title> </head> <body> <h1>{{post.title}}</h1> <h3>by @{{post.author}}</h3> <img src="http://127.0.0.1:8000{{post.main_image.url}}" alt=""> <br> <br> <h4 class="inline">Time:</h4> <p class="inline">{{post.cooking_time}}</p> <h4>Ingredients</h4> <p>{{post.ingredients}}</p> <h4>Instructions</h4> <p>{{post.recipe_description}}</p> <footer> <img class="inline" src="{% static 'images/F_blue.png' %}" alt=""> <p class="inline">Recipes from around the globe, powered by Foodstah.</p> </footer> </body> </html> views.py def recipe_to_pdf(request, slug): recipe = Post.objects.get(slug=slug) title = recipe.title context = {} context["post"] = recipe font_config = FontConfiguration() html_template = render_to_string('post/pdf_template.html', context=context) html = HTML(string=html_template) css = CSS( string=""" @font-face { font-family: Poppins; src: url(https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,400;0,700;0,800;1,200;1,400;1,900); } @page { size: A4; /* Change from the default size of A4 …