Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SessionAuthentication vs. BasicAuthentication vs. TokenAuthentication django rest_framework
I'm little bit confused which should I use between the three. I read the docs regarding this, and learned that BasicAuthentication is not suitable for production, I understand nothing more. I'm having a hard time understandings docs regarding these 3. How do they work? What's the difference? I just know that in order to restrict my api pages I need to implement one of these authentications and permission_classes in my generic APIView. So what I am doing is, a web app, for a school and I don't think I will be making an ios app or android app for this web app. Which should I use? -
Django DRF RawSQL with MariaDB Versioning tables
I'm having a weird issue with Django rest framework and MariaDB versioning tables: In my DB I have a table called foods_food which is a MariaDB versioning table. I want to get a list of all the data in the table as of a specific point in time: foods = Food.objects.raw( '''SELECT * FROM foods_food for SYSTEM_TIME as of '2021-04-01 09:46:41.911590+00:00') If I print the rawSQL query I get: print(foods) # OUTPUT: <RawQuerySet: SELECT * FROM foods_food for SYSTEM_TIME as of '2021-04-01 09:46:41.911590+00:00'> I've copy pasted the SQL query into my DBMS and I can confirm that it is working as expected. Now, to return the actual data to my API endpoint I have to convert the rawQuerySet to a query set in my views.py: queryset = Food.objects.filter(pk__in=[i.pk for i in raw_queryset]) However when I return the queryset data, the versioning is completely ignored and I'm returned with the data as of the "latest version". What am I missing? -
Django or Flask for a Application that will only manipulate Excel file
I know perhaps this question is agonizing for a Senior Python Developer, but God knows I'm flummoxed about which framework I ought to use for my application. My application will take an Excel File from the front-end, and it is going to manipulate the Excel File, create a new Excel file from the input file, and return the new Excel to the front-end. For this, which Python Web framework ought I use? Ought I use Flask or Django, please help me? Moreover, which Python Library I use for Excel Data manipulation Pandas or OpenPyXL -
Custom SQL Parameters with Django's 'get_or_create()' Method
So I have a DB with 14 columns. It is essentially storing coordinates for potential Wildfire Events across the globe. The data is being sourced from NASA. To avoid importing locally, a lot of data which could be the same event (with slightly different coordinates) I created a simple function which defines a threshold dependent on the latitude of the event (longitude distance per degree varies significantly as the latitude changes). As per the Django documentation on get_or_create(), any keyword passed with the exception of those listed in 'defaults' will be used in a get call before returning a tuple of found object with False. My query is, is it possible to use custom SQL with cursor.execute() to introduce a threshold range which can be used to manage inserts to the DB. I'm aware I could use .filter() method to do this but for purposes of modularity, I would like to do the SQL manually in a separate function housed in data_funcs.py (below). The data is first loaded in via Python Requests and stored locally as a text file then converted to a CSV. As per load.py below, I then use a csv.reader() to read in each line for 'pre … -
Django how to identify that the connection was closed from the client
Simple as is, consider that I have this view in Django rest framework: @api_view(['GET']) def test(request): time.sleep(20) try: return Response({"a": "b"}) except Exception: print("do something") Now say that I was in the browser, navigating to the URL of this view to reach it, and then after 5 seconds only (not 20) closed my browser, then, after 15 seconds, for sure I will end up by ConnectionAbortedError. My question is, how can I catch up on those unexpected Connection closed errors by the client, and do some additional actions in my catch block? -
Export csv with UTF8
I'm trying to export a csv file with utf-8 but csv.writer doesn't seems to have an encoding parameter .... any idea ? import csv response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=data.csv' writer = csv.writer(response, delimiter=';') for book in books: writer.writerow([book.author, book.title]) The string journée appears as journ@~e -
Django Object of type set is not JSON serializable
I have run it with old server is working but when i moved to new server it is not working why ? please advise. <class 'TypeError'> Internal Server Error: /lastestnews/ Traceback (most recent call last): File "/var/www/api-uat/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/var/www/api-uat/tigergourd/tigergourd/views.py", line 211, in lastestnews return JsonResponse(json_data, safe=False) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/http/response.py", line 558, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps return cls( File "/usr/lib/python3.8/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/var/www/api-uat/env/lib/python3.8/site-packages/django/core/serializers/json.py", line 104, in default return super().default(o) File "/usr/lib/python3.8/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type set is not JSON serializable -
Is there any way to get some specific fields from a serializer to another serializer?
I want all data from EmployeeLiteSerializer except designation data to BankInfoSerializer without detete get_designation_data method class EmployeeLiteSerializer(serializers.ModelSerializer): designation_data = serializers.SerializerMethodField(read_only=True) class Meta: model = Employee fields = ('first_name', 'last_name', 'code', 'designation_data') def get_designation_data(self, obj: Employee) -> Dict: try: return DesignationLiteSerializer(obj.designation).data except Designation.DoesNotExist: return {'message': 'No designation'} class BankInfoSerializer(serializers.ModelSerializer): employee = serializers.SerializerMethodField(read_only=True) class Meta: model = BankInfo fields = '__all__' def get_employee(self, obj: Employee) -> Dict: return EmployeeLiteSerializer(obj.employee).data -
apache cannot find the django.core.wsgi module
I have an apache server with mod_wsgi running a django site. When I connect to the page from the browser I get an apache 500 Internal Server Error. This morning I re-installed python and django in the virtual environment, probably I messed up or broke something. The apache logs say: caught SIGTERM, shutting down Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/2.7 configured -- resuming normal operations Command line: '/usr/sbin/apache2' Failed to exec Python script file '/var/www/framework_mc/framework_mc/wsgi.py'., referer: https://mysite/accounts/otp/ Exception occurred processing WSGI script '/var/www/framework_mc/framework_mc/wsgi.py'., referer: https://mysite/accounts/otp/ Traceback (most recent call last):, referer: https://mysite/accounts/otp/ File "/var/www/framework_mc/framework_mc/wsgi.py", line 17, in <module>, referer: https://mysite/accounts/otp/ from django.core.wsgi import get_wsgi_application, referer: https://mysite/accounts/otp/ ImportError: No module named django.core.wsgi, referer: https://mysite/accounts/otp/ Failed to exec Python script file '/var/www/framework_mc/framework_mc/wsgi.py'., referer: https://mysite/accounts/otp/ mod_wsgi (pid=118226): Exception occurred processing WSGI script '/var/www/framework_mc/framework_mc/wsgi.py'., referer: https://mysite/accounts/otp/ Traceback (most recent call last):, referer: https://mysite/accounts/otp/ File "/var/www/framework_mc/framework_mc/wsgi.py", line 17, in <module>, referer: https://mysite/accounts/otp/ from django.core.wsgi import get_wsgi_application, referer: https://mysite/accounts/otp/ ImportError: No module named django.core.wsgi, referer: https://mysite/accounts/otp/ mod_wsgi (pid=118226): Failed to exec Python script file '/var/www/framework_mc/framework_mc/wsgi.py'. mod_wsgi (pid=118226): Exception occurred processing WSGI script '/var/www/framework_mc/framework_mc/wsgi.py'. Traceback (most recent call last): File "/var/www/framework_mc/framework_mc/wsgi.py", line 17, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi mod_wsgi (pid=118226): Failed to exec … -
Get current user info inside model form in django admin
I have the below code structure. I want to get the request.user information inside StaffForm. How do I pass the user info to that class class UserProfileAdmin(admin.ModelAdmin): class UserProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): pass class StaffForm(UserProfileForm): def __init__(self, *args, **kwargs): pass class Meta: model = models.UserProfile fields = () class SuperUserForm(UserProfileForm): def __init__(self, *args, **kwargs): pass class Meta: model = models.UserProfile fields = () search_fields = [ 'email', 'name' ] def get_form(self, request, obj=None, **kwargs): if request.user.is_superuser: return self.SuperUserForm else request.user.is_staff: return self.StaffForm -
how to limit foreign key choices in the form page?
below are my models, I want to display only those groups in post form in which the user is joined in. Example: if I joined in "mcu" group then only that group should be displayed, how should I do that?? GROUP MODEL class Group(models.Model): name = models.CharField(max_length=200, unique=True) description = models.TextField(blank=True, default='') members = models.ManyToManyField(User, through='GroupMember') class GroupMember(models.Model): group = models.ForeignKey(Group, related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE) class Meta: unique_together = ('group', 'user') POST MODEL User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=250,default='') message = RichTextField() group = models.ForeignKey(Group, related_name='posts', null=True, blank=True,on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message'] -
i can't connect between app URLs in Django
I have a small problem with URLs file in Django, I'm trying to connect between app URLs, review, and the main urls I have python 3.9.1 Django 3.2.0 I have been searching and try many things on StackOverflow but still, I don't find why the server doesn't work just when I put this line with a red arrow on the comment, please help!! -
How to make a python date time object based on model object values?
Here I have a Task model. Which has start and end datetime fields. User will have a option to set the notification setting while creating Task. (e.g. send notification before 30 minutes/1 hour). TaskNotification model has OneToOne relation with the Task model.Which is responsible for creating notification. The notification created at the time of task model creation. Now problem is while sending notification. I got stuck while sending notification to the users at the right time . I tried to run the task_notification function in background but stucked while getting the right time. Is it a good approach for my use case or is there any better approcah ? class Task(): title = models.CharField(max_length=255) desc = models.TextField(blank=True, null=True) users = models.ManyToManyField(User, blank=True) start_datetime = models.DateTimeField(default=timezone.now) end_datetime = models.DateTimeField(default=timezone.now() + timezone.timedelta(minutes=30)) class TaskNotification(): notification_options = [ ('minute', 'minute'), ('hour', 'hour'), ('day', 'day'), ] task = models.OneToOneField(Task, on_delete=models.CASCADE=) send_before = models.PositiveIntegerField(default=10) notification_option = models.CharField(max_length=10, default='minutes', choices=notification_options) is_viewable = models.BooleanField(default=False) function def task_notification(): tasks = Tasks.objects.filter(is_viewable=False) task_notifications = TaskNotification.objects.filter(task__in=tasks) for notif in task_notifications: event_start_time = notif.task.start_datetime notif_send_before = notif.send_before # will be an integer notif_time_option = notif.notif_time_option # minutes/hour/days if notif_send_req_time: # stucked here how to implement the logic notif.is_viewable=True notif.save() I will … -
Display choices from model (without using django forms)
We have an old django application developed, unfortunately it does not use django forms. It has many dropdowns implemented as follows (and form data is getting stored to the backend using ajax) <div class="form-group" data-enquiry-flag="2"> <label class="form-custom-label">Possession</label> <div class="btn-group" role="group"> <select name="possession_month" id="possession_month" class="form-control btn possession-btn btn-primary"> <option value="">----Select----</option> <option value="Jan" {% if enquiry.possession.possession_month == "Jan" %} selected {% else %} {% endif %}>Jan</option> <option value="Feb" {% if enquiry.possession.possession_month == "Feb" %} selected {% else %} {% endif %}>Feb</option> ... <option value="Dec" {% if enquiry.possession.possession_month == "Dec" %} selected {% else %} {% endif %}>Dec</option> </select> <select name="possession_year" id="possession_year" class="form-control btn possession-btn btn-primary"> <option value="">----Select----</option> <option value="2020" {% if enquiry.possession.possession_year == "2020" %} selected {% else %} {% endif %} >2020</option> <option value="2021" {% if enquiry.possession.possession_year == "2021" %} selected {% else %} {% endif %} >2021</option> ... <option value="2035" {% if enquiry.possession.possession_year == "2035" %} selected {% else %} {% endif %} >2035</option> </select> </div> </div> Earlier its model was something like this: class Possession(models.Model): possession_month = models.CharField(_('Possession Month'), max_length=5, blank=True) possession_year = models.IntegerField(_('Possession Year'), blank=True, null=True) # ... Other fields class Enquiry(models.Model): possession = models.ForeignKey(Possession, verbose_name=_("Possession"), null=True, blank=True, on_delete=models.CASCADE) Which I am modifying like this, from its accepted … -
Django: How to view all registered user Information in HTML template while login user have access to view anything, but user is not admin / superuser
i am new to Django: I am Creating a Website in which i want to show to All user Profiles in a Template to log-in user and when log-in user click to any user name visible in table field, information related to specific user will visible to log-in user .. In HTML Templates.. all registered user is visible in a table where i added the profile view link ***But in my scenario while i click the user name where i added view profile link the link is only showing log-in user information not the clicked user information *** My Project is Ecommerce My App are : Indenter, Login, Logout, Purchaser, Register, Supplier. - Ecommerce. URLs : from django.contrib import admin<br /> from django.urls import path, include urlpatterns = [ path('', include('Register.urls')), path('Login', include('Login.urls')), path('Logout', include('Logout.urls')), path('Purchaser', include('Purchaser.urls')), path('Intender', include('Intender.urls')), path('Supplier', include('Supplier.urls')), ] - Ecommerce.Register.URLs : urlpatterns = [ path('(?P<username>\w+)/profile_detail', views.profile_detail, name="profile_detail"), ] - Ecommerce.Register.views.py : This view i am calling in the Template to view the User information. def profile_detail(request, username): u = User.objects.get(username=username) user = request.user return render(request, 'profile_detail.html', {'user': user, 'user_url': u, }) tempaltes/indenter_home.html In this template in the table where all user is visible in usernaem field … -
What is the scope of global variables in the views.py?
If I declare a global variable myglobalvar in my views.py myglobalvar = "value" def home(request): print(myglobalvar) def thatOneLink(request): myglobalvar = "different value" When someone calls thatOneLink what is the scope of the change? Will myglobalvar = "different value" only for this request? Or only for the session? Or until the server restarts? In JSP by default there were settings on the scope. Django seems to have another package for that: https://pypi.org/project/django-scopes/ But in the very default case without any additional packages, how does Django handle scopes? Or do they have different names or definitions? -
overwite create method in djoser serializers
I am trying to overwrite create method after inheriting UserCreateSerializer from Djoser, but it does not get called when user-created serailizers.py djoser settings -
"Incorrect type. Expected pk value, received list." Error DRF React
Error when attempting post request Many to Many relation via React and Axios Question is how can i post list through axios along with image when I put list in request It shows an error "Incorrect type. Expected pk value, received list." View class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): print(request.data['categories']') file_serializer = serializers.PostSerializer(data=request.data) print(request.data.dict()) if file_serializer.is_valid(): print(request.data) file_serializer.save(owner=self.request.user) return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class PostSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') comments = serializers.PrimaryKeyRelatedField(many=True,queryset=Comment.objects.all()) categories = serializers.PrimaryKeyRelatedField(many=True,queryset=Category.objects.all()) class Meta: model = Post fields = ['id', 'title', 'body','owner','notify_users' ,'comments', 'categories','image'] Axios Request const handleSubmit = (e) => { e.preventDefault(); let form_data = new FormData(); form_data.append("image", postimage.image[0]); form_data.append("title", title); form_data.append("body", body); let catory = categories.map(val=>val.id) console.log(catory) let data = { title:title, body : body, categories:catory, image:postimage.image[0], notify_users : notifyuser } console.log(data.categories) //form_data.append("notify_users", notifyuser); form_data.append("categories",catory) console.log(catory) console.log('error here',form_data.get('categories')) authRequest.post('/posts/',form_data,{ headers: { 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; Github -
Django multi-table inheritance different from Postgres table inheritance
So I'm looking at Django's multitable inheritance, and how it differs from Postgres' table inheritance. Say I have the following models: models.py class Mayor(models.Model): name = models.CharField(max_length=255) class City(models.Model) name = models.CharField(max_length=255) mayor = models.ForeignKey(Mayor, on_delete=models.CASCADE) class Capital(City): embassy = models.BooleanField(default=False) Now, if I build the db from this, I get a table that looks something like: cities: +----------+------------------------+---------------------------------------------------------+ | Column | Type | Modifiers | |----------+------------------------+---------------------------------------------------------| | id | integer | not null default nextval('main_city_id_seq'::regclass) | | name | character varying(255) | not null | | mayor_id | integer | not null | +----------+------------------------+---------------------------------------------------------+ capitals +-------------+---------+-------------+ | Column | Type | Modifiers | |-------------+---------+-------------| | city_ptr_id | integer | not null | | has_embassy | boolean | not null | +-------------+---------+-------------+ This isn't idea, as it means that to get capital cities' mayors, I have to do 2 joins, one from capitals to cities, and then from cities to mayors. In Postgres, we can have: cities: +------------+-------------+------------------------------------------------------+ | Column | Type | Modifiers | |------------+-------------+------------------------------------------------------| | id | integer | not null default nextval('cities_id_seq'::regclass) | | name | text | | | mayor_id | realinteger | | +------------+-------------+------------------------------------------------------+ where the below table is listed as a 'child' capitals: +------------+--------------+------------------------------------------------------+ … -
Djongo Model Error “Select a valid choice. That choice is not one of the available choices.”
I'm using djongo package for a connector backend under django to the mongodb and define my models on it. models.py: class EventModel(BaseModel) name = models.CharField(max_length=20) class CalendarModel(BaseModel): name = models.CharField(max_length=20) color = models.CharField(max_length=20) event = models.ForeignKey(to=EventModel, on_delete=models.SET_NULL, null=True) and admin.py: from django.contrib import admin from .models import CalendarModel, EventModel @admin.register(CalendarModel) class CalendarAdmin(admin.ModelAdmin): exclude = ['_id'] @admin.register(EventModel) class EventAdmin(admin.ModelAdmin): exclude = ['_id'] At first it is ok with like that on sqlite backend and it's work when djongo backend without foreignkey field but send me an error when its on djongo backend and has foreignkey field. It said: error image And I can't create a new object with relation on it. How I can fix it? -
Field 'id' expected a number but got ObjectId
I'm studying djongo and i'm trying to create a platform that automatically assign a random amount (between 1 and 10) bitcoins to all new registered users. My code is following: #views.py def register_page(request): if request.user.is_authenticated: return redirect('order_list') form = RegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,'Account successfully created, welcome '+ username) newUserProfile(username) #<------ this is the function to generate the profile with random BTC return redirect('login') context = {'form':form} return render(request, 'api/register.html', context) #models.py class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) BTC = models.FloatField() balance = models.FloatField() pending_balance = models.FloatField() pending_BTC = models.FloatField() #utils.py def newUserProfile(username): user = User.objects.get(username=username) id = user.id BTC = round(random.uniform(1,10),2) profile = UserProfile.objects.create(id=id, user=user, BTC=BTC, balance = 0, pending_balance = 0, pending_BTC = 0) profile.save() When i push the register button on my webpage i get: Exception Type: TypeError Exception Value: Field 'id' expected a number but got ObjectId('606d892cb5d1f464cb7d2050'). but when i go in the database the new profile is regularly recorded: # userprofile tab {"_id":{"$oid":"606d892cb5d1f464cb7d2050"}, "id":49, "user_id":49, "BTC":3.26, "balance":0, "pending_balance":0, "pending_BTC":0} # auth_user tab {"_id":{"$oid":"606d892cb5d1f464cb7d204f"}, "id":49, "password":"pbkdf2_sha256$180000$nNwVYtrtPYj0$/wwjhAJk7zUVSj8dFg+tbTE1C1Hnme+zfUbmtH6V/PE=", "last_login":null, "is_superuser":false, "username":"Aokami", "first_name":"", "last_name":"", "email":"Aokami@gmail.com", "is_staff":false, "is_active":true, "date_joined":{"$date":"2021-04-07T10:27:56.590Z"}} How to resolve this, or atleast avoid the error page since i obtained anyway what i needed? -
Django orm get other foreign key objects from foreign object
I'm puzzled with this probably easy problem. My Models: class DiseaseLibrary(models.Model): name = models.CharField(max_length=255) subadults = models.BooleanField(default=False,blank=True) adults = models.BooleanField(default=False, blank=True) def __str__(self): return self.name class BoneChangeBoneProxy(models.Model): anomalies = models.ForeignKey('DiseaseLibrary', on_delete=models.CASCADE, related_name='anomalies') technic = models.ForeignKey('Technic', on_delete=models.CASCADE, related_name='technic_proxy') bone_change = models.ForeignKey('BoneChange', blank=True, null=True, on_delete=models.CASCADE, related_name='bone_change_proxy') bone = TreeManyToManyField('Bone', related_name='bone_proxy') From DiseaseLibrary I'd like to get all Objects that link to it via related_name "anomalies". Namely "technic_proxy", "bone_change_proxy", "bone_proxy" which are ForeignKeys to other models. I would expect to get access by the related name "anomalies" and _set >>> ds = DiseaseLibrary.objects.all().first() >>> ds.name 'Some nice name' >>> ds.anomalies <django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x107fa4f10> >>> ds.anomalies_set.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'DiseaseLibrary' object has no attribute 'anomalies_set' >>> How can I access all ForeignKey values in model BoneChangeBoneProxy through model DiseaseLibrary? -
django-plotly-dash, 'Error at Line 0 expected string or bytes-like object' in base.html?
I am working through a tutorial on connecting django-plotly-dash to a Django project. Before I added the Plotly components, I was able to access my templates without issue. Once I set up the various Plotly requirements, I now get this error when I try to go to the main page: error capture I'm not sure where to start figuring out what this is telling me, there are some similar issues on Google (and Stack Overflow) bet I am not seeing finding anything that seems related. Also, I'm basically a noob, so be gentle. -
How to get the value of a specific field in a form in Django view function?
I am trying to achieve a load-up process in my system where the user will input the load amount and add it to a user's current load. How can I get the amount entered in my view function? Here's my function in my views.py def LoadWallet(request, pk): user = get_object_or_404(User, id=request.POST.get('user_id')) user_wallet = user.wallet if request.method == 'POST': form = LoadForm(request.POST) if form.is_valid(): user_wallet = user_wallet+form.instance.load_amount User.objects.filter(id=pk).update(wallet=user_wallet) return HttpResponseRedirect(reverse('user-details', args=[str(pk)])) and the form in my template file <form action="{% url 'load-wallet' user.pk %}" method="POST"> {% csrf_token %} <label for="load_amount">Load amount</label> <input type="text" class="form-control" id="load_amount" onkeyup="replaceNoneNumeric('load_amount')"> <button type="submit" name="user_id" value="{{ user.id }}" class="btn btn-md btn-success" style="float: right; margin: 10px 5px;">Load</button> </form> Right now I tried this but it's returning "name 'LoadForm' is not defined". Should I declare the LoadForm first? Is there a better way to implement this? Thank you! -
django - set verbose_name to object name
How can I set the score charFields verbose_name in GamePlayers to the person.name attribute that it relates to? The Person model has data that is already created & is not empty. class Game(models.Model): name = models.CharField(verbose_name="Game Title", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) person = models.ManyToManyField( Person, through='GamePlayers', related_name='person' ) class Person(models.Model): name = models.CharField(verbose_name="Name", max_length=250) def __str__(self): return self.title class GamePlayers(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) score = models.CharField(max_length=6, verbose_name=person.name) def __str__(self): return f"game: {self.game.title}"