Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
inserting data into django db issues
I have the below code, trying to insert form data into the DB. I don't get an error, but nothing inserts, can anyone advise me as to why? Thanks VIEW from .models import Todo def create_task(request): if request.method == 'POST': creator = request.user assignee = request.POST.get('assignee') task = request.POST.get('task') i = Todo.objects.create(creator=creator, assignee=assignee, text=task, complete='FALSE') i.save(force_insert = True) MODEL class Todo(models.Model): creator = models.CharField(max_length=400, default="none") text = models.CharField(max_length=400) complete = models.BooleanField(default=False) assignee = models.CharField(max_length=400, default="none") def __str__(self): return self.text URLs urlpatterns = [ url(r'^$', views.todo, name='index'), url(r'^$', views.create_task, name='index'), -
How can I get different fields in a form inside a JSONField?
I'm working on a web that needs to store data that can be changed inside a JSONField. For example, my default JSON would be something like: { "apple": [ [5,10], [20,40] ], "banana": [ [5,10], [20,40] ], "orange": [ [5,10], [20,40] ], } Then my model would be something along the lines of: from jsonfield import JSONField ... class MyModel(models.Model): name = models.CharField(...) fruits = JSONField(default=json) And the form that I currently have is: class MyForm(forms.ModelForm): class Meta: model = models.MyModel fields = ( 'name', 'fruits' ) The template is a little bit trickier but lets say I have a code that prints a textbox for every number in the JSON, like: {% for fruit, values in user.MyModel.fruits.items %} <input type="text" name="{{fruit}}_0_0" value="{{values.0.0}} id="id_{{fruit}}_0_0"> <input type="text" name="{{fruit}}_0_1" value="{{values.0.1}} id="id_{{fruit}}_0_1"> <input type="text" name="{{fruit}}_1_0" value="{{values.1.0}} id="id_{{fruit}}_1_0"> <input type="text" name="{{fruit}}_1_1" value="{{values.1.1}} id="id_{{fruit}}_1_1"> I haven't been able to change the values in the database. It doesen't show an error, it just doesn't work. The MyForm.is_valid() in the views file returns False -
Using django admin site's multiple choice field
I guess most of you have paid attention to the admin site's multiple choice field: I want the exact same widget to my MultipleChoiceField in my form. How is it possible to use that widget? -
Unable to print all rows of DB to Django template
I am very new with Django and really need some help. So, I am making the basic to-do application and have created the database, added some sample data (which I can see through the admin interface) and now I need to print each line to the screen. I have the below and I'm not getting any errors, but it doesn't print. Can anyone advise? MODELS from __future__ import unicode_literals from django.db import models # Create your models here. class Todo(models.Model): text = models.CharField(max_length=400) complete = models.BooleanField(default=False) def __str__(self): return self.text VIEWS from .models import Todo def todo(request): todo_list = Todo.objects.all() context = {'todo_list' : todo_list} return render(request, 'home.html', context) HOME.HTML <ul> {% for todo in todo_list %} {{todo_list}} <li>{{ todo.text }}</li> {% endfor %} </ul> URLS from django.conf.urls import include, url from django.contrib import admin from netshock import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), url('login/', views.login_user, name='login'), url('logout/', views.logout_user, name='logout'), ] SETTINGS TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/django/django_project/netshock/templates/authenticate'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Django celery, celery-beat: fills the queue without control, scheduling troubles
I have small project with couple of tasks to run several times a day. The project is based on Django 2.1, having celery 4.2.1 and django-celery-beat 1.3.0. And also have rabbitmq installed. Each task is inside it's projects application. Runs, works, gives some result. The problem is - on virtual server, leased from some provider, if I set any task to run periodically (each hour, or two)- it starts running immidiately, without end and, as i suppose in some kind of parallel threads, wish mesh each other. Command rabbintmqctl list_queues name messages_unacknowldged always shows 8 in queue celery. Purging the queue celery does not give any changes. Restarting service - too. But setting tasks schedule to run in exact time works good. Well, almost good. Two tasks have schedule to run in the beginning of different hours (even and odd). But both run in about 30 minutes after hour beginning, of the same (odd) hour. At least tasks don't run more times in a day than set in schedule. But it is still something wrong. As a newbie with rabbitmq and celery don't know where to look for solution. Official celery docs didn't help me. May be was not looking … -
How do I get my PyCharm project to recognize my locally installed psycopg2 module?
I'm using PyCharm 2018.2.4 Professional Edition, Python 3.7 and Postgres 9.5 on Mac OS X. I have set up a connection to a PostGres DB running locally in my settings.py file ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myproject', 'USER': 'myproject', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' } } However, when I press "Option" and "R", I get the following error File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' Yet on my command line, I'm able to install the library successfully (I'm confused about whether to run pip or pip3 so I ran both): localhost:myproject_project davea$ pip install psycopg2 Collecting psycopg2 Downloading https://files.pythonhosted.org/packages/5c/c1/5e70da7f3ce144c5366e12d8b9c4d8659e803d03c8ec5057cb2eb0ee8077/psycopg2-2.7.6.1-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.5MB) 100% |████████████████████████████████| 1.5MB 110kB/s Installing collected packages: psycopg2 Successfully installed psycopg2-2.7.6.1 localhost:myproject_project davea$ pip3 install psycopg2 Collecting psycopg2 Downloading https://files.pythonhosted.org/packages/ff/db/942f8e40e93b5fe060c8d3a736d8fdd134fa5308dba8484dc06ae46e3fbd/psycopg2-2.7.6.1-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.5MB) 100% |████████████████████████████████| 1.5MB 441kB/s Installing collected packages: psycopg2 Successfully installed psycopg2-2.7.6.1 How do I install this module? -
when modelformset_factory and user identities disagree - a django predicament
The idea here is that each registered user should have access to posting 9 images to their profile page, and I was hoping I could use a modelformset_factory in order to keep D.R.Y. in terms om the model and the template. Several issues: I can only get one image to go through for each user that I have registered, also users can modify oneanother's images at the moment, which of course isn't optimal. The modelformset_factory form which is generated "thinks" that these 9 images are to be distributed amongst the users, ie. user pk=1 gets the first field, user pk=2 gets the second and so on and so forth. In stead I would like the factory to understand that each user should own 9 images and that only the owners of the images may modify their own galleries. I have no idea what I could put into the def __str__(self) to ensure that the images which the factory would spit out are appended with some sort of unique ID. It adds the username just fine, but it would be good if it could differentiate for instance by appendage of numbers 1 through 9 (please review comment in the model for … -
AJAX Data not Posting to View in Django
I've implemented a basic checkout wherein a user may select a shipping address from a list of addresses via the 'address' class. It works on the server side, but I would like to use AJAX to avoid having the page refresh with each selection. The code is not posting any data, however. What am I doing wrong? views.py def pick_address(request): if request.method == 'POST': checkout = Checkout.objects.get(pk=request.POST.get('checkout')) checkout.shipping_address = ShippingAddress.objects.get(pk=request.POST.get('address')) checkout.save() return HttpResponse('success') pick_address.js <script> $('.address').click(function () { $.ajax({ type: 'POST', url: '{% url 'pick-address' %}', dataType:'json', data: { checkout: {{ checkout.pk }}, address: {{ address.pk }}, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { if (data['success']) { alert('success!'); } } }); }); </script> -
How to get bytes from a BinaryField in Django?
Consider we have a model with a BinaryField: from django.db import models import hashlib class Target(models.Model): # ... image = models.BinaryField(max_length=(1<<24)-1) # ... def __str__(self): return hashlib.md5().update(image).hexdigest() Does the above code computes correctly the MD5 digest of the image? Or is there some method or variable inside BinaryField to get the memory to pass to the update() method? -
Django - Order by a GenericRelation count
I have the following model: class Story(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stories') likes = GenericRelation(Like) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Like is just a simple model that uses Django's content type framework: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) target = GenericForeignKey('content_type', 'object_id') All I want to do is order my stories by most liked, but I am unable to do so. I've tried the following with no avail: stories = Story.objects.annotate(count=Count('likes')).order_by('-count') Is there an easy way of doing this? -
Using jQuery mobile page transitions with Django url redirects
I am working on a website with jQuery mobile to style it and control ajax page transitions, but I am attempting to have an external redirect from the login page to the profile page using a Django redirect in the view. However, the url comes up as localhost:8000/#profile as if it is a jQuery redirect when I want it to be an external url redirect to localhost:8000/profile. I would use rel="external" or data-ajax="false", but the redirect is from a form sent to the Django view, not an html anchor tag. My html is: <html> <head> {% load staticfiles %} <link rel="stylesheet" href={% static 'style.css' %}> <script src={% static 'jquery-2.2.4.min.js' %}></script> <script src={% static 'jquery.mobile-1.4.5.min.js' %}></script> <link rel="stylesheet" href={% static "jquery.mobile-1.4.5.min.css" %}> <meta name="viewport" content="initial-scale=1"> </head> <body> <div id='login' data-role="page"> <div data-role="header"> <h1 class="title">Login</h1> <a data-transition="slide" id="to_new_account" class='ui-btn-right' href="#create_account">create</a> </div> <div data-role="content"> <form id="login_form" action="" method="POST"> {% csrf_token %} <input type="text" value="username" name="username"> <br> <input type="text" value="password" name="password"> <br> <input type="submit" value="login" name="login_button"> </form> </div> </div> <div id="create_account" data-role="page"> <div data-role="header"> <h1 class="title">new</h1> <a data-transition="slide" data-direction="reverse" class="button" href="#login">login</a> </div> <div data-role="content"> <form id="create_form" action="" method="POST"> {% csrf_token %} <input type="text" value="username" name="username"> <br> <input type="text" value="password" name="password"> <br> <input type="text" value="email" … -
Partial match in Django search
Is there a way to match for example "123" to "1234" (or "myse" in "mysearch", case insensitive) when performing a Django search? -
How to allow a django end-user to create their own table in a controlled and secured way?
This is regarding: Django / Django ORM / POSTGRES Goal: Allow an end-user to inherit from an existing model, create extra fields in it or create an entirely new model. pseudo model code Example: OriginalModel name = "Main Model" Value_1 = "First Value" User created variation parent = OriginalModel name = "Custom Model" Value_1 = "First Value" Value_2 = "Custom Additional Value" I tried: test_choices = ( ('str', 'str'), ('num', 'num'), ) class App(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users') name = models.CharField(max_length=100) class AppField(models.Model): app = models.ForeignKey(App, on_delete=models.CASCADE) type = models.CharField(max_length=100, choices=test_choices, null=True) title = models.CharField(max_length=100, default='') Problem How do you allow a user to create an AppItem that uses fields in AppField as model fields? Do you know a better way of doing this whole thing? -
I want to build a project with scrapy framework working as backend, Django as the framework and a UI to get the URL to scrape
I have the scrapy framework setup and running as a standalone project. What I want to build next is a Django framework, integrate that with my scrapy framework and build a UI(I know HTML/CSS) where a user can enter the URL to scrape and that URL is fetched and loaded to the backend spider script as a variable to crawl. Could someone guide me to some methodologies, or articles or answers, I just want to know the approach as to how to tackle this in the best possible way. Thanks in advance! -
I have variable Item name ,how to pass this variable to Url?
I have variable Item name ,how to pass this variable to Url ? html <!-- language: lang-html --> <form action="" method="POST" > {% csrf_token %} {{ field.errors }} <p style="font-size:30px" id="t">Chose The Item</p> {{ form.Item }} <a href="{% url 'ItemState' name=form.Item %}"> Done Form iclass ItemState1(forms.Form): Item = forms.ModelChoiceField(queryset=Product.objects.filter(state=1)) Url path('ItemState/<name>', ItemState, name='ItemState'), -
How to retrieve all values inside Django Postgres Array Field?
I used Django ArrayField with Postgres Database, I read the documentation however I cannot find a method to retreive all values saved inside the array field. After retrieved the record from database, I want to convert ArrayField type into python list type. This is their documentation -
Using an alternative model for password reset in Django
Due to the complexities of the application I'm creating, I ended up with three user models. One which is pretty much the normal User which is not used for anything other than admin and two others. I wrote my own set of auth backends to deal with it and it's working well. Now my problem is having a reset password system. Is there a way to use Django's reset password views while using a custom model? -
Cannot run python manage.py check
When I run said command I get python3 manage.py check Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "~/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "~/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "~/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "~/.local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "~/.local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "~/src/lavoro-fabio/places/models.py", line 2, in <module> from django.contrib.gis.db import models as g File "~/.local/lib/python3.6/site-packages/django/contrib/gis/db/models/__init__.py", line 3, in <module> import django.contrib.gis.db.models.functions # NOQA File "~/.local/lib/python3.6/site-packages/django/contrib/gis/db/models/functions.py", line 4, in <module> from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField File "~/.local/lib/python3.6/site-packages/django/contrib/gis/db/models/fields.py", line 3, in <module> from django.contrib.gis import forms, gdal File "~/.local/lib/python3.6/site-packages/django/contrib/gis/forms/__init__.py", line 3, in <module> from .fields import ( # NOQA File "~/.local/lib/python3.6/site-packages/django/contrib/gis/forms/fields.py", line 2, in <module> from django.contrib.gis.geos import GEOSException, GEOSGeometry File "~/.local/lib/python3.6/site-packages/django/contrib/gis/geos/__init__.py", line 5, in <module> from .collections import ( # NOQA File "~/.local/lib/python3.6/site-packages/django/contrib/gis/geos/collections.py", line 9, in <module> from django.contrib.gis.geos.geometry import GEOSGeometry, … -
Class Attribute user input taking way
Hey, I'm doing a project and I want to know if this is a Good way to take user input from class attribute? class FileStudio(): # CLASS ATRRIBUTES def __init__(self, file_name='tod', file_type='.py', complete_file='tod.py'): # Accept Strings self.file_name = input('file name: ') self.file_type = input('file type: ') self.complete_file = self.file_name + self.file_type def act(self): return self.complete_file print(FileStudio().act()) -
Adding both Django_filter and pagination to FilterView class in django
I am using the django_filters lib to filter my list views, here is the filter form : class WorkerFilter(django_filters.FilterSet): class Meta: model = Worker fields = ['id', 'branch'] here is how the view looks : class WorkerListView(FilterView): model = Worker paginate_by = 1 filter_class = WorkerFilter template_name = 'erp_system/worker_list.html' filterset_fields = ['id', 'branch'] def get_queryset(self): new_context = Worker.objects.filter( active=True, ) return new_context And am using the form inside the HTML template this way : <form action="" method="get"> {{ filter.form.as_p}} <button class="btn btn-warning" type="submit"><span class="fa fa-search"></span> بحث </button> </form> And at the end of this HTML page I have the list and the paginator this way : {% for item in filter.qs %} {{item}}<br> {% endfor %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}"><button class="btn-success">الصفحة السابقة</button> </a> {% endif %} <span class="page-current"> صفحة رقم {{ page_obj.number }} من {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}"><button class="btn-success">الصفحة التالية</button> </a> {% endif %} </span> </div> {% endif %} The paginator part is not showing even when I used paginate_by = 1 to debug it and make sure that {% if is_paginated %} works -
Two button with two different action in the same form
I have a form that two button/input. Button1 save the page and refresh it. Button2 save save the page and go to another url. Button1 is working with type="submit" and then view.py takes the data, saves them and refresh the data. My problem is with Button2. I added it with formaction="{% url 'team_area:home' %}" and actually redirect me but the problem is that it doesn't save the data. Button1 still works properly. Is possible to have some sort of request.the_id_of_pressed_button to use in view.py? If can be helpful here are my files involved: modify_players.html <h1>AREA SQUADRA</h1> <form method="post" action=""> {% csrf_token %} <h2>Giocatori</h2> {{ player_formset.management_form }} {% for player_form in player_formset %} {% if forloop.last %} {% if not forloop.first %} <input type="submit" value="Salva" formaction="{% url 'team_area:home' %}"> {% endif %} <h5>Nuovo giocatore:</h5> {% endif %} {% for field in player_form %} {% if forloop.revcounter == 2 %} {{ field }} {% elif forloop.parentloop.last and forloop.last%} {% else %} {{ field.label_tag }} {{ field }} {% endif %} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiungi"> </form> views.py @login_required(login_url="/accounts/login/") def modify_players(request): if request.user.team is not None: PlayerFormSet = modelformset_factory(Player, form=PlayerForm, extra=1, can_delete=True,) if request.method == "POST": player_formset = … -
Why does queryset.iterator() show poor performance
# I am using postgresql # queryset run complex SQL joining 4 tables print(queryset.count()) # print 30000 # it takes 5 sec for i in queryset: print(i.arg) # it takes 10 sec for i in queryset.iterator(chunk_size=30000): print(i.arg) I simplify situation I have suffered like above. iterator() takes more time about 2 times. Of course, I understand that iterator() need more DB-side operation and more request like DECLARE, FETCH and CLOSE because it is using DB CURSOR internally(in practice I check for Django to emit these request through DB log). However, I don't think these additional operations will take that much time. It even will fetch all rows at one FETCH request since chunk_size is the same as the total number of rows. I am wondering if this situation is expected one or not. If it is expected, why it takes that much more time? -
Uncaught SyntaxError: Unexpected end of JSON input. Can't properly parse the info to JSON from the html
Getting the error when trying to open the modal with product details after products were queried with help of ajax Error itself: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at HTMLButtonElement.<anonymous> (scripts.js:54) at HTMLDocument.dispatch (jquery-3.3.1.js:5183) at HTMLDocument.elemData.handle (jquery-3.3.1.js:4991) To be clear: I have some filters, result of which is filtered in the python filter_items function then it uses JSONResponse to send it to the front-end in form of a dictionary(as_dict() function in Item model) were they are added to hidden input value. JS function takes that hidden input value and renders the results of filtering using the data from that input. Item Model which is queried with help of filter function: class Item(models.Model): ITEM_TYPES = ( ('UM', 'Umbrella'), ('SK', 'Skirt'), ('TR', 'Trousers'), ('OT', 'Other') ) BRANDS = ( ('VS', 'Versace'), ('SP', 'Supreme'), ('SI', 'Stone Island'), ('FP', 'Fred Perry'), ) title = models.CharField(max_length=256) image = models.ImageField(upload_to='img/') brand = models.CharField(max_length=256) type = models.CharField(choices=ITEM_TYPES, max_length=2) description = models.TextField(blank=True, null=True) season = models.TextField(blank=True, null=True) discount = models.FloatField(blank=True, null=True) price = models.FloatField() def __str__(self): return self.title + ' ' + self.type def as_dict(self): data = {"title": self.title, "image": self.image.url, "brand": self.brand, "type": self.type, "discount": self.discount, "price": self.price, "rus_representation": self.rus_representation, "description": self.description, "season": … -
Custom django admin actin doesn't called twice as built-in delete_selected
I try to make custom admin action with intermediate setting page. My action perfectly visible in admin interface for correct ModelAdmin. Intermediate page occurs on action. But my action doesn't called when I submit intermediate page from. I have made my action as a copy of built-in delete_selected action. action form in intermediate action html template: <form method="post">{% csrf_token %} <div> <input type="hidden" name="action" value="assign" /> <input type="hidden" name="post" value="yes" /> <input type="submit" value="Yes, I'm sure"/> <a class="button cancel-link">No, take me back</a> </div> </form> action function in admin.py: def assign(modeladmin, request, queryset): selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) methodists = User.objects.filter(groups__name='methodologists') context = dict( ids=selected, ms= {str(x.id):x.username for x in methodists}, title="Set methodologiest", opts=Task._meta, app_label=Task._meta.app_label, media=modeladmin.media, action_checkbox_name="assign") return TemplateResponse(request, "admin/set_methologiest.html", context) -
Django - Showing two table data on a page
I have a table of lessons and exams. I list them by filtering according to the academicians. When I enter the content of the lesson, I see the data for the lesson. I want to see the exam information that belongs to the lesson on the lesson page and I cannot show it because there are different tables. Exams for each lesson: Mid-term and final exam. For example ; Mid-term exam, A, Final exam; Midterm exam for B, Final, Make-up exam. models.py def set_user_files_upload_path(instance, filename): return '/'.join([ 'users', 'user_%d' % instance.id, 'images', filename ]) class Lesson(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) lesson_name = models.CharField(verbose_name=_('Ders Adı'), max_length=150) lesson_content = models.TextField(verbose_name=_('Ders İçeriği'), blank=True) lesson_content_file = models.FileField( verbose_name=_('Ders İçeriği Dosya'), upload_to=set_user_files_upload_path, blank=True, null=True ) lesson_notes = models.TextField(verbose_name=_('Ders Notu'), blank=True) lesson_notes_file = models.FileField( verbose_name=_('Ders Notu Dosya'), upload_to=set_user_files_upload_path, blank=True, null=True ) def __str__(self): return '{lesson_name}'.format( lesson_name=self.lesson_name ) class Meta: verbose_name = 'Lesson' verbose_name_plural = 'Lesson' class Exam(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) exam_type = models.CharField(verbose_name=_('Sınav Türü'), max_length=50) exam_information = models.CharField( verbose_name=_('Sınav Hakkında Bilgi'), max_length=500) exam_file = models.FileField( verbose_name=_('Sınav Kağıdı Dosya'), upload_to=set_user_files_upload_path, blank=True, null=True ) exam_answer_file = models.FileField( verbose_name=_('Cevap Anahtarı Dosya'), upload_to=set_user_files_upload_path, blank=True, null=True ) def __str__(self): return '{lesson} - {exam_type}'.format( lesson=self.lesson.lesson_name, exam_type=self.exam_type ) class Meta: verbose_name = …