Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Streaming LLM output in Django
Im planning to develop Django framework for the LLM fine-tuned model based on HuggingFace models, I want the text to be streamed from model to the Django. My issue is that model streams the output in the terminal but not sure how to make it in a stream in a variable so that I can transfer it to the end-user I tried using pipeline with TextStream but it only output the text in the terminal model_id = "model_a" model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True, # attn_implementation="flash_attention_2" ) tokenizer = AutoTokenizer.from_pretrained( model_id, trust_remote_code=True ) streamer = TextStreamer(tokenizer) pipeline = pipeline( "text-generation", model=model, tokenizer=tokenizer, model_kwargs={"torch_dtype": torch.bfloat16}, streamer=streamer ) -
Why no pip packages accessible from any new directory wheras it is accessible from existing directories while in venv
I am working on a Django project. Recently while working on my new project, I had to delete py an open project folder. Now I am not able to access the list of pip packages from any of the newly created directories except being shown pip version number when I activate venv. However the pip list is accessible from any of the previously created directories even if create a venv in that foldeer and activate that venv. My file directory structures are as given below: pip list accessible in records_log folder of the following directory: C:\Users\abc\Projects\Python_proj_1\Python_proj_ml\records_log pip list is not accessible in newly created sub directory projects_practice folder: C:\Users\abc\Projects\Python_proj_1\Python_proj_ml\projects_practice\records_log The mini conda is installed at the following location: C:\Users\abc\miniconda3 I am able to mitigate this issue by changing the following line in pyvenv.cfg to True, which is supposed to remain default remains 'false' in all normally working directories. include-system-site-packages = true But as I know that there is something amiss. I do not wish to resort to using this work around like the one mentioned above. I need help to fix this issue and get the system as it was before I deleted the project file which led to this … -
Django form with MediumEditor not honoring required attribute
In Django, I have a TextField called 'description' in a model with null and blank set to False (for server side and client side validation). I'm using forms.ModelForm to pull the field and I'm using forms.Textarea to assign attributes. In the attributes, I'm assigning the medium-editor-textarea class attribute to leverage MediumEditor. This field is working as intended and the MediumEditor js is indeed called so that a user can leverage the MediumEditor wysiwyg in the text area; I also have a script in my form template that initializes a new instance of the MediumEditor class with all elements that have the class 'editable': var editor = new MediumEditor('.editable');. The one problem I'm having is that while the div and textarea both contain the required attribute, this is not prompting on the client side that this field is required when a user submits the form. Rather, I continually get the following error message in the console: An invalid from control with name='description' is not focusable, and this points to the textarea tag. In short, even with the required attributes, the browser prompt that the field cannot be empty is not firing on the client side. Here is the relevant code, trimmed … -
Trying to integrate TinyMCE into django but TinyMCE editor is not showing up
I'm following along sentdex's django development tutorial. This is the code in the admin.py file class TutorialAdmin(admin.ModelAdmin): fieldsets = [ ("Title/date", {"fields": ["tutorial_title", "tutorial_published"]}), ("Content", {"fields": ["tutorial_content"]}) ] formfield_overrides = { models.TextField: {'widget': TinyMCE()} } admin.site.register(Tutorial, TutorialAdmin) the tinyMCE editor is not showing up in the site I tried to add TinyMCE to a django site, but it is not showing up. How do I get TinyMCE to show up? -
Django rest framework's ModelSerializer missing user_id field causing KeyError
My ModelSerializer is getting a KeyError when I call .data on the serializer and I'm not sure how to properly fix this error. Knox's AuthToken model looks like this class AuthToken(models.Model): objects = AuthTokenManager() digest = models.CharField( max_length=CONSTANTS.DIGEST_LENGTH, primary_key=True) token_key = models.CharField( max_length=CONSTANTS.TOKEN_KEY_LENGTH, db_index=True) user = models.ForeignKey(User, null=False, blank=False, related_name='auth_token_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) expiry = models.DateTimeField(null=True, blank=True) def __str__(self): return '%s : %s' % (self.digest, self.user) I created a Model serializer class AuthTokenResponseSerializer(serializers.ModelSerializer): class Meta: model = AuthToken fields = "__all__" However, when I create a token_serializer, I get this error >> token_serializer.data *** KeyError: "Got KeyError when attempting to get a value for field `user` on serializer `AuthTokenResponseSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'user'." I think I am getting this error because when the token_serializer is created, it's missing a user key. I can see there is a user_id key but not user (Pdb) token_serializer AuthTokenResponseSerializer(context={'request': <rest_framework.request.Request: POST '/auth/token/'>}, data={'_state': <django.db.models.base.ModelState object>, 'digest': '6b82ac8776113db376d8938a641c3ebdea573b4ab49cb648c171fccc7f4a517e6450cebb21682e26f36562cf7b659f5089957ba49e99c096ebc9eaaa93ab0e53', 'token_key': '872832f8', 'user_id': 34, 'created': None, 'expiry': datetime.datetime(2024, 5, 11, 9, 17, 2, 540546, tzinfo=datetime.timezone.utc)}, partial=True): digest = CharField(max_length=128, validators=[<UniqueValidator(queryset=AuthToken.objects.all())>]) token_key = CharField(max_length=8) created = DateTimeField(read_only=True) expiry = DateTimeField(allow_null=True, … -
Optimizing Django/Postgres Query Performance: Filtering Many to Many relationship using Count Slows Down with Large Dataset
I do have such a model with class RecipeTag(models.Model): tag = models.CharField(max_length=300, blank=True, null=True, default=None, db_index=True) recipes = models.ManyToManyField(Recipe, blank=True) description = models.TextField(blank=True, null=True, default=None) language_code = models.CharField( max_length=5, choices=[(lang[0], lang[1]) for lang in settings.LANGUAGES], default='en', db_index=True # Index added here ) slug = models.CharField(max_length=300, blank=True, null=True, default=None, db_index=True) # Index added here is_visible = models.BooleanField(blank=True, null=True, default=True, db_index=True) # Index added here def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.tag) super(NewRecipeTag, self).save(*args, **kwargs) def __str__(self): tag = self.tag if self.tag else "Tag" return f"{tag} - Visible - {self.is_visible}" I need to filter all RecipeTag that have more then 2 recipes assigned to them, that I am currently doing like that tags = NewRecipeTag.objects.filter(language_code=meta['language'], is_visible=True).annotate(num_recipes=Count('recipes')).filter(num_recipes__gte=2) After that I am paginating them like that and displaying inside my html paginator = Paginator(recipe_tags, 60) page = paginator.page(page_number) recipe_tags = page.object_list My problem that, query taking around 20 seconds to finish, without annotate it happen almost instantly, I do have 4391166 records and hopping to find a solution that will help me to achieve my goal of displaying paginated tags filtered by recipes count as fast as possible, StackOverflow community that's your time! -
Django - Editing/updating records on formset triggering duplicate error
In Django, I have this FBV that updates selected records: def edit_selected_accountsplan(request): selected_items_str = request.GET.get('items', '') selected_items = [int(item) for item in selected_items_str.split(',') if item.isdigit()] accountsplan_to_edit = AccountsPlan.objects.filter(id__in=selected_items) AccountsPlanFormSet = formset_factory(form=AccountsPlanForm, extra=0) if request.method == 'POST': formset = AccountsPlanFormSet(request.POST) if formset.is_valid(): for form, accountplan in zip(formset, accountsplan_to_edit): accountplan.subgroup = form.cleaned_data['subgroup'] accountplan.name = form.cleaned_data['name'] accountplan.active = form.cleaned_data['active'] accountplan.save() return redirect('confi:list_accountsplan') else: initial_data = [] for accountplan in accountsplan_to_edit: initial_data.append({ 'subgroup': accountplan.subgroup, 'name': accountplan.name, 'active': accountplan.active, }) formset = AccountsPlanFormSet(initial=initial_data) return render(request, 'confi/pages/accountsplan/edit_selected_accountsplan.html', context={ 'formset': formset, }) Everything works as expected (the page loads, the form is filled correctly etc.) except when saving the data. The 'name' field is defined as unique in the database, so when I try to change other fields but don't change the name, it gives me a duplicate error. If I change the name to anything else that is not already in the database, it updates the current name correctly, so it's not creating a new record. I've tried to change the loop block to this just to see if I could save: for form, accountplan in zip(formset, accountsplan_to_edit): form.instance = accountplan form.save() return redirect('confi:list_accountsplan') But again, the duplicate error is triggered. I don't understand why this … -
Getting ModuleNotFoundError: No module named 'django' while deploying Django on uWSGI server, while uWSGI server is running on Cygwin on Windows OS
I have installed Cygwin on Windows 10 and installed following packages gcc-core (version 11.0.4-1, under Devel category ) gcc-g++ (version 11.0.4-1, under Devel category ) libintl-devel (version 0.22.4-1, under Text category ) gettext-devel (version 0.22.4-1, under Text category ) python3-devel (version 3.9.16-1, under Python category ) python38-devel (version 3.9.16-1, under Python category ) And I have installed uWSGI version 2.0.25.1 in Cygwin, to deploy a django application. The wsgi.py file of the Django application looks like import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PrateekGupta.settings') application = get_wsgi_application() The config file for uWSGI looks like [uwsgi] chdir = P:/Portfolio/Django module = PrateekGupta.wsgi:application pythonpath = /home/PrateekGupta/virtual_environment/Scripts/python master = True pidfile = /tmp/project-master.pid vacuum = True max-requests = 5000 daemonize = /var/log/Portfolio.log http-socket = 127.0.0.1:8000 buffer-size = 65536 I have activated the Virtual Environment and have installed python and django in it. The response of the pip list command is Package Version ----------------- ------- asgiref 3.8.1 Django 5.0.6 pillow 10.3.0 pip 21.3.1 PyJWT 2.8.0 setuptools 58.4.0 sqlparse 0.5.0 typing_extensions 4.11.0 tzdata 2024.1 wheel 0.37.0 But still whenever I run the uwsgi server with the command uwsgi --ini portfolio-uwsgi.ini In the log file I'm getting the error Traceback (most recent call last): File "/cygdrive/p/Portfolio/Django/./PrateekGupta/wsgi.py", … -
Quelle est le meilleur programmation pour une plateforme de protection de données [closed]
je suis sur le point de réaliser une plateforme de protection et je demande la plus adéquate programmation pour réaliser ce plateforme je ne suis qu'au tout début qui est le cahier de charge et le plan mais je saiqs la programmation utiliser Django python PHP java -
Static files path generated incorrectly in Django project
Description: In my Django project, the static files path is generated incorrectly, appending the current page URL before the static URL. For example, when I'm on the about page, the path becomes http://127.0.0.1:8000/about/static/images/bg/17.jpg instead of http://127.0.0.1:8000/static/images/bg/17.jpg. This causes issues with serving static files. How can I debug and fix this issue? STATIC_URL = '/static/' #Location of static files STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've checked my settings.py file and ensured that STATIC_URL = '/static/'. My static files are located in the correct directory (static/images/bg/17.jpg). I'm using the {% static %} template tag in my templates to reference static files. I've also run collectstatic after making changes to my static files. Expected Behavior: I expect the static files path to be generated as http://127.0.0.1:8000/static/images/bg/17.jpg regardless of the current page URL. -
Nginx + React + Django: Understanding CORS Request Headers
I'm hosting a React frontend app and Django backend API on Nginx in a single local Raspberry Pi, on ports 80 and 8000, respectively, with the following config: // REACT APP server { listen 80; listen [::]:80; root /link-to/build; index index.html; server_name pinode; location / { try_files $uri /index.html; } } // Django APP/Gunicorn server { listen 8000; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /link-to/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } For my use case, I'd like all internal requests between react and django to use localhost. However, the user can access the react front end using the Raspberry Pi's hostname (in this case, http://pinode/ as seen in nginx config above). In react, all API calls use http://localhost:8000/api/*. During my testing of the above, I had some level of success. However, one of the following always fails exclusively: During login, I get a response from http://localhost:8000/api/login/, but the Set-Cookie fails due to Cross-Site policy. Attempting to add headers to nginx backend config results in requests being rejected due to CORS policy. Post requests are rejected due to a missing csrftoken, despite axios is setup with X-CSRFToken header … -
How to post image and text in React Js form?
Here i have two component Child Component which passes text and image to the Parent component and Parent post the form But text is passed but image is getting error. I am using Django as Backend I can provide it too if required. Its just a simple Django-Rest-Framework No validation. Here when i console.log() p_details.Banner, p_imgs.Image both are providing an File Though i am facing Error. Banner : ['The submitted data was not a file. Check the encoding type on the form.'] product_image :"Image": [ "No file was submitted." ] const Parent_Comp = ({p_details, p_imgs}) =>{ const handleSubmit = async (event) => { event.preventDefault(); const products = new FormData(); Object.keys(p_details).forEach((key) => products.append(key, p_details[key])); var parentObj = []; for (var key in p_imgs.Image) { if (p_imgs.Image.hasOwnProperty(key)) { var file = p_imgs.Image[key]; var nameWithKey = p_imgs.Name + "[" + key + "]"; var obj = { "Name": nameWithKey, "image": file }; parentObj.push(obj); } } products.append('product_image', JSON.stringify(parentObj)); const productsObj = {}; for (const [key, value] of products.entries()) { if (key === 'product_image') { productsObj[key] = JSON.parse(value); } else { productsObj[key] = value; } } console.log(productsObj); try { const res = await axios.post('http://127.0.0.1:8000/media/product/create/', productsObj, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', // Assuming you're … -
Forbidden (CSRF cookie not set.) when trying to connect from a desktop app
I'm developing a desktop application where users can log in using credentials from my Django website's database. The goal is for users to be able to create posts on the Django website (forum) through the desktop application. In the desktop app's code, I have the following code, which successfully retrieves a CSRF token from Django: def get_csrf_token(): # Make a GET request to your Django server to fetch the CSRF token response = requests.get('http://127.0.0.1:8000/accounts/get-csrf-token/') # Check if the request was successful (status code 200) if response.status_code == 200: # Extract the CSRF token from the response JSON csrf_token = response.json().get('csrf_token') print("CSRF TOKEN: ", csrf_token) return csrf_token else: # Handle errors, such as failed requests print(f"Failed to fetch CSRF token. Status code: {response.status_code}") return None And the following code which should send the data (username, password, CSRF token) to Django: def login(self): # Retrieve username and password from input fields username = self.username_input.text() password = self.password_input.text() # Send login request to Django server url = "http://127.0.0.1:8000/accounts/login/" data = { "username": username, "password": password, } # Define the headers with the CSRF token headers = { 'X-CSRFToken': get_csrf_token() } print("x-csrftoken: ", headers['X-CSRFToken']) response = requests.post(url, data=data, headers=headers) if response.status_code == 200: # … -
Pipenv skipped update of package, Django 4.2 -> 5
I am trying to update from Django 4.2.13 to the most recent version (Django 5.0.6 at the time of writing). I ran pipenv update and a number of other dependencies were upgraded successfully, as reflected in my Pipfile.lock. However, Django was not upgraded from version 4.2.13, despite a newer version being available. Running pipienv update --outdated shows ✔ Success! Skipped Update of Package Django: 4.2.13 installed, {rdeps['required']} required (Unpinned in Pipfile), 5.0.6 available. All packages are up to date! What does this mean? How can I upgrade Django? -
Django-Oscar / Can't subscrive templates from costumer folder
I'm using django and oscar to create an ecommerce site. I'm trying to add allauth, and i need to add buttons to login_registration.html template. I set the templates dir to my custom template folder and already subscrived the oscar/base.html template and oscar/partials/brand.html template without any issue. Now i'm trying to subscrive the oscar/costumer/login_registration.html template but without any success. It simple does not go into my templates/oscar/costumer folder to look for the login_registration.html first, no matter what i do. I've tried deleting the original oscar login_registration.html to force it to look in my custom templates folder, no joy. I've tried with other html files from original oscar costumer folder, no joy. I've tried cleaning the cache, no joy. It works fine when subscriving base.html and partials/brand.html, but not inside costumer folder. -
Problem facing to fetch data from prayer time api in Django App
I am trying to fetch data from this app http://api.aladhan.com/v1/calendarByCity/:year/:month search by city but failed I am writing this code in my project. Can you please help me how to fix this problem?Thanks in advance. def index(request): if request.method == 'POST': city = request.POST['city'] source = urllib.request.urlopen( 'http://api.aladhan.com/v1/calendarByCity?city={Bangladesh}' + city).read() list_of_data = json.loads(source) data = { "Fajr": str(list_of_data['timings']['Fajr']), "Dhuhr": str(list_of_data['timings']['Dhuhr']), "Asr": str(list_of_data['timings']['Asr']), "Maghrib": str(list_of_data['timings']['Maghrib']), "Isha": str(list_of_data['timings']['Isha']), } print(data) else: data={} return render(request, "main/index.html",data)` I am trying to get data of five times prayer. -
Problem on django queryset and distinct/order with annotated fields
Can anybody help with this problem on django queryset distinct/order with annotated fields? THIS WORKS It returns nicely and called my Serializer after, no problem at all. def get_queryset(self) -> list: distinct_by = ('distance_to_first_point', 'id') pnt = create_point(float(lat), float(lng)) queryset = queryset.annotate(distance_to_first_point=Distance("first_point",pnt)).order_by("distance_to_first_point") return queryset.order_by(*distinct_by).distinct(*distinct_by) THIS DOENSN'T WORK If I try to access any field on the queryset it gives me this error: Cannot resolve keyword 'distance_to_first_point' into field I'm assuming the error is due to the annotated field, but Why? Before the distinct and order I can access queryset[0].distance_to_first_point for example and it works also.. def get_queryset(self) -> list: distinct_by = ('distance_to_first_point', 'id') pnt = create_point(float(lat), float(lng)) queryset = queryset.annotate(distance_to_first_point=Distance("first_point",pnt)).order_by("distance_to_first_point") queryset = queryset.order_by(*distinct_by).distinct(*distinct_by) queryset_ids = queryset.values_list('id', flat=True) return queryset -
What database should I use?
I am doing first steps in Django. And I want to write program which can help me in my сurrent work. What is the problem? I need to have fields with dictionary of objects. But I do not know how can I do this. As I understood it is rather problematic for sql databases. So can I use nosql ones to solve such problem? -
django-allauth cant select providers using administration page
I'm trying to add google authentication, I added 'allauth.socialaccount.providers.google' into installed apps and created SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } }, } but administration page doesnt show me this provider no option to select google Having followed all the required steps in the docs, obtained client id and secret key e and I also have refreshed, cleared cache, run makemigrations and migrate many times but the field won't show 'google' as the option. Could you show me the way to solve this? Thank you! -
save an image to media in post method django
I want to store an image in the media folder and the URL in the image field of the model. in this code the image is directly get saved to the model class CustomUser(AbstractUser): email = models.CharField(max_length=50,unique=True, null=True) username = models.CharField(max_length=50) userimage = models.ImageField(upload_to='profile/', null=True) phone = models.CharField(max_length=50) password = models.CharField(max_length=500) account_id = models.UUIDField(default=uuid.uuid4, editable=False) business = models.ForeignKey('company.Company', on_delete=models.CASCADE, null=True) and the view.py @api_view(['POST']) def CreateAcc(request): if request.method == 'POST': data = request.data password = make_password(data["password"]) mail = data['mail'] name = data['name'] phone = data['phone'] image = data['image'] CustomUser.objects.create(email=mail, username=name,phone=phone, password=password,userimage=image ) return Response(True) How to save the image the the media file ? -
Can't pass instance while creating an DB entry in django
I have two models, DocumentData & RecurringInvoice, which have a one to one relationship with each other. When I create an entry in the RecurringInvoice table, I want to pass in the DocumentData instance, instead of the id. But I get an error saying: {'document_data': [ErrorDetail(string='Incorrect type. Expected pk value, received DocumentData.', code='incorrect_type')]} It works if I pass the id of the instance though. From what I know, we can pass in either the instance or the id to link the entries. So why does it fail when I pass the instance? Relevant controller code: try: # get the document data instance doc_data = DocumentData.objects.get(id=docDataID) except DocumentData.DoesNotExist: return Response({ "message": "Document data does not exist" }, status=status.HTTP_400_BAD_REQUEST) invoice_serializer = RecurringInvoiceSerializer( data={ "document_data": doc_data, "send_date": request.data["send_date"], "recipients": request.data["recipients"], "invoice_name": request.data["invoice_name"] } ) if not invoice_serializer.is_valid(): print(invoice_serializer.errors, invoice_serializer._errors) return Response({"message": "Failed to save invoice data"}, status=status.HTTP_400_BAD_REQUEST) invoice_serializer.save() RecurringInvoice model: class RecurringInvoice(models.Model): document_data = models.OneToOneField( DocumentData, on_delete=models.CASCADE, null=True, blank=True) send_date = models.IntegerField( default=1, validators=[MinValueValidator(1), MaxValueValidator(28)] ) invoice_name = models.CharField(max_length=255) recipients = ArrayField(models.CharField(max_length=100)) is_paused = models.BooleanField(default=False) stop_date = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"ID: {self.id}, Name: {self.invoice_name}, Active Till: {self.stop_date}" class Meta: verbose_name = "Recurring Invoice" … -
LDAP Authentication with Django Rest Framework
I am new to Django and i am using Django Rest Framework for Backend. I followed this tutorial to add Ldap authenrication to my Django Rest Framework project. AUTH_LDAP_SERVER_URI = "ip" AUTH_LDAP_BIND_DN = "dn" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,tempelate" but when i try to login i get the error { "non_field_errors": [ "Unable to log in with provided credentials." ] } Where did i go wrong. The IP points to the correct address of Active Directory, the bind DN and Passwords are the ones i used in my Moodle Application and they work.I believe AUTH_LDAP_USER_DN_TEMPLATE corresponds to context. AUTHENTICATION_BACKENDS = ["django_auth_ldap.backend.LDAPBackend"] Here is the Authentication Backends. -
html dropdown subject list filter
me working on python django school LMS project and facing issue in html dropdown filter. there are 3 fields. teacher name, subject list, and checkbox of classes. If I select class 1 one then that time subject dropdown should be show only related subject but in subject list its showing all subject from database. i will attach a code and required output for reference. </head> <body> <script> function showSuccessPopup() { alert("Successfully Submitted"); } </script> <h2 style="text-align: center;">Assign Subjects and Classes to Teachers</h2><br> <div class="container"> <div class="card"> <form method="post" onsubmit="showSuccessPopup()"> {% csrf_token %} <div class="form-group"> <label for="teacher">Teacher:</label> <select name="teacher" id="teacher" class="form-control"> <option>----Select Teacher----</option> {% for teacher in teachers %} <option value="{{ teacher.id }}">{{ teacher.first_name }} {{ teacher.last_name }}</option> {% endfor %} </select> </div><br> <div class="form-group"> <label for="subject">Subject:</label> <select name="subject" id="subject" class="form-control"> <option>----Select Subject-----</option> {% for subject in subjects %} <option value="{{ subject.id }}">{{ subject.name }}</option> {% endfor %} </select> </div><br> <div class="form-group"> <label for="classes">Classes:</label> {% for cls in classes %} <div class="form-check"> <input type="checkbox" name="classes" value="{{ cls.id }}" class="form-check-input"> <label class="form-check-label">{{ cls.classes }}</label> </div> {% endfor %} </div> <button type="submit" class="btn btn-primary">Assign</button> </form> </div> </div> </body>[dropdown subject](https://i.sstatic.net/Tgkf4GJj.jpg) expected output in subject dropdown -
Django - Request Header Fields Too Large
We use an OAuth2-Proxy for our apps. Therefore the request header includes all groups of a user and the header get large. This is no problem for our fastAPI based apps but not for Django based apps. We always get 431 (Request Header Fields Too Large). Any ideas how to increase the max header value in Django? Request Header Fields Too Large Error parsing headers: 'limit request headers fields size' -
Django File Upload Not Working: Files Not Appearing in Media Directory or Database
I am developing a Django application where users can upload files associated with specific topics and submissions. Despite setting up everything according to the Django documentation, the files do not appear in the specified media directory or in the database after upload. I am using Django 5.0.4 and Python 3.10. Models.py: class File(models.Model): topic = models.ForeignKey(Topic, related_name='files', on_delete=models.CASCADE, null=True) submission = models.ForeignKey(Submission, related_name='files', on_delete=models.CASCADE, null=True) filename = models.FileField(upload_to='submissions/', null=True) upload_date = models.DateTimeField(auto_now_add=True) is_accepted = models.BooleanField(default=False) def __str__(self): return f"File: {self.filename.name} for Topic: {self.topic.name}" Forms.py: class UploadFileForm(ModelForm): class Meta: model = File fields = ('filename',) Views.py: def upload_file(request, subm_id, topic_id): submission = get_object_or_404(Submission, pk=subm_id) topic = get_object_or_404(Topic, pk=topic_id) form = UploadFileForm() context = {'submission':submission, 'topic':topic, 'form': form} if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_instance = form.save(commit=False) file_instance.topic = topic file_instance.submission = submission file_instance.save() messages.success(request, 'File succesfully uploaded') return redirect('upload_file', subm_id=submission.id, topic_id=topic.id) else: print(request.FILES) messages.error(request, 'No file was uploaded') form = UploadFileForm() return render(request, 'users/upload_file.html', context=context) Settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' Template: <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label class="form-label" for="{{ form.filename.id_for_label}} " >Загрузите файл</label > {{ form|crispy }} </div> <input class="btn btn-secondary" type="submit" value="Submit" /> </form> What could be causing …