Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a class to a field tag in a Django form
I would like to add a bootstrap class to a label of the input field of my form, I can add classes to the input field but I could not find a guide on how to add a class to the label in the form declaration, can you help me? Thanks class MyForm(forms.Form): file = forms.FileField (label="Choose File", widget=forms.ClearableFileInput(attrs={'multiple': True, 'class': 'custom-file-input'})) -
Cannot query "vendor@gmail.com": Must be "CustomUser" instance in Django
views.py @login_required def become_vendor(request): # vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': # vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendordetailform.is_valid(): # if vendorform.is_valid(): # new_user = vendorform.save() vendordetailform.instance.vendoruser = request.user request.user=vendordetailform.save() print(request.user)-#vendor@gmail.com vendordetails = VendorDetails.objects.get(vendoruser_id=request.user) print(vendordetails) user = CustomUser.objects.filter(id=request.user.id) vendordetails = VendorDetails.objects.filter(vendoruser_id=user.id) vendor_details = vendordetails[0].vendor_details.all() print(vendor_details) # vendor_user = VendorDetails.objects.filter(vendoruser_id=user) user.is_active = False user.save() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: # vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() return render(request, 'vendor/become_vendor.html', {'vendordetailform':vendordetailform}) I want to false the logged in user that the user has related field with the User model. Querying the user id that related with this email id in another model causes issue. -
How to customize the admin form for a custom image model in Wagtail CMS?
I need to add a string based unique ID to Wagtail’s image model. These IDs are a relatively short combination of letters, numbers and punctuation, e.g. "AS.M-1.001". So I am using a custom image model with Django’s standard CharField for that with the argument unique=True. But the editing form unfortunately does not check if the ID is unique. So I can use the same ID for multiple images. This check for uniqueness does work in any other standard form in Wagtail, e.g. the Page model. But not for the image model. from django.db import models from wagtail.images.models import Image, AbstractImage class CustomImage(AbstractImage): custom_id = models.CharField(max_length=32, unique=True, null=True, blank=True) admin_form_fields = ( 'custom_id', ) + Image.admin_form_fields My approach would be to override the editing form with a custom one to display more warnings and errors, like you can do with base_form_class for Wagtail’s Page model etc., as documented here. I tried both wagtail.admin.forms.WagtailAdminModelForm as well as wagtail.images.forms.BaseImageForm. from wagtail.images.forms import BaseImageForm from wagtail.admin.forms import WagtailAdminModelForm class CustomImageForm(WagtailAdminModelForm): # add more logic here pass class CustomImage(ArtButlerIDMixin, AbstractImage): ... base_form_class = CustomImageForm Both lead to the same exception: raise AppRegistryNotReady("Models aren't loaded yet.") So a tried to resort the apps in my settings … -
how to realise redirect to same page in Django views?
I am writing an online store in Django. How do I redirect to the same page? This is needed to remove an item from the popup cart. The delete from cart function: def cart_remove_retail(request, slug): cart = Cart(request) product = get_object_or_404(Product, slug=slug) cart.remove(product) return #??? when i try: return HttpResponseRedirect(request.path_info) I get round-robin query. Thanks! -
How to connect MYSQL Data Base to my Django app via an ssh
How to connect my Django app to MySQL DB via ssh. I have a MySQL DB hosted in Namecheap. I can connect to it via ssh using a terminal, is there any way I can do that?? -
HTTPS with Django Gunicorn in AWS ECS Container with Load Balancer
i have a running Docker Container with Django and Gunicorn in ECS with a Load Balancer in front. Everything was working fine until I tried to switch to https. The result is a 504 Gateway Time-out Error. Question is, do I need Nginx with self certificate to handle https or can I do it with AWS Load Balancer ? Thanks, Christian -
Django raw function security (SQLi)
I have been reading through the Django docs & am not sure I am clear whether the below is safe from SQLi. I can see we can also use the cursor Does anyone have any view on this? distinct_skills = skills.objects.raw(''' SELECT distinct category as id from voxi_skills where creator = %s ''', [request.user.username]) -
How to path absolute path for img attribute in html
sorry for this dummy question but i am having a trouble in my django and react app. i have an endpoint which serves the image name but the image is saved in my local directory and in my react app i just want to append the file name like this function Condition(props) { let src = C:/Users/25191/Desktop/python_projects/doctorsolve/Drsove/media/media/images/HealthCondition/${props.meddata.image} return ( <> <div className="item"> <a href="#"> <img src={src} alt="medicine item image" /> <div className="desc"> <p className="medicinename">{props.meddata.title}</p> </div> </a> </div> </> ); } -
AttributeError: 'AnonymousUser' object has no attribute 'profile'
I have built a Django app and it worked well. When I had run an another django app in a port(localhost:8000) and tried the app I built on the port, it says error like this. AttributeError: 'AnonymousUser' object has no attribute 'profile' Here is my code: class DashboardView(auth_views.LoginView): template_name = "dashboard/home.html" verify_email_required = 'registration/verify_email_required.html' form_class = ProfiledAuthenticationForm def get(self, request, *args, **kwargs): # context = {'form': self.form_class()} context = self.get_context_data() context['form'] = self.form_class() if request.user.profile.is_verified: return render(request, self.template_name, context) else: return render(request, self.verify_email_required, context) Note: Initial when I built the app, it worked well, but for now it takes error. when user does not log in, the homepage was redirected to login page. -
How to get Client's IP in Django Views
I have piece of code to extract client IP in Django views. However my code is executing only this ip = request.META.get('REMOTE_ADDR') and I am always getting 127.0.0.1 as IP. Most of the solutions I have searched used below mentioned code. Any other way to do it?? def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip -
Upload XML Files in Django, Parse XML & Compare with existing models dataset
Can someone give me a better approach for below use case please ? upload XML file Scan XML file with specific tags Store required data in which format ? (I thought of building JSON dump ?) I have data in different models for different components. How can i compare data that i have in step3 with django models and produce some output ? ( Sort of data comparison ) Note : JSON Dump which i get at step 3 is full dump of required data and data at step 4 is being referred to small small chunks of data which has to be combined and compared against recently uploaded file JSON Dump -
Using a GIN index in Django which was created in postgreSQL
I have created a model in Django. class MyModel(models.Model): features = TextField(blank=True, default='') There are several possible ways to store the data in the feature field. Some examples below. feature1;feature2 feature1, feature2 feature1,feature2 And so on. I created a GIN index for that field. That's postgreSQL code I used inside migrations.RunSQL. CREATE INDEX features_search_idx ON "mymodel" USING gin (regexp_split_to_array("mymodel"."features", E'[,;\\s]+')); The migration worked and I managed to find that index using, for example, \di+ mymodel_features_search_idx. Now I would like to use that created index to filter my queryset. I thought something like the code below would work MyModel.objects.annotate(F('features_search_idx')).filter(features_search_idx__in=['Feature1', 'Feature2', 'Feature3'].count() Unfortunately an error occurred django.core.exceptions.FieldError: Cannot resolve keyword 'feature_search_idx' into field.. How can I use my created index? -
how to access an api in react js with axios on same server like django + react js
I have connected the frontend(ReactJS) with backend(python) using Django and axios. How can i post an Api on the Django app using axios from React JS? -
Django OTP TOTP - how to display QR code in template
I have successfully implemented two-factor-auth package to my web app however I would like to display QR code to a template when a user is logged in but am unable to do so as it stands. This package uses wizard forms and when a user is prompted to setup two factor the QR code is displayed during setup for them to scan on their chosen device but not sure how to use the QR code for later use in another template. I found the follwing piece of code from the wizard template which I tried to use but says page not found: <div class="d-flex justify-content-center"> <p><img src="{{ QR_URL }}" alt="QR Code" /></p> </div> Page not found error Using the URLconf defined in wfi_workflow.urls, Django tried these URL patterns, in this order: admin/ account/login/ [name='login'] account/two_factor/setup/ [name='setup'] account/two_factor/qrcode/ [name='qr'] The current path, account/two_factor/qrcode/, matched the last one. But I can view the QR code for users via Admin panel under: Otp_Totp TOTP devices Click on user and QRCode link is at the bottom of page Anyone know how to go about displaying the QR code only in another template? If more info is required do let me know. Thanks -
Django User Manager Not Checking Model Validators
I'm using a custom django user model. I have created everything and all seems perfect until I try to call the create_user from a registration page on the template. It is creating the user without taking the validators I have placed in the models into consideration. The validators are working just fine until I try to use the create_user action. def validate_reg(value): try: x = SignUpAccess.objects.get(reg_key=value) if x.is_used == True: raise ValidationError( message='Your validation number is used already', ) except SignUpAccess.DoesNotExist: raise ValidationError( message='Your validation number does not exist', ) class User(AbstractUser): username = None email = models.EmailField( unique=True, max_length=75, # db_index=True, primary_key=True, verbose_name='email address' ) reg_number = models.CharField( max_length=12, unique=True, null=True, validators=[validate_reg] ) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' objects = UserManager() As seen above I have added a validator in the registration number to make sure only those with a valid registration number can create an account on the site. This works perfectly when I try to create a user from admin (which is really pointless). As with custom user models, I have a user manager class UserManager(BaseUserManager): def create_user(self, … -
Cannot store user instance in the related model in django?
views.py def become_vendor(request): # vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': # vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendordetailform.is_valid(): # if vendorform.is_valid(): # new_user = vendorform.save() print("hello") vendordetailform.instance.vendoruser = request.user print("hello1") request.user=vendordetailform.save() print("hello2") request.user.is_active = False request.user.save() user_details = CustomUser.objects.filter(id=request.user.id) vendor_details = user_details[0].vendor_details.all() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: # vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() Here I save the user store details in the foreign key related model after the user logged in. Here I face issue in the line vendordetailform.instance.vendoruser = request.user. The user instance is not stored and user.is_active=False is not happening. the error is Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000158FEFB15B0>>": "VendorDetails.vendoruser" must be a "CustomUser" instance. -
JavaScript POST non-API request with repeated keys in payload
Javascript. POST request. It is not an API request (axios or fetch), but the old classical request. I need a payload like ...&_selected_action=5&_selected_action=10. So I think I cannot use a form submitting technique here. With a single occurence ...&_selected_action=5 I am able to do it, everything works well. For the repeated value I can create the string by hand or by URLSearchParams().toString() but I am not able to send it. Any idea? More details. I need create this request in Django+Vue application which partially replaces the old school Django Admin. The ListView is replaced using Vue and now I want to reuse the actions where Django Admin uses Post request formatted as above. So with single selected row in list I am able to do it, but with 2+ selected rows I cannot find a good way how to do it. -
Unauthorized: /auth/users/
i am using react in the frontend and Django in the backed and am trying to register user, but when I try creating new user I get error Unauthorized: /auth/users/ [02/Dec/2021 12:29:27] "OPTIONS /auth/users/ HTTP/1.1" 401 58 The frontend looks somewhat like this export const signup = (first_name, last_name, email, password, re_password) => async dispatch => { const config = { headers: { 'Content-Type': 'application/json' } }; const body = JSON.stringify({ first_name, last_name, email, password, re_password }); try { const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/users/`, body, config); dispatch({ type: SIGNUP_SUCCESS, payload: res.data }); } catch (err) { dispatch({ type: SIGNUP_FAIL }) } }; -
How to add a timepicker only in my django project?
I am new to django and web development. I want to implement a timepicker only for my website. I don't know how to add it to my models and forms? and how should I implement the timepicker whether using bootstrap or jquery. Is there any easy way to do that? forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content','chamber','address','fees','days','hours'] widgets = { 'hours':forms.DateField(widget=forms.DateInput(attrs={'class':'timepicker'})) } models.py class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField('Doctor\'s Name',max_length=200) content = models.CharField('Specialty',max_length=200) chamber = models.CharField('Chamber\'s Name',max_length=200) address = models.CharField('Address',max_length=100) fees = models.IntegerField(default=0) days = myFields.DayOfTheWeekField() hours = models.DateField('Visiting Hours') liked = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='liked') date_posted = models.DateTimeField(default=timezone.now) objects = PostManager() class Meta: ordering = ('-date_posted', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) I want to add a timepicker in the hours fields and post it to the models too. Don't know what models.field should I use and what form since I am at the very beginning level of django The timepicker should look somewhat similar like this. -
User profile update using dj-rest-auth + allauth
I'm trying to implement authentication using dj-rest-auth library, Everything works fine up to now but when i try to update user it says user with same name exist. user/ is my url which give me a view with PUT and PATCH method. But bot are not working and if i change my username it updates. urls.py urlpatterns = [ # path('', views.login, name="login"), path('login/', LoginView.as_view()), path('logout/', LogoutView.as_view()), path('register/', RegisterView.as_view()), path('verify-email/', VerifyEmailView.as_view(), name='rest_verify_email'), path('account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), path('account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), path('user/', UserDetailsView.as_view()), path('google/connect/', GoogleLogin.as_view(), name='google_connect') ] models.py USER_TYPE_CHOICE = ( ('admin', 'admin'), ('student', 'student'), ('instructor', 'instructor'), ) class CustomUser(AbstractUser): phone = models.CharField(max_length=12) user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICE, default='student') # class UserProfile(models.Model): # user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete=models.CASCADE) # # custom fields for user # full_name = models.CharField(max_length=100) # profile_pic = models.ImageField() serializers.py from dj_rest_auth.serializers import UserDetailsSerializer, PasswordResetSerializer from rest_framework import serializers from django.conf import settings from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from dj_rest_auth.registration.serializers import RegisterSerializer from .models import * from allauth.account.forms import ResetPasswordForm, ResetPasswordKeyForm class CustomRegisterSerializer(RegisterSerializer): phone = serializers.CharField(required=True, max_length=100) def get_cleaned_data(self): data_dict = super().get_cleaned_data() data_dict['phone'] = self.validated_data.get('phone', '') data_dict['user_type'] = self.validated_data.get('user_type', '') return data_dict class CustomUserDetailsSerializer(UserDetailsSerializer): class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + \ ('phone', 'user_type', ) class CustomPasswordResetSerializer(PasswordResetSerializer): … -
Django rest framework - serializer for dictionary structured payload
I'm trying to create a Serializer for a payload that looks something like this - { "2fd08845-9b21-4972-87ed-2e7fd03448c5": { "operation": "Create", "operationId": "356f6501-a117-4c8d-98ce-dcb4344d481b", "user": "superuser", "immediate": "true" }, "fe6d0c85-0021-431e-9955-e8e1b1ebc414": { "operation": "Create", "operationId": "adcedb2f-c751-441f-8108-2c29667ea9cf", "user": "employee", "immediate": "false" } } I thought of using DictField, but my problem is that there isn't a field name. it's only a dictionary of keys and values. I tried something like: class UserOperationSerializer(serializers.Serializer): operation = serializers.ChoiceField(choices=["Create", "Delete"]) operationId = serializers.UUIDField() user = serializers.CharField() immediate = serializers.BooleanField() class UserOperationsSerializer(serializers.Serializer): test = serializers.DictField(child=RelationshipAuthorizeObjectSerializer()) But again, there isn't a 'test' field. -
Connecting mysql to django project [closed]
I am displaying some chart values through js file in the django project statically. I want my js to fetch it from mysql. What should I do? Thanks. -
Django: Renaming Models, M2M Table not renamed
TLDR: Models moved to a new app. After migrating M2M relation refers to table that does not exist. Previous M2M table was not renamed. Django Version: 3.2.3 Scenario: I am refactoring a Django application. In this process I have moved some models to a new app. To do so, I renamed the tables as described by Haki Benita, using SeparateDatabaseAndState. One of the models Studentsin the new app has a field with Many2Many relationship to another model Teachers (which I also moved to the new app). oldapp/migrations/000X_auto_XXX.py operations = [ ... migrations.SeparateDatabaseAndState( state_operations=[ migrations.DeleteModel( name='Students', ) ], database_operations=[ migrations.AlterModelTable( name='Students', table='newapp_students' ) ] ), migrations.SeparateDatabaseAndState( state_operations=[ migrations.DeleteModel( name='Teachers', ) ], database_operations=[ migrations.AlterModelTable( name='Teachers', table='newapp_Teachers' ) ] ), ... ] newapp/migrations/0001_initial.py operations = [ ... migrations.SeparateDatabaseAndState( state_operations=[ migrations.CreateModel( name='Teacher', fields=[...], options={...}, ) ], database_operations=[] ), migrations.SeparateDatabaseAndState( state_operations=[ migrations.CreateModel( name='Students', fields=[ ... ('teachers', models.ManyToManyField(blank=True,related_name='students', to='newapp.Teachers')), ... ], options={...}, ) ], database_operations=[] ), ... ] After running python manage.py migrate all the Models got renamed (so far so good).. Problem: The automatically generated table for Many2Many was not renamed (oldapp_students_teachers). However, the model in the new app refers to a table in the new app (newapp_students_teachers) that does not exist. I did some … -
Why is my static CSS file working fine but not javascipt in Django?
I'm new to Django. I'm trying to add a javascript for my navbar. Browser is reading static CSS file properly. But it looks like browser is ignoring my static javascript file. Here is my code: Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] Index.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"> <link rel='stylesheet' type='text/css' href="{% static 'style.css' %}"> <script type='text/javascript' src="{% static 'style.js' %}"></script> <title>{% block title %}{% endblock title %}</title> </head> To check whether javascript is working properly I have only put a alert box. But still it is not showing alert box. Config.js alert("Checking"); -
Static files from AWS not served when they contain a Django {{variable}}
I have a Django App, deployed on Heroku with AWS S3. All static and dynamic files are being served, except when the static file name contains a Django variable. <div class="sibling" id="left"> <a href="{% url 'showtree' sibling_left_id %}"> <img src="{%static '/img/siblingsLeftFrame'%}{{no_siblings_left}}.png"> </a> </div> The generated URL should be (for example): ...amazonaws.com/img/siblingsLeftFrame02.png But looks like this: ...amazonaws.com/img/siblingsLeftFrame?X-Amz-Algortihm=AWS-4-etc.(credentials, date etc.).png Locally it works, but on Heroku/AWS I get a 403 Response. Is this a CORS problem? Here are the settings: INSTALLED_APPS = [ ... "corsheaders", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True