Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-allauth : prevent user to provide alternative email when logging using social account
I use django-allauth with google and facebook providers and the following options: SOCIALACCOUNT_AUTO_SIGNUP=True SOCIALACCOUNT_EMAIL_VERIFICATION="none" With these settings, django-allauth will use the email provided by the 3rd-party app (Facebook, Google), unless it is already used in an existing account. In this case the user can choose whatever email. I would like an error message instead of that, saying that the address is already in use since I do not want to validate email with social accounts (using social accounts should be handy). How to prevent using social accounts that are associated with an address which is already registered? -
How do I solve this Django HttpResponse error please?
My problem is that in the templates and in the CMD I become a None return instead the images. The views: class AddProductImages(TemplateView): template_name = "addimages.html" def post(self, *args, **kwargs): try: images = self.request.FILES.getlist('images') product = Product.objects.get(id = self.kwargs['pk']) for image in images: product_images = Images.objcts.create( product = product, images = image ) return redirect('index') except Exception as e: print(e) The urls: path('addimages/<int:pk>/', AddProductImages.as_view(), name="addimages"), The templates: <div class="container my-5"> <br /> <h1>ADD IMAGE</h1> <br /> <hr /> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="images" id="" class="form-control" multiple> <br> <button type="submit" class="btn btn-sm btn-primary my-3">Submit</button> </form> </div> The results: """ The result is so: what's the problem please? ValueError: The view photo.views.AddProductImages didn't return an HttpResponse object. It returned None instead. [31/Aug/2022 22:08:11] "POST /addimages/1/ HTTP/1.1" 500 65400 """ So, could someone check this please? Thanks! -
Does @transaction.atomic follow functon calls
I want to confirm my theory. I was reading the docs, but maybe I am not reading correctly Let's say we have @transaction.atomic def create(...): few queries... func_a() return def func_a(): also running few queries... If queries fail inside func_a will transaction atomic rollback? I am trying to figure out if it wraps the whole execution flow or just the create function in this scenario. Sorry if my question is a bit silly -
How to remove pk in django datalist?
I output datalist, but output pk. I read that it can be removed in data-value like this https://stackoverflow.com/a/48076273/9653855 How can I rewrite the code so that my datalist is displayed in this format <option data-value="1" value="DjangoOneLove"></option>? my forms class ListTextWidget(forms.Select): template_name = 'include/_forms_orders_datalist.html' def format_value(self, value): if value == '' or value is None: return '' if self.is_localized: return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidget() class SimpleOrderAddForm(forms.ModelForm): #service = forms.ModelChoiceField(queryset=Service.objects.all(), widget=ListTextWidget()) service = ChoiceTxtField(queryset=Service.objects.order_by('-used')) class Meta: model = Orders fields = ['service'] my forms_orders_datalist.html <input id="ajax_input_{{ widget.name }}" list="{{ widget.name }}" autocomplete="off" {% if widget.value != None %} name="{{ widget.name }}" value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %}> <span class="badge rounded-pill bg-warning text-dark" id="ajax-{{ widget.name }}" name="ajax-{{ widget.name }}"></span> <datalist id="{{ widget.name }}"> {% for group_name, group_choices, group_index in widget.optgroups %} {% if group_name %} <optgroup label="{{ group_name }}">{% endif %}{% for option in group_choices %} {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} </optgroup>{% endif %}{% endfor %} </datalist> -
Django, Assign specific fuction tomodel field and then call it
I have a model built like this class ApiPartner(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, verbose_name=_('Name')) api_key = models.CharField(max_length=50, verbose_name=_('API key'), null=True) secret_key = models.CharField(max_length=50, verbose_name=_('Secret key'), null=True) client_key = models.CharField(max_length=50, verbose_name=_('Client key'), null=True) endpoint = models.CharField(max_length=50, verbose_name=_('Endpoint'), null=True) logo = models.ImageField(upload_to='logos/', null=True) evey API partner has its own method to retrieve data, for example def get_youtube_posts(endpoint,api_key): results=list(requests.get(endpoint+'?key='+api_key).json()) return results[0:50] def get_instagram_posts(endpoint,api_key,secret_key): return requests.get(endpoint+'?key='+api_key+'&secret='+secret_key) the question is: how do i assign the 'get_posts' function to the model so i can call a generic ApiPartner.get_posts() and it will retrieve the posts using the given function? I'm thinking about like a models.FunctionField but i know that doesn't exist. I think this is more a logical problem than a technical one but i can't find a way. Thank you -
How to convert this method in django-rest-framework
I've already done this method in django. But I wanna convert this in django-rest-framework. I'm not how to do this can any one help me regarding this . I want to know how to build the serializers and views for this. At the same time how to send additional data in this itself sorry the code being dirty thank you in advance... models.py class User(AbstractUser): ADDCHKS_ID=models.CharField(max_length=16, blank=True, null=True) is_active=models.BooleanField(default=False,blank=True, null=True) is_excutive=models.BooleanField(default=False,blank=True, null=True) class ExcutiveRegistration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) '''Personal Details''' First_name = models.CharField(max_length=100,null=True ,blank=True) Last_name = models.CharField(max_length=100,null=True ,blank=True) DOB = models.DateField(max_length=100,null=True ,blank=True) Fathers_name = models.CharField(max_length=100,null=True ,blank=True) Contact_number = models.IntegerField(max_length=10,null=True ,blank=True) Alt_Contact_number = models.IntegerField(max_length=10,null=True ,blank=True) # Profile_picture=models.ImageField(upload_to='images/', null=True, verbose_name="") '''Current Addresss''' Pin_code_c = models.IntegerField(max_length=6,null=True ,blank=True) State_c = models.CharField(max_length=50,null=True ,blank=True) District_c = models.CharField(max_length=50,null=True ,blank=True) Taluk_c = models.CharField(max_length=50,null=True ,blank=True) Location_c = models.CharField(max_length=100,null=True ,blank=True) House_no_c = models.IntegerField(max_length=4,null=True ,blank=True) Street_c = models.CharField(max_length=100,null=True ,blank=True) '''Permanent Address''' Pin_code_p = models.IntegerField(max_length=6, null=True,blank=True) State_p = models.CharField(max_length=50, null=True,blank=True) District_p = models.CharField(max_length=50, null=True,blank=True) Taluk_p = models.CharField(max_length=50, null=True,blank=True) Location_p = models.CharField(max_length=100, null=True,blank=True) House_no_p = models.IntegerField(max_length=4, null=True,blank=True) Street_p = models.CharField(max_length=100, null=True,blank=True) '''Reference''' Family_reference_name = models.CharField(max_length=100, null=True,blank=True) Family_reference_conatact_number = models.IntegerField(max_length=10, null=True,blank=True) Neighbour_reference_name = models.CharField(max_length=100, null=True,blank=True) Neighbour_reference_contact = models.IntegerField(max_length=10, null=True,blank=True) '''Document Proof''' ID_Proof_Document_Type=models.CharField(max_length=50, choices=ID_CHOICES, default="Voter", null=True, blank=True) # ID_Proof_Document= models.ImageField(upload_to='images/', null=True, verbose_name="") '''Bank Details''' # … -
Django - redirect function does not execute
i got this model: class Order(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) made = models.BooleanField(default=False) paid = models.BooleanField(default=False) complete = models.BooleanField(default=False) "Account" is custom user model in utils.py i made this function: from .models import Order def HasActiveOrder(user): try: order = Order.objects.get(user=user) except: return False if order: return True and when I'm using it in views like that: if HasActiveOrder(request.user): print("You have at least one unpaid order") return redirect('cart') I can see "You have at least one unpaid order" in console, but I'm not getting redirected, I do not really understand why cuz if print function is getting executed, redirect should work as well. I can't see any error in console. -
Attendance reports using django
I have a Student class and Attendance class where student var in Attendance is ForeignKey of Student class and Student class contains User as ForeignKey. Now when I take attendance using takeattendance function in views.py the attendance is stored properly in the Attendance class, But I have 3 logins hod, staff and student when staff add the attendance I want that the particular student should get the count of there own attendance in percentage. I am unable to get the logic for it. Please Help me with it Models.py class Student(models.Model): id=models.AutoField(primary_key=True) user=models.OneToOneField(User,on_delete=models.CASCADE) branch=models.ForeignKey(Course,on_delete=models.CASCADE,null=True,blank=True) middle_name=models.CharField(max_length=50,null=True) roll_no=models.IntegerField() mobile_no=PhoneNumberField(default='') parents_mobile_no=PhoneNumberField(default='') year= models.ForeignKey(Year,on_delete=models.CASCADE) division=models.ForeignKey(Division,on_delete=models.CASCADE) batch=models.ForeignKey(Batch,on_delete=models.CASCADE) semester=models.ForeignKey(Semester,on_delete=models.CASCADE, null=True,blank=True) class Attendance(models.Model): id = models.AutoField(primary_key=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) student= models.ForeignKey(Student, on_delete=models.CASCADE) status = models.CharField(max_length=15) views.py def takeattendance(request): if request.method == "POST": subject = Subject.objects.get(id=request.POST['subject']) student_ids = request.POST.getlist('student_name') status_list = request.POST.getlist('status') attendance_objs = [] for sid, status in zip(student_ids, status_list): attendance_objs.append( Attendance( subject=subject, student=Student.objects.get(id=sid), status=status ) ) Attendance.objects.bulk_create( attendance_objs ) if request.user.is_authenticated and request.user.user_type == 2: return render(request,'ms/hod/Attendance.html') elif request.user.is_authenticated and request.user.user_type == 3: return render(request,'ms/staff/Attendance.html') else: return HttpResponse("Failed") else: return HttpResponse("Failed") -
Django Admin shows multiple instances for same primary key
I am struggling with a weird issue in Django (4.0.7) where multiple instances for the same primary key are shown in Django Admin, as well as when executing queries. I have displayed the primary keys to make clear that they are identical: The two classes involved are Collection and Card, where every card has a foreign key to a collection. class Collection(models.Model): FREQUENCY_CHOICES = [('never', 'Never'), ('less', 'Less'), ('normal', 'Normal'), ('more', 'More')] title = models.CharField(max_length=200) author = models.CharField(max_length=200, blank=True, null=True) user = models.ForeignKey(User, related_name='collections', on_delete=models.CASCADE) type = models.CharField(max_length=10, choices=(('books', 'Books'), ('tweets', 'Tweets'), ('articles', 'Articles'), ('podcasts', 'Podcasts'))) custom_id = models.CharField(max_length=200, blank=True, null=True) # e.g. raindropref, amazon book id, etc. url = models.URLField(blank=True, null=True) tags = TaggableManager(blank=True) connection = models.ForeignKey(Connection, related_name='collections', null=True, blank=True, on_delete=models.SET_NULL) frequency = models.CharField(max_length=10, choices=FREQUENCY_CHOICES, default='normal') class Card(models.Model): text = models.TextField() collection = models.ForeignKey(Collection, related_name='cards', on_delete=models.CASCADE, blank=True) custom_id = models.CharField(max_length=200, null=True, blank=True) author = models.CharField(max_length=200, null=True, blank=True) url = models.URLField(blank=True, null=True) created_at = models.DateTimeField(default=timezone.now) favorite = models.BooleanField(default=False) tags = TaggableManager(blank=True) notes = models.TextField(blank=True, null=True) location = models.IntegerField(blank=True, null=True) I cannot fathom where the issue might be. I have already set up the databse from scratch, with no success. Here is an example database query: for c in Collection.objects.all(): print(c.pk, … -
I can't make migration back, after i deleted them in Django
I am using Django with VSC. I got some problem with my database, so i did want to delete inside of migrations but by mistake i deleted directly folder of migrations. Anyway then i used the code; python manage.py makemigrations python manage.py migrate --fake Then i got my migrations informations back. But the problem is, this time it didn't detect my own migrations. So when i click something have connection with database. I got a mistake like "No such table: MyMigrationsName" How can i fix it ? -
DRF pagination with filtering
I have a Django Rest Framework project which is serving up (amongst other things) events. In general, as there could be thousands of events, I prefer to keep the API calls paginated in order to stop the front end API calls from taking too long. I can use this paginated route to produce a table on the front end which will reflect each page in the returned response. Up until now, all good. However, I also want to add a dropdown filter above the table where users can select any of the possible venues that the events are at. But to get an exhaustive list of all the possible venues for the dropdown list, I'll need to go and fetch ALL of the events anyway! Is there another way to do this? Or is a non-paginated events route my only choice? -
RelatedObjectDoesNotExist at /auth/profile/ User has no profile. (user is creating but profile is not)
I had created a custom registration form through which I am creating User and I want to create a profile of the user while creating a User. The code is working if I create a profile manually through admin but not creating while creating user. below is my code. please help me out. Models.py from distutils.command.upload import upload from email.policy import default from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import User from PIL import Image # Create your models here. class User(AbstractUser): is_user = models.BooleanField(default=False) is_doctor = models.BooleanField( default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class User_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=100,blank=False) address = models.TextField(max_length=500,blank=False) gender = models.CharField(max_length=7, blank=False) phone = models.CharField(max_length=12,unique=True,blank=False) Username = models.CharField(max_length=100,blank=False,unique=True) Userpassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname class dr_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) image = models.ImageField(upload_to="image") specialisation = models.CharField(max_length=100,blank=False) qualificaton = models.CharField(max_length=100,blank=False) phone = models.CharField(max_length=12,blank=False,unique=True) gender = models.CharField(max_length=7,blank=False) address = models.TextField(max_length=500,blank=False) state = models.CharField(max_length=50,blank=False) city = models.CharField(max_length=50,blank=False) zip = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=50,blank=False) dUsername = models.CharField(max_length=100,blank=False,unique=True) dPassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='#', upload_to='profile_images') bio = models.TextField() def __str__(self): … -
How to display text in html from Django as it is typed in textbox
I want to display the text in HTML from Django in proper format. i.e. Proper space, line break, etc. I used <p>{{blog.main_content}}</p> This is the screenshot of data added The text displaying in webpage Please help me to figure it out. How can I display this text in a proper format? -
Not allowed to load local resource in Django (Images)
I'm trying to load multiple images using Django rest API but getting the error as - Not allowed to load local resource. the setting of app is - STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have checked multiple solution on google but is this due to chrome or Django? Can anyone help here please. NOTE: The call of the API is giving 200 response but only rendering is not happening. Thanks!! -
DRF+Axios: some requests fail with `ERR_NETWORK` or `ERR_BLOCKED_BY_CLIENT`
This is not a question, more like an answer to this common problem. I have a Dashboard built with NextJs and Django+DRF and i am using axios as a HTTP Client. i have noticed that some of my requests go through, and some do not (mainly the requests that fetch for example monthly/yearly payments/expenses of the company). Down below you'll find the solution to this problem. -
Django SetPasswordForm heritage doesn't work
I want to inherit from the built-in Django SetPassWordForm which is class SetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { "password_mismatch": _("The two password fields didn’t match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get("new_password1") password2 = self.cleaned_data.get("new_password2") if password1 and password2: if password1 != password2: raise ValidationError( self.error_messages["password_mismatch"], code="password_mismatch", ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user by providing a custom class to the fields: class CustomSetPasswordForm(SetPasswordForm): def __init__(self, *args, **kwargs): super(CustomSetPasswordForm, self).__init__(*args, **kwargs) new_password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) new_password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) But the template doesnt render it: # user/authentication/password_reset_new.html <div class="password-wrapper field-wrapper mb-4"> <div class="tag pl-1">{{ form.new_password1.label }}*</div> <div class="input text-woys-purple">{{ form.new_password1 }}</div> </div> <div class="password-wrapper field-wrapper mb-4"> <div class="tag pl-1">{{ form.new_password2.label }}*</div> <div class="input text-woys-purple">{{ form.new_password2 }}</div> </div> # urls.py # Set new password path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(template_name='user/authentication/password_reset_new.html', form_class=CustomSetPasswordForm), name='password_reset_done'), -
How to send variables from view.py to a signal in Django
i want django to create a ServerModeratorPermission object just after the user has been set as the moderator of the server views.py: class ModeratorSettingsView(LoginRequiredMixin, View): form_class = AddModeratorForm ... def post(self, request, server_tag): form = self.form_class(request.POST) user = User.objects.get(pk=request.POST.get('user')) server = Server.objects.get(tag=server_tag) moderators = server.moderator_of.exclude(user=server.creator) ServerModerator.objects.get_or_create(user=user) moderator = ServerModerator.objects.get(user=user) moderator.server.add(server) return render(request, 'servers/moderator-settings.html', {'moderators':moderators, 'server':server, 'form':form}) signals.py: @receiver(post_save, sender=ServerModerator) def give_default_permission(instance, *args, **kwargs): # i need server_tag for this query # server = Server.objects.get(tag=server_tag) moderator = ServerModerator.objects.get(pk=instance.id) ServerModeratorPermission.objects.create(moderator=moderator, server=server) is there anyway to send server_tag that being used in the view class to the signal? -
Avoid serializer from returning double titles for relation serializer
I have these serializers serializer 2 has a relational field to serializer 1 serializer 1 class ExerciseSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) subject = serializers.SlugRelatedField(read_only=True, slug_field="title") topic = TopicSerializer() class Meta: model = Exercise fields = ["id", "subject", "topic", "questions"] serializer 2 class ExerciseTokenSerializer(serializers.ModelSerializer): exercise = ExerciseSerializer() class Meta: model = ExerciseToken fields = ["exercise", "completed", "score"] this results in a nested "exercise" were I have to access the data by "exercise.exercise", looking at the results below will better explain the issue: { "etoken": 30, "exercise": { "exercise": { ... "completed": false, "score": 0 } } this is how I want it to output { "etoken": 30, "exercise": { ... "completed": false, "score": 0 } } How is this achievable? I couldn't a solution in the docs or here in stack overflow. Thanks. -
Create an API server using Django/FastAPI/Flask and create the following APIs that return this data as JSON in various different ways
https://docs.google.com/document/u/0/d/1BYRJAEI-5aSsQSlHB4BBmvCnKCORPwCGr0ewLvr1f_o/edit?usp=sharing create an API server using Django/FastAPI/Flask and create the following APIs that return this data as JSON in various different ways. All the details of project are given in link. -
Filter model assigned to user , ManyToManyField - Django
new to django and I am finding it hard to know what to search and what questions to ask sooo....here it goes... I have a model named Obiectiv to which I have assigned users in the admin panel using manytomanyfield. models.py: class Obiectiv(models.Model): numeObiectiv = models.CharField(max_length=250) color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green') user = models.ManyToManyField(User) I want that when the user is logged in, he is able to see only the models that have been assigned to him: views.py @login_required def home(request): obiective = Obiectiv.objects.all() return render(request, 'home.html', context={"obiective":obiective}) With the code in the views.py it display all the Obiectiv models. home.html {% for obiectiv in obiective %} <div class="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="card rounded-0 shadow border-primary text-start summary-card my-3"> <div class="card-body"> <div class="d-flex w-100"> <div class="col-8 pe-2"> <div class="summary-title fs-5 border-bottom">Total Categories</div> <div class="summary-count text-end fw-bolder mt-3 px-4">{{ obiectiv.numeObiectiv|intcomma }}</div> </div> <div class="col-4"> <div class="summary-icon p-3 rounded border text-center bg-gradient bg-light"> <i class="fa fa-list"></i> </div> </div> </div> </div> </div> </div> {% endfor %} thank you in advance. -
IIS django static files not showinvg
i try to deploy my Django app on IIS for work but is not serving my static files. i watched this tutorial: https://www.youtube.com/watch?v=APCQ15YqqQ0. Right now my Django app looks like this, the CSS is not appearing I added a virtual directory as well and have set the physical path to the static file in the project. In my my settings.py i have STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] I have no idea what i am missing. please tell me if you need more information. -
Design DB to calculate prize based on distance of cities
I am working on a side project to calculate the prize of the service based on the city distances. In my prize table I have values like below: CATEGORY DISTANCE VALUE Category A < 100 km 10EUR Category A From 100 km to 300 km 50 EUR Category A > 300 km 100 EUR My idea is to prepare a DB structure like below: CATEGORY DISTANCE_FROM DISTANCE_TO VALUE Category A 0 100 10 Category A 100 300 50 Category A 300 x 100 Is this the right approach? I am also wondering how to later get the correct value if for example distance is 150 km? The project will be build in Django, any help appreciated. -
Django login_required doesn't work with multiple gunicorn workers
So I have a project which contains multiple micro-services, the entry point is the Django micro-service(with user login & authentication). All other Apis are wrapped with the @login_required decorator by Django. I've deployed it using ngnix, gunicorn inside a kubernetes pod. Everything works fine with 1 worker(sync) but I obviously want multiple workers, so when I increase my number of workers and threads(gthread), it doesn't let me login redirects to login/?next=/login/5/. After spending some time, I figured out the following: Since the default value of keepalive of a worker is 2s, the worker closes connection and a new worker is assigned & since they don't share common memory,my session cookie isn't carried forward. I tried increasing the keepalive time to 10s , now it lets me login but if someone tried to login when the worker is about to expire(around 10s), same, doesn't login & redirects to login/?next=/login/5/. Another direction I found was about fixing the secret key as in this post, but I just using the default standard value which I even hardcoded in settings.py, but no luck. I'll attach my gunicorn config/logs below: config: ./gunicorn.conf.py wsgi_app: None bind: ['0.0.0.0:8000'] backlog: 2048 workers: 2 worker_class: sync threads: 4 worker_connections: … -
How to gain specific field value manually in django admin fieldsets
I'm overriding admin/includes/questions/fieldset.html to change the behavior of some fields using the JavaScript. In the orignal fieldset.html by django theres a loop to display the fields, But I want to pick the value of first field for some usecase. How can I do that {% for line in fieldset %} <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} {% for field in line %} <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} {% if field.is_checkbox %} {{ field.field }}{{ field.label_tag }} {% else %} {{ field.label_tag }} {% if field.is_readonly %} <div class="readonly">{{ field.contents }}</div> {% else %} {{ field.field }} {% endif %} {% endif %} {% if field.field.help_text %} <div class="help"{% if field.field.id_for_label %} id="{{ field.field.id_for_label }}_helptext"{% endif %}> {{ field.field.help_text|safe }} </div> {% endif %} </div> … -
The form for UpdateView for editing the user profile is not displayed. Django
I'm trying to make an UpdateView to edit user profile without pk or slug using get_object() with self.request.user. But when I run my settings, the form is not shown. Here is my code: urls.py: urlpatterns = [ path('settings/', UserSettings.as_view(), name='settings'), path('<slug:profile_slug>/', ShowUserProfile.as_view(), name='profile'), ] views.py: class UserSettings(LoginRequiredMixin, DataMixin, UpdateView): template_name = 'users/user_settings.html' form_class = UpdateUserForm def get_object(self, *args, **kwargs): return self.request.user def get_success_url(self): return reverse_lazy('profile', kwargs={'profile_slug': self.request.user.userpofile.slug}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title='Settings') forms.py: class UpdateUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password') widgets = {'username': forms.TextInput(attrs={'class': 'form-control form-input form__input'}), 'password': forms.TextInput(attrs={'class': 'form-control form-input form__input'})} user_settings.html: <form class="form" method="post"> {% csrf_token %} {% for item in form %} <div class="row"> <div class="col-sm-4"> <label class="form__label" for="{{item.id_for_label}}">{{item.label}}: </label> </div> <div class="col-sm-8"> {{item}} </div> </div> <div class="form__errors">{{item.errors}}</div> {% endfor %} <button class="button" type="submit">Set settings</button> </form> It doesn't even throw an error. What I need to do?