Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How show image in django pdfkit pdf file?
I have a issue, I create detail view in html and after i convert it in pdf for all models object. i use pdfkit, however it doesnt shows object's image, then i run code with image it has some errors. def customer_render_pdf_view(request, pk): posts = get_object_or_404(Person, pk=pk) enrolment =get_object_or_404(Enrollment, pk=pk) template = get_template('test.html') html = template.render({'costumer': posts, 'enrolment':enrolment}) options = { 'page-size': 'Letter', 'encoding':' base64.b64encode("utf-8")', } pdf = pdfkit.from_string(html, False, options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="person.pdf"' return response my HTML code : <img src={{costumer.image.url}} height='200px'> -
django retrieve all items filtering by FK
I would like to make an API for retrieve all the dailies of a specific tracker for then retrieve them in react native, could you give me some help about how do it? thanks in advance. I also have User and Habit classes, but in this case i just need this API. class Tracker(models.Model): habit = models.ForeignKey(Habit, on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='trackers', on_delete=models.CASCADE) start_date = models.DateField(blank=False) end_date = models.DateField(blank=False) published = models.BooleanField(blank=False) @property def habit_title(self): return self.habit.title def is_active(self): today = datetime.now().date() return (today >= self.start_date) and (today <= self.end_date) def no_of_days(self): return abs((self.end_date-self.start_date).days) + 1 class Daily(models.Model): STATUS = [('DONE', 'DONE'), ('TODO', 'TODO'), ('NOTDONE', 'NOTDONE'),] date = models.DateField() status = models.CharField(choices=STATUS, max_length=10, default='TODO') tracker = models.ForeignKey(Tracker, on_delete=models.CASCADE) class Meta: unique_together = (('date', 'tracker'),) index_together = (('date', 'tracker'),) serizalizers.py class TrackerSerializer(serializers.ModelSerializer): habit_title = serializers.ReadOnlyField() class Meta: model = Tracker fields = ['id', 'start_date', 'end_date', 'published', 'is_active', 'no_of_days', 'habit', 'habit_title', 'user'] def create(self, validated_data): tracker = Tracker.objects.create(**validated_data) diff = abs((validated_data['start_date'] - validated_data['end_date']).days) for i in range(0, diff + 1): Daily.objects.create(date=(validated_data['start_date'] + timedelta(days=i)), tracker=tracker) return tracker class DailySerializer(serializers.ModelSerializer): class Meta: model = Daily fields = ['id', 'date', 'status', 'tracker'] views.py class TrackerViewSet(viewsets.ModelViewSet): serializer_class = TrackerSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def … -
Running pytest using django manage.py, clear cache option
There are several tests, written with pytest, in my django app I run test using manage.py test with setting TEST_RUNNER = 'PytestTestRunner' PytestTestRunner class class PytestTestRunner: def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs): self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb @classmethod def add_arguments(cls, parser): parser.add_argument( '--keepdb', action='store_true', help='Preserves the test DB between runs.' ) def run_tests(self, test_labels): import pytest argv = [] if self.verbosity == 0: argv.append('--quiet') if self.verbosity == 2: argv.append('--verbose') if self.verbosity == 3: argv.append('-vv') if self.failfast: argv.append('--exitfirst') if self.keepdb: argv.append('--reuse-db') argv.append('--cache-clear') argv.extend(test_labels) return pytest.main(argv) The problem is, that even i have option --cache-clear, the .pytest_cache directory is still created How to prevent this behaviour? -
submit html form django
i have this django app and i'm trying to submit form but study material file field have multiple file select option so what i'm trying to do create keylevel with name description status after that with keylevel id i'm saving files in another table. models.py: class KeyLevel(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(null=True, blank=True) status = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class KeylevelFileUpload(models.Model): key_level_id = models.ForeignKey(KeyLevel, related_name="keylevel", to_field="id", verbose_name=_("Key Level Id"),on_delete=models.CASCADE, null=True, blank=True, db_column="key_level_id") study_material = models.FileField(upload_to='study_material', null=True, blank=True) status = models.SmallIntegerField(verbose_name=_("Status: 1 for Active; 0:Inactive"), default=1) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) html: <form method="post" action="{% url 'keyLevelAdd'%}" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-3"> <div class="formControl static"> <label for="levelName" class="formLabel">{{form.name.label}}</label> <input type="text" name="{{form.name.html_name}}" class="formField" placeholder="Scripture Key Level" id="levelName"> </div> </div> <div class="col-md-4"> <div class="formControl static"> <label for="" class="formLabel">Study Material</label> <div class="upload-input"> <input type="file" name="{{form.study_material.html_name}}" class="formField" placeholder="Scripture Key Level" id="studyMaterial" multiple> </div> <div class="upload-icon"> <div class="browseImg"> <i class="fas fa-upload"></i> {% comment %} <input type="file" class="browseField" name="studyMaterialbrowse" id="studyMaterialb" multiple> {% endcomment %} </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="formControl static textarea"> <label for="" class="formLabel">{{form.description.label}}</label> <!-- <label for="" class="formLabel">About Level Conditions</label> --> <textarea class="formField" placeholder="" rows="5" name="{{form.description.html_name}}">Description</textarea> </div> </div> <div class="col-md-3"> <div … -
For loop not working as expected in Django, HTML
I'm trying to create a search bar where the user can search for a specific user in the database. I've created a for loop in the search_users HTML file but the loop is not iterating through any of my users. Whenever I try to load the page the first line loads ("You searched for ...") but anything in the for loop does not. models.py class User(AbstractUser): """User in a club.""" username = models.EmailField(unique=True, blank=False) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) bio = models.CharField(max_length=520, blank=True) chess_experience = models.IntegerField(blank=False, validators = [MinValueValidator(0)]) personal_statement = models.CharField(max_length=10000, blank=False) created_at = models.DateTimeField(auto_now_add=True) views.py def search_users(request): if request.method == "POST": searched = request.POST.get('searched',False) users = User.objects.filter(first_name__contains=searched) return render(request, 'search_users.html', {'searched': searched, 'users': users}) else: return render(request, 'search_users.html', {}) search_users.html {% if searched %} <h1>You searched for {{ searched }}</h1> {% for user in users %} <a href="{% url 'show_user' user.id %}">{{ user }}</a><br/> {% endfor %} {% else %} <h1>You forgot to search for a member...</h1> {% endif %} -
Angular to Django. File Uploader with a Date Parameter
I have some working code on Django, where i created a simple file uploader with a date picker that is passed through a view and then uploaded onto a database using a standalone python class that utilise sqlalchemy. However, I have been working on migrating the UI aspect onto an Angular Front End, but hit a road block and not sure where I am going wrong. The user needs to be able upload a excel binary file, input a date and hit upload. This should send a request to a view which then handles the request. The view it self works perfectly, when the file and dates are inputted from the Django HTML template. But I can't seem to make it work once the inputs come from Angular. Here is my code views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.FILES['data'], request.POST['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST) file-upload.service.ts DJANGO_SERVER: string = "http://127.0.0.1:8000"; constructor(private http:HttpClient) { } public upload(data: any, selectedDate:any) { return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, data, selectedDate); } upload.component.ts onChange(event: any) { this.filetoUpload = event.target.files[0]; } inputEvent(event:any) { this.monthEndDate = event.value; } … -
Can not raise ValidationError in django update serializer
I'm trying to raise ValidationError in an update serializer, but couldn't. Here is my code: from rest_framework.exceptions import ValidationError class PersonUpdateSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ( "name", "surname", ) def validate(self, attrs): # type: (dict) -> dict errors = {} attrs = super(PersonUpdateSerializer, self).validate( attrs ) if "surname" not in attrs: errors["surname"] = "This field is required." if errors: raise ValidationError(errors) return attrs def update(self, instance, validated_data): for key in validated_data: setattr(instance, key, validated_data.get(key)) instance.clean() instance.save() return instance When I don't send "surname" parameter, it should raise ValidationError, but it doesn't. What am I missing? -
How to get user id from the related field model in django?
views.py @login_required def become_vendor(request): vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendordetailform.is_valid(): vendordetailform.instance.vendoruser = request.user request.user=vendordetailform.save() request.user.is_active=False request.user.save() user_details = CustomUser.objects.filter(id=request.user) vendor_details = user_details[0].vendor_details.all() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: vendordetailform = VendorAdminDetailsForm() return render(request, 'vendor/become_vendor.html', {'vendordetailform':vendordetailform}) I have two models 1. User model, 2. VendorDetails model (vendoruser is connected by foreignkey relationship with vendordetails) Here I save the User extra details (VendorDetailsForm) if the requested user is applying for a vendor. I could be saved the requested user details in VendorDetails Model. But when I am getting the requested user id, I can't . instead I get vendordetails model foreignkey field. Here I want to inactive the requested user who came with this vendor details form. I am getting Field 'id' expected a number but got <VendorDetails: yabeshofz@gmail.com-Customer1>. -
Django ModelForm how to display only a subset of Model
I have a django model for an appointment to the doctor class Appointment(models.Model): patient=models.ForeignKey(Patient,on_delete=models.SET_NULL,null=True) date=models.DateField(default=datetime.date.today) doctor=models.ForeignKey(Profile,on_delete=CASCADE) status=models.CharField(max_length=12,default="open") def __str__(self): return self.name Doctor is one of the roles in the Profile model. My form is defined like so class AppointmentForm(forms.ModelForm): class Meta: model=Appointment exclude = ['id'] def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) self.helper=FormHelper() self.helper.layout=Layout( Row( Column('patient',css_class="form-control, col-md-4 mb-0"), Column('date',css_class="form-group, col-md-4 mb-0"), Column('doctor',css_class="form-group, col-md-4 mb-0"), css_class='row ' ), Submit('btn_save', 'Save',css_class='btn-success') ) When displaying the form using crispy forms, all the users of the Profile models are shown. How do I display only Profiles with role Doctor? -
Bind cache Django class based view response with parameter from request
I want to cache my API response and bind it with parameter that is present in GET request. The request looks like this: GET /products?producent=some_company Here is my simplified class: class ProductsListCreate(generics.ListCreateAPIView): def list(self, request, *args, **kwargs): cached_response = cache.get(f"response-products-{producent}", None) if not cached_products: queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) serializer = self.get_serializer(page) response = self.get_paginated_response(serializer.data) producent = request.query_params.get("producent") cache.set(f"response-products-{producent}", products, timeout=20) return response return cached_response But when I'm trying to cache the response I receive error: django.template.response.ContentNotRenderedError: The response content must be rendered before it can be pickled. Do you have any tips for me? I was searching here https://docs.djangoproject.com/en/3.2/topics/cache/ when I was trying to figure out this. At first I tried the approach with @cache_page but it won't allow me to use the parameter from request, so I guess the way to go is Low level cache API. -
Difference pip/pipenv
I guess it's going to be obvious in a few seconds but I am fairly new to web development. I am learning how to use Django and I encountered an issue with allauth after having installed it through pipenv and tried to migrate. I got a lovely ModuleNotFoundError: No module named 'allauth'. As I said, I installed it through pipenv and I could see allauth in my .venv/Lib/site-packages file. I have my virtual environment set and activated. A quick research and thanks to this answer, I solved my issue by "reinstalling" it with pip install allauth, and my migration is now working fine. What I don't understand is, wasn't it already installed when I did pipenv install allauth, do I need to install everything once with pipenv to get the Pipfile & Pipfile.lock updated and then also install it through pip...? Obviously, I don't fully understand the difference between pipenv & pip, if some charitable soul would be kind enough to explain this to me, I'd greatly appreciate it :) Edit: I saw this thread already but either way I am stupid or whatever but it still doesn't make much sense to me. -
Passing JSON from custom view to template
So I have worked with a Django program that was working before, got some code got lost and I managed to recover the most, but have some issues left. I have a class that's building different dictionaries that are supposed to be passed on to the frontend, where there are some Javascript function that's work with that data. My problem is I can't get the pass the data from the view to the template. I have tried to use HttpResponse, but then it just displays the data on a blank screen. I just want to pass it to the template and let the JavaScript functions there work with it. class ReportDashboardView(AuthMixinLineManager, ReportDashboard, generic.TemplateView): """Team report view, build data required for graphs and tables.""" template_name = 'index.html' http_method_names = ['get'] def get(self, request): data_left, data_joined, data_changed_team = self.init_report() data_left = json.dumps(data_left) return HttpResponse(json.dumps(data_left), content_type="application/json") Looks like this I instead just want to "feed" the data to the already existing HTML-template and use the escapejs to access the data that comes from the view. I know the URL-patterns is correct. And here is a example of how the JavaScript functions looks. So my questions is, does anyone have any suggestion on how … -
How to filter many2many field with another many2many?
I have following model in my Django: class Filter(models.Model): min_price = models.PositiveIntegerField(null=False, blank=False) max_price = models.PositiveIntegerField(null=False, blank=False) trait = models.ManyToManyField(Trait, null=True, blank=True) class Flat(models.Model): living_area = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, db_index=True) trait = models.ManyToManyField(Trait) class Trait(models.Model): name = models.CharField(max_length=255, blank=False, null=False, db_index=True) In my case trait can be for example: elevator. If there is connection between Flat and Trait(name="Elevator") then I can assume that Flat has elevator. What I want to do is to searching flats based on traits - traits from Flat and traits from Filter should be the same. I did somethink like this: filte_obj = Filter.objects.get(pk=pk) flat = Flat.objects.filter(trait__id__in=[x.id for x in filter_obj.trait.all()]) Unfortunately I does not work as I want. I want to see only Flats which Traits QuerySet is the same as Filter's traits QuerySet. How can I do that? -
How can I filter out static logs on Heroku Papertrail for a Django App?
I am trying to filter out logs related to static files on a Heroku/Django App. Based on this answer django - how to filter out GET static and media messages with logging? I added the following code snippet in settings.py def skip_static_requests(record): if record.args[0].startswith('GET /static/'): # filter whatever you want return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { # use Django's built in CallbackFilter to point to your filter 'skip_static_requests': { '()': 'django.utils.log.CallbackFilter', 'callback': skip_static_requests } }, 'formatters': { # django's default formatter 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s', } }, 'handlers': { # django's default handler... 'django.server': { 'level': 'INFO', 'filters': ['skip_static_requests'], # <- ...with one change 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, }, 'loggers': { # django's default logger 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, } } I was able to filter out static logs, but it only works on localhost. How can I get this to work for Heroku Logs and for a logging service like papertrail? -
Django+Twilio: How can I display inside my django app the sms I sent/received using twilio? (Architecture question)
I have a high level architecture question: I built a django app and I integrated with Twilio so that I can send SMS from my django app. Now I am trying to understand if there is a way for me to display the sms I send and receive almost as a chat inside my application. I know this is very high level but I am mostly looking for architecture suggestions, not specific code. Any suggestion? -
How to get field : Django RestFramework
How to get duration field from the table video, In my project there are two tables related to video models.py class Video(BaseModel, Timestamps, SoftDelete): video_name = models.CharField(max_length=254, null=True, blank=True) description = models.TextField(null=True, blank=True) duration = models.DurationField(null=True, blank=True) class VideoDetails(BaseModel, Timestamps, SoftDelete): max_attempt_allowed = models.PositiveSmallIntegerField() amount = models.DecimalField(max_digits=19, decimal_places=2) video = models.OneToOneField(Video, on_delete=models.CASCADE) Here I want to calculate total duration of a course, for that created a function: def get_duration(course_id): print('course', course_id) hour = VideoDetails.objects.filter(video__coursemodulevideos__module_id__coursesectionmodule__section_id__coursesectiondetails__course=course_id).aggregate(Sum('duration')) print('h', hour) "hour = VideoDetails.objects.filter(video__coursemodulevideos__module_id__coursesectionmodule__section_id__coursesectiondetails__course=course_id).aggregate(Sum('duration'))" through the above line how to get duration from video model, give me a solution to fix this situation -
Why is Django giving me a ValueError when I reference a class within the same model?
I'm building a simple recipe app, and so far I have two models: Ingredient and Recipe. Each recipe should have multiple ingredients, so I laid out my model like this: class Ingredient(models.Model): name = models.CharField(max_length=50) class Recipe(models.Model): title = models.CharField(max_length=100) ingredients = models.ForeignKey(Ingredient, on_delete=CASCADE) instructions = JSONField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=SET_DEFAULT, default='Chef Anon') When I makemigrations, I get nothing, but when I migrate, I get this ValueError: ValueError: Cannot alter field cookbook.Recipe.ingredients into cookbook.Recipe.ingredients - they do not properly define db_type (are you using a badly-written custom field?) Following the example here (Django: Add foreign key in same model but different class), I've tried setting ingredients=models.ForeignKey(Ingredient, on_delete=CASCADE) as well as using lazy syntax ingredients=models.ForeignKey("Ingredient", on_delete=CASCADE), but each time, makemigrations shows no changes, and migrate gives me the same ValueError. -
Django Multilanguage - allow users to translate their own input
I'm writing a multilanguage application for renting out property. I've succesfully translated all of the static content inside my application, but the input that the user gives is dynamic and needs to be translated by them. Example: The user needs to create all the different rental types that are available for a client to choose from. However, for each language this type has a different name because it needs to be translated. Ideally, when creating a rental type, the user should see multiple input fields for the name: one for each language. Django should then determine by the client's language which name to show. I've tried using django-modeltranslation and that created some extra columns on my database, but I cannot find a way for a user to edit all of these columns from one view. This is my translation.py # translation.py from modeltranslation.translator import register, TranslationOptions from .models import RentalType, Costs @register(RentalType) class RentalTypeTranslationOptions(TranslationOptions): fields = ('type', 'slug') @register(Costs) class CostTranslationOptions(TranslationOptions): fields = ('name',) Which were succesfully migrated to my database: Migrations for 'main': main\migrations\0014_auto_20211202_1559.py - Add field name_en to costs - Add field name_fr to costs - Add field name_nl to costs - Add field slug_en to rentaltype - … -
How to sort items in template with <select>/<option> tag in Django based app?
Actually, I`m working on E-commerce App using Django Framework. Here I integrated 'blog' app. But I faced an issue with sorting my Posts. #views.py class PostListView(ListView): model = Post template_name = 'article.html' paginate_by = 3 def get_queryset(self): return Post.objects.order_by('-created_at') -
The platform 'undefined' is not currently supported for Docker debugging
I'm following this blog post to debug a containerized Django application with VSCode but it seems I'm getting something wrong. I tried changing some values (ports) but then it says that an error occurred while using the Docker extension. My files looks like this: /docker-compose.yml version: '3.8' services: piola-server: build: context: ./server command: python manage.py runserver 0.0.0.0:8000 volumes: - ./server/:/usr/src/app/ ports: - 8009:8000 - 3002:3002 env_file: - ./server/.env.dev depends_on: - piola-db piola-db: image: postgres:13-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=piola - POSTGRES_PASSWORD=piola - POSTGRES_DB=piola_dev volumes: postgres_data: server/manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings') from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen(("0.0.0.0", 3002)) print('Attached!') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() .VSCode/launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "docker", … -
Admin - do not display "reset" and link to ressource
I created an TabularInline to upload fonts and images I need for a model entry. This comes with django's usual methods: Is there any non-template-hacky way to remove the ressource link (red) and reset (blue) option? -
Django rest framework upload nested form data
I have a front end react.js app that send a form data to a django rest framework end point. Basically, I want to create an order that consists of multiple ads, for now I am testing it using one ad. I am using a function that converts a javascript object to a FormData object from here https://gist.github.com/ghinda/8442a57f22099bdb2e34. As I understood from this function, the FormData object is just a text with a certain syntax, below are some object examples. JavaScript object from browser console {user_id: 'google-oauth2|117955176430010920035', fullname: 'Full Name', email: 'gmail@gmail.com', phone: '', ordertotalprice: 1950, …} ads: Array(1) 0: {display: 1, firstday: '2021-12-2', lastday: '2021-12-15', duration: 13, image: File, …} length: 1 lastIndex: (...) lastItem: (...) [[Prototype]]: Array(0) email: "gmail@gmail.com" fullname: "Full Name" ordertotalprice: 1950 phone: "0000000" user_id: "google-oauth2|11795517643001" [[Prototype]]: Object FormData Object from browser console using the gist.github link from above user_id google-oauth2|117955176430010920035 index.js:25 fullname Full Name index.js:25 email mail@gmail.com index.js:25 phone 00000000 index.js:25 ordertotalprice 1950 index.js:25 ads[0][display] 1 index.js:25 ads[0][firstday] 2021-12-2 index.js:25 ads[0][lastday] 2021-12-15 index.js:25 ads[0][duration] 13 index.js:25 ads[0][image] File {name: 'Picture1.png', lastModified: 1637958641422, lastModifiedDate: Fri Nov 26 2021 22:30:41 GMT+0200 (Eastern European Standard Time), webkitRelativePath: '', size: 1094958, …} index.js:25 ads[0][filetype] image/png index.js:25 ads[0][originalname] Picture1.png index.js:25 ads[0][price] … -
Django (v3.1) PASSWORD RESET LINK: AssertionError at line 260 of django/contrib/auth/views.py assert 'uidb64' in kwargs and 'token' in kwargs
I am having trouble getting past an Assertion error when clicking the password reset link in Django 3.1.2. I have Django running within a Docker container. The emailed link appears to be correct, as it uses the proper domain 'localhost'. However, after clicking the link, the error message replaces the domain 'localhost' with 'Django:8000'. HTML FILES password_reset_email.html {% load i18n %}{% autoescape off %} {% trans "You're receiving this e-mail because you requested a password reset" %} {% blocktrans %}for your user account at {{ site_name }}{% endblocktrans %}. {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb36=uid token=token %} {% endblock %} {% trans "Your username, in case you've forgotten:" %} {{ user.username }} {% trans "Thanks for using our site!" %} {% blocktrans %}The Super Awesome team{% endblocktrans %} {% endautoescape %} password_reset_confirm.html {% extends "admin/base_site.html" %} {% load i18n %} {% block breadcrumbs %}<div class="breadcrumbs"><a href="/">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset confirmation' %}</div>{% endblock %} {% block title %}{% trans 'Password reset' %}{% endblock %} {% block content %} {% if validlink %} <h1>{% trans 'Enter new … -
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.