Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I send React post requet with file data to an API?
Here I want to register user with image so I want to pass both image and name in my formdata. I am able to upload the file using some guideline (I am not good with react) but I am not able to pass the input name with my formdata. which procedure to follow? import React from 'react' import { useState, getState } from "react"; import axios from "axios"; import { useDispatch, useSelector } from 'react-redux' function VendorRegistration() { const [file, setFile] = useState(null); const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/vendor/register/"; const handleSubmit = async e => { e.preventDefault(); //if await is removed, console log will be called before the uploadFile() is executed completely. //since the await is added, this will pause here then console log will be called let res = await uploadFile(file); console.log(res.data); }; const userLogin = useSelector(state => state.userLogin) const { userInfo } = userLogin const uploadFile = async file => { const formData = new FormData(); formData.append("avatar", file); return await axios.post(UPLOAD_ENDPOINT, formData, { headers: { "content-type": "multipart/form-data", "Authorization" : `Bearer ${userInfo.token}`, } }); }; const handleOnChange = e => { console.log(e.target.files[0]); setFile(e.target.files[0]); }; return ( <form onSubmit={handleSubmit}> <h1>React File Upload</h1> <input type="file" onChange={handleOnChange} /> <input type="name" /> <button type="submit">Upload File</button> … -
How to have different login pages for same authentication model in Django?
I have one Django user model (with a custom user manager) but two different user types, namely Store and Customer, to handle authentication: authentication/models.py class User(AbstractBaseUser, PermissionsMixin): ... # checks if user is associated with a store object def is_store(self): return hasattr(self, 'store') # checks if user is associated with a customer object def is_customer(self): return hasattr(self, 'customer') stores/models.py class Store(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.RESTRICT, primary_key=True) ... def clean(self): # validates that the selected user doesn't belong to a customer object if self.user.is_customer(): raise ValidationError({'user': _('This user is already associated with a customer.')}) customers/models.py class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE, primary_key=True) ... def clean(self): # validates that the selected user doesn't belong to a store object if self.user.is_store(): raise ValidationError({'user': _('This user is already associated with a store.')}) Now, the stores and customers should use two different websites to login in i.e. stores will use admin.domain.com while customers will simply use domain.com. If a store is logged into admin.domain.com, will it also show that he is logged in when he visits domain.com? If so, how can I prevent this and isolate these two models to specific sites, while using the same authentication model and methods? -
Can someone help me optimize my Django queries/project structure?
I have created a new Django project and it works fine, but I'm sure there is a better way to do the following and thought of asking. So my main issue is on the template where I have to call the same for loop twice. The one time to include a clinic of the url as you can see on the urls.py, and the other time to show the rest of clinics that are available in the same day. urls.py path('onhold-hospitals/<slug:region_slug>/<slug:clinic_slug>/results/<yyyy:date>/', views.onhold_hospital_results, name='date-clinics-view-results') I'm using this statement in the template: {% for hospital in available_hospitals %} {% if hospital.onhold_date|date == default_date|date and hospital.clinic == clinic%} <h5>Name: {{ hospital.hospital}} - Name: {{ hospital.onhold_date}} - Clinic: {{ hospital.clinic}}</h5> {% endif %} {% if hospital.onhold_date|date == default_date|date and hospital.clinic != clinic%} <p>Other clinics available on the same day: {% for hospital in available_hospitals %} {{hospital.clinic}} {% endfor %} {% endif %} {% endfor %} And here are my core model: class Schedule(models.Model): onhold_hour = models.CharField(max_length=50, blank=True, null=True) onhold_date = models.DateField(default=date.today) region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, related_name="area") hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE, null=True, related_name="available_hospital") clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE, null=True, related_name="clinic_type") all these are being returned from the following views.py: def onhold_hospital_results(request, region_slug, clinic_slug, **date_filters): clinic … -
How to make Custom Registration Form in HTML integration with Django without using Django forms
I want to take specific inputs from user during registration and map with authentication mechanism of Django.This page will be displayed to super users only after login and will be available as a menu as register user.I don't want to customize admin page and use inbuilt form functionality of Django. Please guide. registration <body bgcolor="Lightskyblue"> <br> <br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label> Party name </label> <input type="text" name="partyname" size="100"/> <br> <br> <label> Party Employee Number: </label> <input type="text" name="partyno" size="100"/> <br> <br> <label> Party category: </label> <input type="text" name="partycategory" size="100"/> <br> <br> <label> Party type: </label> <input type="text" name="partytype" size="100"/> <br> <br> <label> Party subtype: </label> <input type="text" name="partysubtype" size="100"/> <br> <br> <label> Party spoc: </label> <input type="text" name="spoc" size="100"/> <br> <br> <label> Party email: </label> <input type="text" name="partyemail" size="100"/> <br> <br> <label> Party Mobile: </label> <input type="text" name="partymob" size="100"/> <br> <br> <label> Party address: </label> <input type="text" name="partyadd" size="100"/> <br> <br> <label> Party level: </label> <input type="text" name="partylevel" size="100"/> <br> <br> <label> Party State: </label> <input type="text" name="partystate" size="100"/> <br> <br> <input name='uploaddoc' type="submit" value="Uploaddoc" > </form> </body> models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) party_emp_number=models.CharField(max_length=100, blank=True, null=True) party_category=models.CharField(max_length=100, blank=True, null=True) party_type=models.CharField(max_length=100, blank=True, null=True) party_subtype=models.CharField(max_length=100, blank=True, null=True) … -
search_phase_execution_exception, failed to create query
I am using elasticsearch-dsl in my django project. Elasticsearch is totally new for me and at some point i got this error: error So i started debugging and removing some part of my code. But here i am my code has become extremely simple but i still don't know why i get this error. The code: import re from django.conf import settings from elasticsearch_dsl.query import Bool, Match, MatchPhrase, Nested from .documents import RubricPageDocument def _build_match_query(query, field): if len(query) <= 4: return Match(**{field: {'query': query}}) if re.match('^".*"$', query): return MatchPhrase(**{field: {'query': query}}) return Match(**{field: {'query': query, 'fuzziness': 'AUTO'}}) def search_query_in_rubric_pages(query): q_title = _build_match_query(query, 'title') q = q_title s = RubricPageDocument.search().query(q) response = s.execute() # error raise on this line return [_format_hit(hit, 'rubric') for hit in response] def search_query(query): """ search in elastic search index for rubric pages * query (str): the query """ page_hits = search_query_in_rubric_pages(query) return { 'hits': page_hits, } Please help me -
Django : Re-login problems with msal when we are already authenticated
I am a newbee in Django. I am trying to do my first Dashboard. For the authentication, I am using msal and the graph tutorial from Microsofs : https://docs.microsoft.com/en-us/graph/tutorials/python I did a different template for my app but used the function from the tutorial to login. Then I tried to do my first application that is to upload a file. When I click on the link to go the app, I restart the process of login and after it redirect me to the home page. I do not get why it redirects me because I should be authenticated. Below is my html code/template that splits the login page and the dashboard when we are authenticated. Home.html <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- Boxicons CSS --> <link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'> </head> <body> {% if user.is_authenticated %} <link rel="stylesheet" href="{% static 'style.css' %}"> <div class="sidebar close"> <div class="logo-details"> <a href="{% url 'home' %}"> <img src="{% static 'image/logo.svg' %}" alt="" > </a> <!-- <span class="logo_name">CodingLab</span> --> </div> <ul class="nav-links"> <li> <a href="#"> <i class='bx bx-grid-alt' ></i> <span class="link_name">Dashboard</span> </a> </li> <li> <div class="iocn-link"> <a href="#"> <i class='bx bx-buildings'></i> <span class="link_name">Organisation</span> … -
can I generate ERD using .sql file in python?
ERD generator using python scripts in python -
How to create pivot tables with model_bakery
I want to create a baker recipe who create one object, objects from a pivot table and links everything well. An incident is created when cells of a technology (2g, 3g, 4g, 5g) are down, but not all technologies are impacted. So we have a pivot table to manage this. My goal is to avoid writing code duplicates and manage this with a simple baker.make_recipe("incidents.tests.incident_with_multiple_impacts") to create an incident and 4 different impacts (technologies are created in fixtures) # incident/models/incident.py class Incident(models.Model): impacted_technologies = models.ManyToManyField( Technology, through="IncidentIncidentImpactedTechnologies" ) # network/models/technology.py class Technology(models.Model): alias = models.CharField(max_length=2, unique=True, blank=False) # ie: "2G", "3G"... name = models.CharField(max_length=4, unique=True, blank=False) # incident/models/incident_technologies.py class IncidentIncidentImpactedTechnologies(models.Model): incident = models.ForeignKey( to="incident.Incident", on_delete=models.CASCADE, related_name="technology_impacts", ) technology = models.ForeignKey( to="network.Technology", on_delete=models.CASCADE, related_name="impacting_incidents", ) During my researches, I writed code above (I want to keep first recipes to reuse them later): def get_technology(key=None): if key: return Technology.objects.get_by_alias(key) # to get it with "2G" return random.choice(Technology.objects.all()) incident_assignation = Recipe( Incident, # few other fields ) impacted_techno = Recipe( IncidentIncidentImpactedTechnologies, incident=foreign_key(incident_assignation), technology=get_technology, # Default, take random technology # Fields describing a NO_IMPACT on this techno ) impacted_techno_cell_down = impacted_techno.extend( # Fields describing a CELL_DOWN impact on this techno ) impacted_techno_degraded = impacted_techno.extend( … -
user login either email or username in Django rest framework with simplejwt authentication
I'm using: Django==3.2.9 djangorestframework==3.12.4 djangorestframework-simplejwt==5.0.0 I want to make a login system that takes either username or email and password as a parameter from a user. After that authenticate a user with those credentials and provide access & refresh token as a response. And I want to use access and refresh tokens use the JWT token system of djangorestframework-simplejwt. -
Looping problem with defauldict in Django templates
On my Django , i used defauldict on my views, and to give a structure I put this code in my template , but it s not working nothing happen in my output What i need to change please ? I want to see in my web page something like this : .List in the file : value value1 value3 ... .List not in the file : value value value... .html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> Dashboard Result</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $("#btnPrint").live("click", function () { var divContents = $("#dvContainer").html(); var printWindow = window.open('', '', 'height=400,width=800'); printWindow.document.write('<html><head><title> ListingCheckPDF</title>'); printWindow.document.write('</head><body >'); printWindow.document.write(divContents); printWindow.document.write('</body></html>'); printWindow.document.close(); printWindow.print(); }); </script> </head> <body style="margin-top: 30px; padding: 100px"> <h1> List </h1> <form id="form1"> <div id="dvContainer"> </div> <input type="button" value="Print Div Contents" id="btnPrint" /> </form> {% for key, value in results.items %} {{ item.key }} {{ item.value}} {% endfor %} {% autoescape off %}{{ output_df }}{% endautoescape %} </body> </html> views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict def home(request): if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = … -
Why is my my related field not working properly? [Django]
I want to acheive: I have 2 Models Tag and Startup. my models.py file - from django.db import models from django_extensions.db.fields import AutoSlugField from django.db.models import CharField, TextField, DateField, EmailField, ManyToManyField class Tag(models.Model): name = CharField(max_length=31, unique=True, default="tag-django") slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"]) def __str__(self): return self.name class Startup(models.Model): name = CharField(max_length=31, db_index=True) slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"]) description = TextField() date_founded = DateField(auto_now_add=True) contact = EmailField() tags = ManyToManyField(Tag, related_name="tags") class Meta: get_latest_by = ["date_founded"] def __str__(self): return self.name When creating a startup, I have a dropdown list of created Tags which I want to relate to my Startup that I am creating. When I am posting the data - { "name": "Startup4", "description": "TestStartup", "contact": "startuptest@gmail.com", "tags": [ { "url": "http://127.0.0.1:8000/api/v1/tag/first-tag/", "name": "First Tag", "slug": "first-tag" }, { "url": "http://127.0.0.1:8000/api/v1/tag/second-tag/", "name": "Second Tag", "slug": "second-tag" }, { "url": "http://127.0.0.1:8000/api/v1/tag/third-tag/", "name": "Third Tag", "slug": "third-tag" } ] } A startup is created but the tags field remains empty. No Tags are related. My serializers.py file - from rest_framework.serializers import HyperlinkedModelSerializer, PrimaryKeyRelatedField, ModelSerializer from .models import Startup, Tag class TagSerializer(HyperlinkedModelSerializer): class Meta: model = Tag fields = "__all__" extra_kwargs = { "url": { "lookup_field": "slug", "view_name": "tag-api-detail" } } class … -
using inline javascript inside a python loop
I have a list of entries. Insider the list of entries I have a link to individual entries. I have an update form that updates one field. I want to open the update form inside a new window. The user then submits the form is directed to a success page which currently has a timed close. The issue I am encountering is with the inline javascript which opens the form in a new window. When I attempt to assign the kwarg on the url it the javascript does not change with each entry in the list. I have limited javascript, and jquery knowledge. I just want the javascript to open a new window for each update form. I have included the template below. <thead> <tr> <th>Script No.</th> <th>Entered on</th> <th>Patient</th> <th>Email</th> <th>Product</th> <th>Form</th> <th>Units</th> <th>Dispensing Price</th> <th>Status</th> <th>Dispatch Date</th> <th>Entered by</th> <th></th> </tr> </thead> <tbody> {% for script in scripts %} <tr> <td>{{script.pk}}</td> <td>{{script.entered_on}}</td> <td>{{script.patient}}</td> <td>{{script.patient.email}}</td> <td>{{script.product}}</td> <td>{{script.product.form.description}}</td> <td>{{script.quantity}}</td> <td>$&nbsp;{{ script.dispensing_price }}</td> {% if script.dispatch_date is not none %} <td>{{script.get_script_status_display}}</td> {% else %} <td><a href = "{% url "script:script_update_status" script.pk %}">{{script.get_script_status_display}}</a></td> {% endif %} <td><a href ="#" onclick="updateStatus()" style="float:right;"> <script>var url = "{% url "script:script_update_status" script.pk %}"; function updateStatus() {var … -
To pass the Response from the nested function `Django REST framework`
I am using python django with Django REST framework It can return the Reponse to the browser like this, in the views.py from rest_framework.response import Response @api_view(['GET']) def get_by(request): res = {"test":"answer"} return Response(res) I want to pass the Response to the browser where nested function from rest_framework.response import Response @api_view(['GET']) def get_by(request): x(t) def x(): #error happens here!! res = {"error":"error happens!!"} return Response(res) in this case, it is simple, I can return the error to the first function and first function can return the error Response. but when you have three four,five nested function? What is the best practice? -
Setting up a good python development environment/editor
I've been developing a project web application in VSCode, using eslint and prettier. It's great and saves me a lot of time. I'm trying to setup a similar environment for a django project, but I'm either lacking a lot of features (no automatic linting, no intellisense) or Pylance is throwing errors like Expected class type but received "LazySettings" Cannot access member "XX" for type "YY" I've tried using the template (https://github.com/wemake-services/wemake-django-template) to combat some of these issues, but I end up in the same place. It feels like I'm lacking some fundamental knowledge. I am able to run the server without issues. Using python 3.9.10. Any suggestions (new editor, vscode settings, stubs) would be very appreciated. -
Автозаполнение поля формы получая id вопроса django
Создаю свой форум. Пытаюсь сделать ответы на вопросы я сделал автозаполнение поле User_id в таблице Quetions и а таблице Answer user_id : models.py class Quetions(models.Model): User_id = models.ForeignKey (User,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Пользователь',blank=True) category_id = models.ForeignKey (Category,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Предмет') schoolclass = models.ForeignKey (SchoolClass,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Класс') subject = models.CharField(max_length=255,verbose_name='Тема вопроса') text = models.TextField(verbose_name='Вопрос') img = models.ImageField(blank=True) date_published = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Тема {self.subject}' class Meta: verbose_name_plural = 'Вопрос' class Answer(models.Model): id_questions = models.ForeignKey(Quetions,to_field='id',on_delete=models.DO_NOTHING,verbose_name='К какому вопросу',blank=True) user_id = models.ForeignKey. (User,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Пользователь', blank=True) Text = models.TextField(verbose_name='Вопрос') date_published = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Тема {self.id_questions}' class Meta: verbose_name_plural = 'Ответ' Автозаполнение в двух таблицах я сделал так: views.py def Questions(request): if request.method == 'POST': user = request.user form = QuestionsForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.User_id = user form.save() return redirect('/') else: return redirect('/') else: form = QuestionsForm() model = Quetions.objects.all() return render(request, 'Questions.html', {'form': form,'model':model}) Не понимаю как сделать автозаполнение поле id_questions в таблице Answer? Заранее СПАСИБО -
Django Rest Swagger Not showing up all the APIs
I am working with Django Rest swagger. But it's not showing up all the APIs. The url paths for /tickets are missing: Even path to /dj-rest-auth/user/ is missing as well: Backend/urls.py from django.contrib import admin from django.urls import path, include from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='API') urlpatterns = [ path('admin/', admin.site.urls), #path('api/v1/', include(api_urlpatterns)), #path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('api/', include('ticket.urls')), path('swagger/', schema_view) ] Tickets/urls.py from django.urls import path from ticket import views urlpatterns = [ path('tickets/', views.ticket_list), path('tickets/<int:pk>/', views.ticket_detail), ] My directory structure: -
Override dispatch() method in PasswordResetConfirmView
I have written a class that inherits from PasswordResetConfirmView PasswordResetConfirmView can be found here: https://github.com/django/django/blob/7f4fc5cbd4c26e137a1abdd9bd603804ddc0e769/django/contrib/auth/views.py#L260 For what it's worth here is the part of the class that I have written (nothing ground breaking I know!): class PwdResetConfirm(PasswordResetConfirmView): template_name = 'account/password_reset_confirm.html' success_url = reverse_lazy('two_factor:login') form_class = PwdChangeForm What I want to do is change the behaviour of PasswordResetConfirmView dispatch() method so that a message is created if a password reset is unsuccessful, so the lines in PasswordResetConfirmView: # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) would effectively become: messages.success(self.request, _(mark_safe( 'Your password change link appears to be invalid.'))) # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) I am new to overriding classes and as such,I am not even sure where to start. In summary, my question is: How can I add the message to PasswordResetConfirmView class's dispatch() method without overriding the entire method? -
django-activity-stream and django-comments-xtd
On a django project i'm using both django-activity-stream and django-comments-xtd, Is there a way to build a stream of the comments posted via the django-comments-xtd package ?? because obviously I will not modifiy the code of the comment package... to add action in it (see action help in the help) How am I supposed to do so ?? Thanks for your help -
how to join in queryset
I have some problems with QuerySet in Django python. I have 2 tables/models. class PP(models.Model): imei = models.BigIntegerField(primary_key=True) name = models.CharField(max_length = 50) val2 = models.IntegerField(default = 0) def __str__(self): return self.name class Mea(models.Model): imei = models.ForeignKey(PP, on_delete=models.CASCADE) v1 = models.IntegerField(default = 0) v2 = models.IntegerField(default = 0) v3 = models.IntegerField(default = 0) dates = models.DateField(default=datetime.date.today) def __str__(self): return self.imei PP +----+--------+------+ |imei| name | val2 | +----+--------+------+ | 1 | john | 12 | | 2 | adam | 5 | | 3 | alfred | 3 | +----+--------+------+ Mea +----+----+----+-----+---------------------+ |imei| v1 | v2 | v3 | date | +----+----+----+-----+---------------------+ | 1 | 4 | 15 | 18 | 2020-10-16 11:15:53 | | 1 | 2 | 12 | 17 | 2020-10-16 11:22:53 | | 1 | 3 | 13 | 16 | 2020-10-16 11:32:53 | | 2 | 1 | 16 | 15 | 2020-10-16 13:22:53 | | 2 | 3 | 13 | 25 | 2020-10-16 13:42:53 | | 2 | 4 | 12 | 35 | 2020-10-16 14:12:53 | | 3 | 1 | 21 | 12 | 2020-10-16 14:12:53 | | 3 | 2 | 28 | 42 | 2020-10-16 15:12:53 | | 3 … -
Calling value from ajax to Django views
Im confused why it returns None when I print the value that comes from ajax, I used request.POST.get("ajaxvalue") to get the value from ajax requests but it didn't work, can anyone know what's the problem I encountered? it's very helpful for me. views.py @csrf_exempt def updateStatus(request): if request.method=="POST": taskId = request.POST.get('id') source = request.POST.get("sources") target = request.POST.get('targets') print(taskId); print(source); print(target); return JsonResponse({'datas': 'test'}) html ajax $.ajax({ data: { id, 'sources':0, 'targets':1 }, url: "{% url 'updateStatus' %}", type: 'POST', cache: false, contentType: false, processData: false }) .done(function(data){ console.log("success"); }); urls.py urlpatterns = [ path('updateStatus/',views.updateStatus, name='updateStatus'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Using geograpy4 on server
URGENT!!!!!!!!!! NEED HELP!!!!!! ----- i've install geograpy4 on my centos7 server because i wrote a function that could detect a citiy's name on an extracted text. it walked fine when working in local but when i try it on server an error was throwed as shown in the first picture. the 3rd picture is the code portion where i use geograpy4. i want to precise that before geograpy4 i was using locationtagger and it gave me the same error so i'm thinking that it's nltk the problem but i'm not sur... -
Getting the origin (absolute path) of a uploaded file in Django
In my django app I ask for files. The user can select multiple audio files via: django.forms.ClearableFileInput(attrs={'multiple': True}) However, for my use case the absolute file paths were the selected files originated from is important. When I access the files with request.FILES.getlist(), I can only see the name of the selected file, but not the full path. How do I get the absolute paths? -
Django-Models extend Data
Is there any way to extend the Information created in one Model Class to another? I want to have all Informations that someone created in Admin for "Form" in class "Test" aswell for further evaluation. from django.db import models import requests as rq class Form(models.Model): ipName = models.CharField(max_length=100) ipAddress = models.CharField(max_length=100) ipKey = models.CharField(max_length=100) ipSecret = models.CharField(max_length=100) ipMask = models.CharField(max_length=100) ipWahrheit = models.BooleanField(default=True) def __str__(self): URL = "https://" + self.ipAddress Key = self.ipKey Secret = self.ipSecret r = rq.get(f'{URL}/api/routes/gateway/status', auth=(Key, Secret), verify=False) return self.ipName + str(r) + "Test" class Test (Form): pass -
Forms dont populate with data on edit with Django 4
I have make an override on my User class, i have add fields. I have make a template for update the fields of the User class. But the problem is i have only some fields having a data. "Firstname, Lastname" This is my views for editing an user: # Vue de la page User (édition) @staff_member_required(login_url='user_login') def admin_users_edit(request, pk): if request.method == "POST": user = User.objects.get(id=pk) form = UserEditForm(instance=user, data=request.POST) if form.is_valid(): user.save() messages.add_message(request, messages.SUCCESS, "L'utilisateur à bien été modifié") return redirect('admin_users_index') else: print(form) print("Invalid Form") print(form.errors) return redirect('admin_departements_index') else: user = User.objects.get(id=pk) form = UserEditForm(instance=user) return render(request, 'back/users/edit.html', {"user":user,"form":form}) And this is my forms, i have try to render the checkox with different solutions, but the radio or checkbox dont populate with the data, they are empty on the form... # Formulaire de l'édition d'un utilisateur YES_OR_NO = ( (True, 'Oui'), (False, 'Non') ) class UserEditForm(forms.ModelForm): username = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Pseudo','autocomplete':'off'})) first_name = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Prénom','autocomplete':'off'})) last_name = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Nom','autocomplete':'off'})) email = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Pseudo','autocomplete':'off'})) password = forms.CharField(label="", help_text="", widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'Mot de passe','autocomplete':'off','required':'false'})) phone = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Téléphone fixe','autocomplete':'off'})) mobile = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Portable','autocomplete':'off'})) is_staff … -
How to get a CharField's value as a string inside the model class?
class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='commenter', null=True) txt = models.CharField(max_length=1000, null=True) summary = str(txt)[:30] + '...' how can I get txt's value as a string and save it in summary? The code above returns somthing like this as string: <django.db.models.fields.CharF...