Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django-credit-card error invalid literal for int() with base 10: b'cc_expiry'
Please I need some assistance on django-credit-card. This is the official doc i was referencing. https://pypi.org/project/django-credit-cards/ This is the error i'm getting, invalid literal for int() with base 10: b'cc_expiry' this is my model class CreditCard(models.Model): cc_number = CardNumberField(_('card number')) cc_expiry = CardExpiryField(_('expiration date')) cc_code = SecurityCodeField(_('security code')) this is my modelform class CreditCardForm(forms.ModelForm): class Meta: model = CreditCard fields = ['cc_number', 'cc_expiry', 'cc_code'] views class CreatCardView(LoginRequiredMixin, FormView): template_name = 'transactions/create-card.html' form_class = CreditCardForm success_url = '/transactions/view-card/' def form_valid(self, form): if form.is_valid(): form.save() print(form.cleaned_data) return super().form_valid(form) -
Django REST | django.db.utils.IntegrityError: NOT NULL constraint failed:
Problem: django.db.utils.IntegrityError: NOT NULL constraint failed: backend_storage.user_id I'm sending POST request with this data: { "password":"foobarbaz", "username":"foo", "additional":"bar", "user_id":2 } models.py class Storage(models.Model): user = models.ForeignKey(Users, on_delete=models.CASCADE) username = models.CharField(max_length=200, null=True, default = None) password = models.CharField(max_length=200, null=False) timestamp = models.DateTimeField(auto_now_add=True) additional = models.CharField(max_length=500, null=True, default = None) -
Django + Postgres: OperationalError FATAL: sorry, too many clients already (as a result of a deliberate attack)
There are many similar questions on Stackexchange but they do not address my particular case. The problem is that there are deliberate attacks on the website with many simultaneous requests. I have mimicked these attacks with a/b testing: ab -k -c 150 -n 90000 'https://www.mywebsite.com/' The website gets down with the following error: OperationalError at / FATAL: sorry, too many clients already The number of max connections allowed on my Postgres instance is 100. Raising it, as recommended in most answers on Stackexchange, is pointless, as there might be significantly higher numbers of requests during the deliberate attacks which we have been suffering lately. I have tried remedying the issue by creating a special middleware caching the number of requests: from ipware import get_client_ip class IPMiddleware: REQUEST_PERIOD_IN_SECONDS = 10 MAX_REQUESTS_IN_PERIOD = 100 TOO_MANY_REQUESTS_BAN_PERIOD_IN_SECONDS = 60 * 2 def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: ip, is_routable = get_client_ip(request) if ip: if cache.get(f'ip_is_banned_{ip}', False): raise PermissionDenied() cache_key = f'requests_made_{ip}' try: cache.incr(cache_key) except ValueError: cache.set(cache_key, 1, self.REQUEST_PERIOD_IN_SECONDS) requests_made = cache.get(cache_key) if requests_made > self.MAX_REQUESTS_IN_PERIOD: cache.set(f'ip_is_banned_{ip}', True, self.TOO_MANY_REQUESTS_BAN_PERIOD_IN_SECONDS) except: pass response = self.get_response(request) return response The order of my middlewares in settings.py is the following: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', …