Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Azure mobile app service keep getting it's pyodbc library version change without any actions
We have a Django/React mobile app that is hosted in Azure with the an app service plan (python 3.8.17) on Linux. 2-3 times a week, it stops working because the version of the pyodbc changes without any action on our side. We need to log into the SSH and switch the library libmsodbcsql-17-10.so.4.1 to libmsodbcsql-17-10.so.2.1 and then everything comes back to normal. What can cause this issue ? We checked if it was planned maintenance or any other Azure service that took action of some sort but couldn't find anything. -
Django unittest. Extract pk of a created object using .post method
Im studying some Python courses and i've got a project fully dedicated to unittest and pytest. The problem I have here is that i use the client.post method to create a note. My reviewer asked me get the note i just created using its pk. Have no idea how to do it. This is the code i currently have : def test_user_can_create_notes(self): response = self.auth_another_author.post(URL_NOTES_ADD, data=self.form_data) self.assertRedirects(response, URL_NOTES_SUCCESS) self.assertTrue(Note.objects.filter( title=self.form_data['title'], text=self.form_data['text'], slug=self.form_data['slug']).exists()) So i need to get the note object by pk and then check with assertEqual if its fields match the self.form_data fields I also tried getting the freshly created object using get and filter by the slug field. But that did not convince my reviewer -
How To Change LDAP Variables?
I need to change django-auth-ldap variables such as AUTH_LDAP_URI with dynamic inputs from user. How do I manipulate these variables in the memory? I tried changing imported variables expecting library automatically detects it. -
IntegrityError FOREIGN KEY constraint failed [In django project ]
While adding user data in DB through a form I created I got this error integrity error at \add_emp and it says foreign key constraint failed I tried deleting dbsqlite3 files, migrations files, and pychache files but that did not work please tell me where I am wrong it's my first time getting this error. enter image description here This is shown after submitting This is the Models.py code from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) This is the views .py code # Create your views here. def index (request): return render(request,"index.html") def all_emp (request): context={"emps":Employee.objects.all(),"roles":Role.objects.all(),"departments":Department.objects.all()} return render(request,"all_emp.html",context) def add_emp(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] salary = int(request.POST['salary']) bonus = int(request.POST['bonus']) phone = int(request.POST['phone']) dept = int(request.POST['dept']) role = int(request.POST['role']) new_emp = Employee(first_name= first_name, last_name=last_name, salary=salary, bonus=bonus, phone=phone, dept_id=dept,role_id=role,hire_date = datetime.now()) new_emp.save() return … -
Which Certificate Authorirties can issue an X.509 certificate for document signing in PEM format?
I am looking to build a custom document signing solution in my Django application using PyHanko. I want to use the certificates from a CA for this purposes. However majority of CAs that I reviewed either offer the complete document signing service or they provide certificate as tokens/Yubikey. Only Digicert is the provider that I could find which allows to download the certificate and then use it manually. Are there any other CAs that allow to download a dcoument signing cert in PEM etc format? -
How can I load Deep learning model only once so that the problem of loading the model every time while calling API in Django is reduced?
I am trying to load the heavy pretrained model which size is larger than 1 GB though API using Django. The model is loaded every time I call API which is time consuming. What can be the solution for this ? I was expecting to load model only once and can use methods while calling API. -
DRF doesnt populate field label when using source
So, I have some model with few fields I want to expose over REST API: class MyModel(models.Model): field1 = models.TextField(verbose_name="Field 1") field2 = models.TextField(verbose_name="Field 2") and have corresponding serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('field1', 'field2') This way it works fine: using GET I retrieve fields values, and using OPTIONS I retrieve secondary fields information (e.g. if the field is required, help text, and label) The problem is that I don't want to expose real fields name, and I want to use some other name instead, for example: field1 and secondField. For that I modify my serializer: class MySerializer(serializers.ModelSerializer): secondField = serializers.CharField(source='field2') class Meta: model = MyModel fields = ('field1', 'secondField') Now I receive correct values on GET, but fields labels are wrong on OPTIONS: for second field I receive "Secondfield" instead of "Field 2" How do I get correct field label when using source? -
django session (i can't carry the data to the next page)
once the login successful , it redirect to the whmcs page and show the success message too but it's not show the first name and last name of the user why ?? please help me viewa.py ( `def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] api_url = 'https://www.chltech.net/manage/includes/api.php' api_username = 'XMBoFf3A3RvUCQnsJaQEHjQefx9W5FWC' api_password = '4yCdTGPvQWS2tnRFYS6CgIG7HMcmtLWZ' api_action = 'validatelogin' api_params = { 'username': api_username, 'password': api_password, 'action': api_action, 'responsetype': 'json', 'email': email, 'password2': password, } response = requests.post(api_url, data=api_params) if response.status_code == 200: data = response.json() if data['result'] == 'success': user_first_name = data.get('firstname', '') user_last_name = data.get('lastname', '') request.session['user_first_name'] = user_first_name # request.session['user_last_name'] = user_last_name print(user_first_name,user_last_name) messages.success(request , "login successful") return redirect('whmcs') else: messages.error(request, "Invalid email or password.") else: messages.error(request, f"Login failed: HTTP Error {response.status_code}") form = CustomAuthenticationForm() return render(request, 'login.html', {'form': form}) def whmcs(request): user_first_name = request.session.get('user_first_name', '') user_last_name = request.session.get('user_last_name', '') return render(request, 'whmcs.html', {'user_first_name': user_first_name, 'user_last_name': user_last_name})` ) whmcs.html ( <!DOCTYPE html> <html> <head> <title>Client Emails</title> </head> <body> {% block content %} <h1>Welcome, {{ user_first_name }} {{ user_last_name }}</h1> {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alter alter-danger"> {{message}} </div> {% else %} <div class="alert … -
django-livereload-server installation
I am new to django and trying to install django-livereload-server In the installation guide, somewhere says: You need to inject the loading of the livereload javascript. You can do this in one of two ways: Through middleware by adding 'livereload.middleware.LiveReloadScript' to MIDDLEWARE_CLASSES (probably at the end): MIDDLEWARE_CLASSES = ( ... 'livereload.middleware.LiveReloadScript', ) Through a templatetag in your base.html (or similar) template: {% load livereload_tags %} ... {% livereload_script %} For the first solution, I've noticed there is no MIDDLEWARE_CLASSE = () in the settings.py file (django 4.2.4). Theres only a MIDDLEWARE_CLASSE = [] list, and putting 'livereload.middleware.LiveReloadScript' in it does not work. (Live reload runs, but can't refresh the page.) Where should I put 'livereload.middleware.LiveReloadScript' to get it to work? Whats the instruction for the second solution? I don't see the base.html in my project/ app. Should I create it myself? Appreciate any help! Using: VSCode, django, enve, Installed packages: asgiref 3.7.2 beautifulsoup4 4.12.2 Django 4.2.4 django-livereload-server 0.4 dnspython 2.4.2 et-xmlfile 1.1.0 greenlet 2.0.2 pip 23.2.1 setuptools 63.2.0 six 1.16.0 soupsieve 2.4.1 sqlparse 0.4.4 tornado 6.3.3 typing_extensions 4.7.1 tzdata 2023.3 -
How to check if field in a table object is equal to specific string in django template language?
model name=ApplicationForm test_selection is one of the charfiled in ApplicationForm(table) views.py applied_student=get_object_or_404(ApplicationForm, dob=dob,id=app_id) i am using this query in view and sending this data to my template... I want to check if applied_student.test_selection=="selected" but its not working i tried using {% if student.test_selection =="selected" %} If worked {% endif %} i want to compare this filed with stored string value in table in djanog template -
Customizing JWT token claims in Django
I'm trying to customize my JWT token and what ever I do I got an error like this : ImportError: cannot import name 'MyTokenObtainPairView' from 'base.api.serializers' (D:\Anaraki\api\bakend\base\api\serializers.py) here is my serializers.py file: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer my urls.py file: from django.urls import path from . import views from rest_framework_simplejwt.views import (TokenRefreshView, TokenObtainPairView) from .serializers import MyTokenObtainPairView # to customize the token we use this one insted . urlpatterns = [ path('',views.getRoutes), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] I did everything's that doc said but I still got this ... error, please help me. -
In Django, which has faster and better performance beween ".filter(a).filter(b)" and "Q objects" and "or/and queries" and "keyword queries"
Simply put, what is the order of performance and speed among the following similar looking queries in the Django ORM? .filter(a).filter(b) instances = Model.objects.filter(a=A).filter(b=B) Q objects instances = Model.objects.filter(Q(a=A) & Q(b=B)) or/and queries instances = Model.objects.filter(a=A) & Model.objects.filter(b=B) keyword queries instnaces = Model.objects.filter(a=A, b=B) Thank you, and please leave any comments below. AND please don't copy and paste chatgpt or any other ai services. -
How to implement SignOut request NextAuth with Django REST API?
I am trying to create frontend on next js for my Django REST API. I use Next Auth for frontend auth and token auth for backend api. For login I used api for example www.mysite.com/login and I got token and user data, so for logout I used api endpoint example www.mysite.com/logout it is needed to pass token in headers. So how to implement logout? import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" import api from "../baseaxios" const SIGN_IN_HANDLERS = { "credentials": async (user, account, profile, email, credentials) => { return true; }, }; const SIGN_IN_PROVIDERS = Object.keys(SIGN_IN_HANDLERS); const handler = NextAuth({ providers: [ CredentialsProvider({ name: 'Credentials', credentials: { username: { label: "Email", type: "email", placeholder: "Email" }, password: { label: "Password", type: "password" } }, async authorize(credentials, req) { const res = await api.post("/login", { body: JSON.stringify(credentials), headers: { "Content-Type": "application/json" } }) const user = await res.json() if (res.ok && user) { return user } return null } }) ], pages: { signIn: '/login', }, callbacks: { async signIn({user, account, profile, email, credentials}) { if (!SIGN_IN_PROVIDERS.includes(account.provider)) return false; return SIGN_IN_HANDLERS[account.provider]( user, account, profile, email, credentials ); }, async jwt({user, token, account}) { // If `user` and `account` are set … -
django, problem with the - contact - keyword
I am new to django and trying to create a contact page. Here is my urls.py in the app folder: urlpatterns = [ path("contacts", contact_view), ] and my views.py contact_view(request): return HttpResponse('<h1>Contact Page</h1>') Everything works fine when trying: http://127.0.0.1:8000/contacts I've noticed when I change contacts to contact as the following: urlpatterns = [ path("contact", contact_view), ] and then try http://127.0.0.1:8000/contact, it gives: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/contact/ Using the URLconf defined in config.urls, Django tried these URL patterns, in this order: 1. admin/ 2. 3. about 4. contact The current path, contact/, didn’t match any of these. I've tried restarting the server and the VSCode. Not working! Appreciate any help on this. Windows 11, VSCode, django 4.2.4 -
IntegrityError FOREIGN KEY constraint failed [In django project ]
enter image description here While adding user data in DB through a form I created I got this error integrity error at \add_emp and it says foreign key constraint failed I tried deleting dbsqlite3 files, migrations files, and pychache files but that did not work please tell me where I am wrong it's my first time getting this error. from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) -
Behave Django Testing - Behave testing only uses dev database instead of test database
How to properly set up behave-django so that it can use a test database loaded with data using factories? Please have a look to the code I have written. environment.py environment.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SampleDemo.settings') django.setup() from behave import fixture, use_fixture from django.test.runner import DiscoverRunner from django.test.testcases import TransactionTestCase, TestCase from src.core.models import User class BaseTestCase(TransactionTestCase): @classmethod def setUpClass(cls): User.objects.create_superuser(username='setuadmin', password='admin', email='setuadmin@admin.com') super(BaseTestCase, cls).setUpClass() @classmethod def tearDownClass(cls): User.objects.filter().delete() super(BaseTestCase, cls).tearDownClass() @fixture def django_test_case(context): context.test_case = BaseTestCase context.test_case.setUpClass() yield context.test_case.tearDownClass() del context.test_case def before_all(context): django.setup() context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() yield context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() def before_scenario(context, scenario): use_fixture(django_test_case, context) feature file Feature: Polish Grading CRUD Test CRUD methods of Polish-Grading Module REST API testing framework Background: Given I set REST API server url Scenario: User login with valid credentials Given I provide user authentication credentials And I make an http post call to "/user/login/" api Then I must get a response with status code 200 and a jSon object with token Scenario: fetch grading details Given I provide the params to fetch polish-grading details When I set the HEADER param request content type as "application/json". And I send HTTP GET request as "/polish/fetch-grading/" Then I receive the Valid … -
Django Post Office - How can I add a foreign key in the Email model that references the Client model?
I'm utilizing the django-post-office library in my Django project. I aim to link the library's existing Email model to my Client model, ensuring that while a single client can have multiple emails, each email can only be linked to one client. Is this feasible? Interestingly, ChatGPT provided a solution, but it mentioned parameters (create_models, model_class) that don't exist in the library therefore the code below doesn’t work. However, I'm curious if ChatGPT might have been hinting at an approach I am not aware. Suggestions how to solve it ? from post_office.models import Email as PostOfficeEmail class ClientEmail(PostOfficeEmail): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='emails') from post_office import mail def send_client_email(client, subject, message): mail.send( recipients=[client.email], sender='your_sender_email@example.com', subject=subject, message=message, create_models=True, # This will create an Email model instance model_class=ClientEmail, # Use our extended model ) # Associate the email with the client email = ClientEmail.objects.last() email.client = client email.save() -
Django: calling .only() on my model causing infinite loop?
I am using .only to fetch the required fields from my model, it seems like my __init__ method causing a inifinite loop when calling only on this model, and this is my model: class PodcastEpisode(models.Model): audio_metadata = models.JSONField(null=True) featured_artists = models.ManyToManyField(to=User, related_name='featured_artists') podcast_series = models.ForeignKey(to=PodcastSeries, on_delete=models.CASCADE, null=False) published = models.BooleanField(default=False) published_at = models.DateTimeField(blank=True, null=True) _original_audios = None # To store current data _published = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self._original_audios = self.audio_metadata # self._published = self.published When I commented these lines self._original_audios = self.audio_metadata and self._published = self.published, it doesn't cause inifinite loop. I am not sure how this is happening even if I have included audio_metadata in my .only() fields. This is my query PodcastEpisode.objects\ .filter(id__in=id_list).prefetch_related(*prefetches).only(*['id' 'audio_metadata']) Please suggest me how do I use .only() and where should I place these _original_audios and _published variables. -
How to hide django default filters from others except admin user?
I have below User graphql API endpoint in my application. Query class Query(UserQuery, graphene.ObjectType): all_users = DjangoFilterConnectionField( UserType, filterset_class=UserFilter) Type class UserType(DjangoObjectType): class Meta: model = User fields = "__all__" interfaces = (graphene.relay.Node,) Filter class UserFilter(FilterSet): user_name_search = CharFilter( method='user_name_filter', label='User Name Search' ) class Meta: model = User fields = [ 'user_name_search', 'user_id', 'first_name', 'last_name', 'email', 'gender', 'height', 'rating', 'phone', 'city', 'state', 'country', 'active', 'deleted', ] def user_name_filter(self, queryset, name, value): return User.objects.filter( Q(first_name__icontains=value) | Q(last_name__icontains=value) ) On API side it shows below filtes by default, I need to hide the filters like first, last, before, after, offset because I don't want to expose all my data to everyone on the internet. So basically if is_superuser is true then only those filters should work. Please guide how to handle this scenario. -
Django uploads Gif as JPG despite a function to add it as video
I'm trying to upload a .gif to my django 3.2 api. I have already ran troubleshoots through Postman and came to the conclusion that my flutter app sends it as a .gif and it gets returned as a .jpg. The problem is on the backend. Here is my relevant code from add media function which checks for file_meme subtype and converts the incoming .gif to a video(There is a separate block for checking if its video and add the video) : def add_media(): if file_mime_subtype == 'gif': if is_in_memory_file: file = write_in_memory_file_to_disk(file) temp_dir = tempfile.gettempdir() converted_gif_file_name = os.path.join(temp_dir, str(uuid.uuid4()) + '.mp4') ff = ffmpy.FFmpeg( inputs={file.temporary_file_path() if hasattr(file, 'temporary_file_path') else file.name: None}, outputs={converted_gif_file_name: None}) ff.run() converted_gif_file = open(converted_gif_file_name, 'rb') temp_files_to_close.append(converted_gif_file) file = File(file=converted_gif_file) file_mime_type = 'video' has_other_media = self.media.exists() self.save() I'm not sure where the problem is. From my limited understanding, it is taking only the first frame of the .gif and uploading it as an image. -
How to upload multiple images or files in a single input field using Django forms?
Could you please provide more context or specific details about the issue you're facing with Django forms? This will help me understand your problem better and provide you with a more accurate solution. I attempted to implement the MultiFileInput widget from the django-multiupload package within my Django form. I expected the widget to allow users to upload multiple images or files through a single input field. However, I faced challenges integrating this widget within my existing form structure. While the widget appeared on the page, I couldn't figure out how to handle the uploaded files and save them to the database. The documentation for the package lacked detailed examples for this specific use case. n short, I tried using the MultiFileInput widget but struggled with its integration and file handling. Any guidance or code snippets to achieve this functionality would be greatly appreciated -
Multiple User Foreign Keys to Same Model?
I'm attempting to create a simple web application (first django personal project) for my friends and I to log our casual sporting bets against eachother. Currently I have the model like this using django's auth User model: class Bet(models.Model): bettor1 = models.ForeignKey(User, related_name='bets', on_delete=models.CASCADE) bettor2 = models.CharField(max_length=256) bet_description = models.TextField() bet_amount = models.PositiveIntegerField() win_amount = models.PositiveIntegerField() create_date = models.DateTimeField(auto_now=True) Currently bettor1 is correctly linked to the user that is logged into the application, but I would like to make it so that bettor 2 is also a foreign key (i think?) connecting to another user's account that exists on the application. (So bettor 1 can choose the opponent he is wagering against from a dropdown menu of the other users with existing accounts). How can I do this? Tried setting another foreign key to user but got errors. Not sure how this is done. -
Non existing value for foreign key in django
I would like know if I can make django accept values for foreign key that doesn't exist in the column referenced. The problem in the business logic is that a model can point to the phone number of a user that doesn't exist yet -
cannot import name in a file?
Hello I am trying to run my django application but its saying: cannot import name 'd' from 'niu' (C:\Users\amber\Umaido\niu_init_.py) which is strange. I have created d in my code file: [ and importet it than into views.py ( The problem now is that it usually works on the Terminal but my Command prompt Terminal is telling me that its an error. I have tried to change form code import d to from . import d but it does not work either -
How to reload the app on Django after changed files?
I have been studying Django lately. The novice tutorials are good, but from a student perspective, there are some steps which are black boxes. One of them is file monitoring: every time I need to update the application, my heart beats faster, I stop the ongoing process and run python manage.py runserver. In real world, I have worked with solutions using Django, but was never clever enough to know how the github pull requests would update the actual hosted app. Would you please help me understand this knowledge gap? Remark: On NodeJS, we use the library nodemon to monitor changes on files.