Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python logging with crontab not working
i have python script in django project # bar.py import logging logger = logging.getLogger(__name__) def run(): ...some logic... logger.info("success") and i want make work this script using django-extesions runscript and crontab #setting.py 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'formatter': 'verbose', 'filename': 'foo.log', }, }, 'loggers': { 'myApp': { 'handlers': ['file'], 'level': 'DEBUG' } } if i run this script in terminal with django-exteions runscript, i can get foo.log and log message "success" /path/to/venv/python /path/to/myproject/manage.py runscript bar but run this script with crontab, script is doing very well, but it wasn't make foo.log and write nothing 10 * * * * /path/to/venv/python /path/to/myproject/manage.py runscript bar how can i solve this problem? -
django-cors-headers with spotify not working
I am using the spotify API/spotipy with django and need users to log into their accounts in order to access their data. I have used "pip3 install django-cors-headers" and added the appropriate sections to settings.py. #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jazz_stuff.apps.JazzStuffConfig', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CSRF_TRUSTED_ORIGINS = ( 'localhost:8000', ) #views.py def callSpotify(request): if request.method == 'POST': if request.is_ajax(): sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI, scope=SCOPE,cache_path=CACHE) url = sp_oauth.get_authorize_url() return HttpResponseRedirect(url) return None Even with this, I still get the error about missing the access-control-allow-origin header, and the spotify login page does not open up. jquery.min.js:2 XHR finished loading: GET "http://localhost:8000/callSpotify/". (index):1 Failed to load https://accounts.spotify.com/authorize?client_id=14c8a7dfd5804fb5994243e69bb7606f&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback%2F&scope=user-modify-playback-state+user-top-read&show_dialog=True: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. XHR finished loading: OPTIONS "https://accounts.spotify.com/authorize?client_id=14c8a7dfd5804fb5994243e69bb7606f&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback%2F&scope=user-modify-playback-state+user-top-read&show_dialog=True". How should I proceed so that I do not get cors errors? -
Django Forms: How to reference existing object field values in form validation?
So I am creating a Django app which I hope will be used in my school. This means that I have users that are teachers and students, and different permissions for these accounts. I have set it up so that every accounts has a self.teacher attribute, which is a boolean. So for students accounts, self.teacher will be False, and for teachers, self.teacher will be True. My app also contains a profile page, and this page has an edit profile feature. In my app, I want the user to be able to edit, amongst other things, their grade. Now, I have it set up so that grade can be an option of: - 10 - 11 - 12 - N/A Students must only be able to pick a number, while teachers are allowed to select N/A. So I want to have a form validation (which validates the grade field) that checks to see if the user submitting the form is a student, and if so, checks that they have not selected N/A. If they have selected N/A, the validation should raise an error. Any thoughts on how to implement this using Django Forms? -
Build Django Model (read only) on SQL statement - as one would on a db view but
Excuse my (django orm) ignorance, but I would like to create a view based on a raw ("ENGINE": "sql_server.pyodbc" but shouldn't matter). I find many examples of basing a django model on a db view, but need to do similar or a sql statement as I cannot create a view in the database. I think I need to use the raw() manager to execute the query but am stumbling through Django for the first in a long time and cannot find any specific examples of the way to incorporate this in the model definition. Using a database view built on the sql works fine, but is not practical in production using Django 2.0 - Thanks in advance! -
Unable to save a Django Model Object to a varchar datatype field on Sql Server
I am trying to update a object field on a legacy Sql Server database and it's not working. While I was debugging I realized that my problem was only when I was trying to save to a varchar data type field. I had no problem to save to a char data type field. Here follows my code: product = Product.objects.get(id=907169) product.brand = "test_value" product.save(update_fields=['brand']) In this case the variable brand has a varchar data type on the database. So, oddly the object doesn't save and still I get no error message. Any ideas what's going on? -
Django REST Filter_Class for the ManyToManyField
I have a model with a ManyToManyField. So, I have a endpoint to retrieve the list of this ManyToManyField. But I want filter the queryset with the GET parametters (CF: FilterClass). But What is the best practice to do that ? I have already a FilterClass for this model and it's 2 different models Thank you, @detail_route( methods=['GET'], url_path='parts', ) def get_parts(self, request, set__idSet=None): my_set = self.get_object() queryset = my_set.mySetParts.all() # I want filter this queryset page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) -
How to store Users' Location in a Django/Postgres Application
I am developing a react native app which adds a user's location to the databse every time the open the app. My goal is to store as much location data for the user as possible so I can do some machine learning to calculate which posts in their normal area of movement every day will pertain most to them. I use GeoDjango and PostGis to make the application location-aware, and am struggling to determine which data structure in the database will best fit this scenario. The question comes down to whether I should give each user a location = pg_fields.ArrayField() attribute which will end up being extremely large, or use a ManyToManyField for a UserLocation object in the Location app. I know toast tables are an issue in postgres with large arrays, but are they a big enough issue where it would not be worth the stress when trying to extract the data for the user when running machine learning algorithms? -
exclude vs filter using q
Can't understand how this is possible: A = object_list.filter( Q(sales__sale_starts__lte=today) & Q(sales__sale_ends__gte=today) ) # query inside filter catches 2 objects B = object_list.exclude( Q(sales__sale_starts__lte=today) & Q(sales__sale_ends__gte=today) ) # query inside exclude catches 3 objects, # though it is the same as previous # in other words: object_list has 20 objects, # A has 2 objects, and B has 17 objects Is there any difference in how filter() and exclude() working when using Q objects? Thanks. -
Django admin show proper child form based on parent field
I have the following models: #Abstact Parent Class import datetime class Media(models.Model): #Types of Media that Screens are capable to display in idle time MEDIA_TYPES = ( ('article', _('Article')), ('video', _('Video')), ('image', _('Image')), ) media_type = models.CharField(max_length=10, choices=MEDIA_TYPES, default=1) title = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) description = TextField(blank=True) duration = models.TimeField(default=datetime.time(00, 00)) screen = models.ForeignKey(Screen, on_delete=models.CASCADE) class Meta: verbose_name = _("Media") verbose_name_plural = _("Media") abstract = True class Image(Media): image = models.ImageField(upload_to='images/%Y/%m/%d/') class Meta: verbose_name = _("Image") verbose_name_plural = _("Images") #set media type to image def __init__(self, *args, **kwargs): self._meta.get_field('media_type').default = 3 super(Image, self).__init__(*args, **kwargs) class Video(Media): video = models.FileField(upload_to='videos/%Y/%m/%d') class Meta: verbose_name = _("Video") verbose_name_plural = _("Video") #set media type to video def __init__(self, *args, **kwargs): self._meta.get_field('media_type').default = 2 super(Video, self).__init__(*args, **kwargs) Parent class (Media) has a ForeignKey to Screen Model: class Screen(models.Model): #Types of Screens (To be replaced by dynamic screen types in app settings) SCREEN_TYPES = ( ('large', _('Large Touchscreen')), ('small', _('Small Touchscreen')), ('display', _('Display Screen')), ) # Fields screen_type = models.CharField(max_length=10, choices=SCREEN_TYPES, default='display') class Meta: verbose_name = _("Screen") verbose_name_plural = _("Screens") I want to edit Media as an inline of Screen in Django admin in such a way that when a … -
Django 1.11 - strange behavior in get_or_create
I see a strange behavior in get_or_create I have no record with slug='ian-osborn' >>> DjProfile.objects.get(slug='ian-osborn') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name frontend.models.DoesNotExist: DjProfile matching query does not exist. So I would expect get_or_create to istantiate a new DjProfile object but I get a Key (slug)=() already exists. error. >>> DjProfile.objects.get_or_create(slug='ian-osborn') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 464, in get_or_create return self.get(**lookup), False File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name frontend.models.DoesNotExist: DjProfile matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "frontend_djprofile_slug_f04b026a_uniq" DETAIL: Key (slug)=() already exists. I'm running a similar query in a Django command from django.core.management.base import BaseCommand from frontend.models import DjProfile class Command(BaseCommand): ... what am I doing wrong? -
How do I avoid saving duplicate data? [Django]
I would like to prevent the form from being saved if the "Oficio" number already existed. Is there any way to do a data check before saving the data in the database? If "Oficio" number exists, show error by informing "Existing Oficio Number". This is my template that insert data: {% extends 'base.html' %} {% block body %} <form action="" method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper form-group"> {{ form.numero.errors }} <label for="{{ form.numero.id_for_label }}">Número do Ofício:</label> {{ form.numero }} </div> <div class="fieldWrapper form-group"> {{ form.data.errors }} <label for="{{ form.data.id_for_label }}">Data:</label> {{ form.data }} </div> <div class="fieldWrapper form-group"> {{ form.para.errors }} <label for="{{ form.para.id_for_label }}">Para:</label> {{ form.para }} </div> <div class="fieldWrapper form-group"> {{ form.cargo_para.errors }} <label for="{{ form.cargo_para.id_for_label }}">Cargo Para:</label> {{ form.cargo_para }} </div> <div class="fieldWrapper form-group"> {{ form.assunto.errors }} <label for="{{ form.assunto.id_for_label }}">Assunto:</label> {{ form.assunto }} </div> <div class="fieldWrapper form-group"> {{ form.texto.errors }} <label for="{{ form.texto.id_for_label }}">Texto:</label> {{ form.texto }} </div> <button class="btn btn-group btn-primary" type="submit">Salvar</button> <a href="/oficio/">Voltar para a listagem</a> </form> {% endblock %} This is my view: def novo(request): if request.method == "POST": form = FormOficio(request.POST, request.FILES) if form.is_valid(): item = form.save(commit=False) item.responsavel = get_object_or_404(Responsavel, usuario=request.user) item.save() return render(request, 'salvo.html', {}) else: form = FormOficio() … -
how to set dynamic initial values to django modelform field
i'm kinda new to django, i need to set a dynamic initial value to my modelform field. i have a database field in my model name 'author' it has a foreignkey that connects it to the django user model. i need to automatically set this to the current user anytime a user fills in information into the form. from what i gathered about this problem, i'd have to define an init function inside the MyHouseEditForm below, i'm new to django and all the examples i've seen a pretty confusing. really nned help forms.py from django import forms from django.contrib.auth.models import User from .models import Myhouses class MyHouseEditForm(forms.ModelForm): class Meta: model = Myhouses fields = ('author','name_of_accomodation', 'type_of_room', 'house_rent', 'availability', 'location', 'nearest_institution', 'description', 'image') i need to set the value of 'author' to the current user anytime a user logs in. models.py from django.db import models from django.contrib.auth.models import User class Myhouses(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='author') Available = 'A' Not_Available = 'NA' Availability = ( (Available, 'Available'), (Not_Available, 'Not_Available'), ) name_of_accomodation = models.CharField(max_length=200) type_of_room = models.CharField(max_length=200) house_rent = models.IntegerField(null=True) availability = models.CharField(max_length=2, choices=Availability, default=Available,) location = models.CharField(max_length=200) nearest_institution = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to='profile_image') def __str__(self): return … -
Django channels: No module named 'asgiref.sync'
I am following this guide for channels tutorial (https://media.readthedocs.org/pdf/channels/latest/channels.pdf) and after adding channels to top of INSTALLED APPS, adding ASGI_APPLICATION = 'mysite.routing.application' to my setting file and creating following routing.py: # .../routing.py from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter({ # (http->django views is added by default) }) I am getting this error after running python manage.py runserver: ModuleNotFoundError: No module named 'asgiref.sync' I have following versions of libraries: Django (1.11.5) asgiref (1.1.2) channels (2.0.2) ... Can someone help me ? I am new to channels. -
Django Template--Conditional Based on The Current URL Path
I'm trying to exclude some content from the 'Blog' section of my site, and would like to exclude this info on any paths that start with /blog, which would include the main /blog page and and any other associate pages including blog/<blog-post> etc. I've looked at this post and tried some of the advice mentioned here but can't exactly get it to work. Here are my two blog URL's: url(r'^$', BlogListView.as_view(), name='blog'), url(r'^(?P<slug>[\w-]+)/$', blog_post, name='blog_post') and what I've tried (unsuccessfully) in my django template: {% url 'blog:blog_post' slug=slug as the_url %} {% if request.path == the_url %} <div>&nbsp;</div> {% else %} <div class="container"> <div class="nav-2"> <ul class="nav nav-pills"> {% block side_block %} {% get_category_list %} {% endblock %} </ul> </div> </div> {% endif %} I was able to get it to exclude the main blog page like this {% if request.path == "/blog/" %} <div>&nbsp;</div> {% else %} but having an issue with the actual blog posts. any ideas? -
How should I unit test middlewares in Django 2.0.2
I've been trying to test my custom middleware using this example however I'm getting this error message: missing 1 required positional argument: 'get_response'. How should I pass the parameter since according to this information __ init __ method in Django middleware must declare a get_response input, which represents a reference to a prior middleware class response. -
Custom Meta Sort
This is my meta model info (Django 2). class Meta: managed = True db_table = 'mydb' ordering = ['in_stock', '-type', 'sale_price', 'name'] I was wondering if I can evaluate the in_stock attribute dynamically. For example: If in_stock=0, then in_stock=50, else in_stock=1. My model should sort per the result of my conditional. Is this even possible? -
gunicorn,django ImportError: No module named application
Can anyone help? I recently merged migrations, then ran manage.py migrate, ran into an error, deleted the migrations because I didn't need them (models that I ended up not using). Now I am stuck with this error. Can anyone help? I searched elsewhere and didn't find anyone with the same error. This is just running the code by hand (as you see below). My whole site has a 502 bad gateway error; I imagine it is related to what you see below ♥root@ubuntu-2gb-nyc3-01:/home/mike/movingcollage#gunicorn --bind=unix:/home/mike/movingcollage/movingcollage.sock movingcollage.wsgi.application --preload /usr/local/lib/python2.7/dist-packages/djstripe/__init__.py:23: UserWarning: dj-stripe deprecation notice: Django 1.7 and lower are no longer supported. Please upgrade to Django 1.8 or higher. Reference: https://github.com/pydanny/dj-stripe/issues/275 warnings.warn(msg) Traceback (most recent call last): File "/usr/local/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 74, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 185, in run super(Application, self).run() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 71, in run Arbiter(self).run() File "/usr/local/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 57, in __init__ self.setup(app) File "/usr/local/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 113, in setup self.app.wsgi() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 66, in wsgi self.callable = self.load() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python2.7/dist-packages/gunicorn/util.py", line 356, in import_app __import__(module) ImportError: No module named application -
Getting and setting data in sqlite in django
So, I'm trying to update some information in sqlite db in django. What I wanna do is the following: 1. I get existing data from the db 2. Based on the data, I do some calculations on the given data to make new data. 3. After getting the new data, I put them in the sqlite db. I wanna do the process above manually or automatically. I'm currently using django framework to make some web application. In my website, there's a bunch of stores having customer reviews, and I wanna make popularity points of each store based on calculations of the reviews. How can I update data of a column based on data of another column? -
How can I launch a new terminal to track my shell script triggered from Django?
I'm working on a Django 2.0.2 project built in python 3.6.3 which necessitates forking off a shell script as a background child process. This is currently how I'm currently triggering it: import subprocess subprocess.Popen(./master.sh) Unfortunately, this doesn't echo to the same terminal as the Dango server like other processes on the site. The pipeline outputs to a log.txt file after completing, but as some jobs will take hours to complete, I'd like a way to follow the job as it happens by spawning a new terminal. I have tried using gnome-terminal commands, but so far I've had no successful readout. -
How to create Multi User Account
Please am really need you guys help on how to use Django to create Multi-user Account. e.g Student, Lecturers, and Department login page(Admin).. in this system the department will be the Admin to register the lecturers inorder to have access and why the Student register on their own... Am design a project titled Online Assignment Submission System (it is my final year Project)... I really need you guyz help... on how to go about it using Django. -
How do I filter access to certain views based on time?
I am trying to create a system whereby users can only access a certain page at a time which they have booked. Users who have not booked access to this time will not be able to access the page. Essentially the page will only be available to users once they have booked! I am trying everything I can to do it see my files below. models.py class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) daterequired = models.DateTimeField(default=timezone.now) students = models.CharField(max_length=200) length = models.CharField(max_length=40, blank=True) def __str__(self): return str(self.user) forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking exclude = ['user', ] widgets = { 'students': forms.TextInput(attrs={'placeholder': 'Number of Students'}), 'length': forms.TextInput( attrs={'placeholder': 'Time needed in hours'}), } views.py @login_required def choose(request): pod = Pod.objects.all() booking = Booking.objects.filter(user=request.user) bookingtime = booking.daterequired.strftime("%Y-%m-%d %H:%M:%S") currenttime = datetime.now().strftime("%Y-%m-%d %H:%M:%S") timedifference = currenttime - bookingtime if timedifference <= booking.length: return render(request, 'choose.html', {'pod': pod, 'booking': booking}) else: return HttpResponse("<p>NO ACCESS</p>") I am not sure how far off I am at the moment but would appreciate any help in the right direction. Thanks guys! -
Django not passing data to views on POST request
I've created a dropdown menu that is supposed to pass data to a view that'll help filter a queryset. However, it doesn't seem like the data is actually being passed to the view. Below is the relevant code I've written. template.html <!-- Query based content for dropdown menu --> <form method="POST" action="{% url 'property-selected' %}" id="property-select"> {% csrf_token %} <select class="dropdown-content" onchange="this.form.submit()" name="property-select"> {% if current_user_meters %} <option disabled selected> -- select an option -- </option> {% for meter in current_user_meters %} <option class="dropdown-menu-option" value="{{meter.id}}">{{meter.name}}</option> {% endfor %} {% else %} <option>You don't have any meters</option> {% endif %} </select> </form> views.py def property_selected(request): if request.method == 'POST': selection = request.POST.get('property-select') current_user_groups = Group.objects.filter(id__in=request.user.groups.all()) current_user_properties = Property.objects.filter(groups__in=current_user_groups) current_user_meters = Meter.objects.filter(meter_id__in=current_user_properties) selected_meters = Meter.objects.filter(name=selection) selected_meter_data = MeterData.objects.filter(name=selection).order_by('date') return render(request, 'properties/property-selected.html', { 'current_user_meters': current_user_meters, 'selection': selection, 'selectected_meters': selected_meters, 'selected_meter_data': selected_meter_data, }) for the querysets in the views file, the "selection" variable doesn't seem to be getting anything, which is where I want the data from the POST request to go. I want the data from the POST request to go there so my "selected_meters" and "selected_meter_data" queries will work as intended. Thanks! -
EditForm won't save the image from my ImageField
So basically I am just trying to change the data of my user. Everything works in the edit form, except that the image won't get saved. It gets passed in the form, my form has enctype enabled and also added request.FILES in the view, but nothing seems to work. When debugging, I only get that my form has no such 'photo' attribute. class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': "E-mail Address", 'class': 'email'})) name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Name", 'class': 'name'})) surname = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Surname", 'class': 'surname'})) photo = forms.ImageField(required=True, error_messages={'required': 'A profile picture is required.'}, widget=forms.FileInput(attrs={'class': 'profile_pic'})) phone = forms.CharField(max_length=15, required=True, validators=[RegexValidator(regex='^[0-9+]+$', message='Not a valid phone number.')], widget=forms.TextInput(attrs={'placeholder': "Phone Number", 'class': 'phone'})) class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'photo') if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, request.FILES, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.first_name = form.cleaned_data['name'] user.last_name = form.cleaned_data['surname'] user.save() form.save() return redirect('index') {% if user.is_student %} <div id="profile-edit"> <a id="close" href="{% url "index" %}"><i class="fas fa-times"></i></a> <form class="main-form" method="post" enctype="multipart/form-data"> {% csrf_token %} <h3 id="sign-title">Edit Profile</h3> <p class="field"> {{ form.email }}</p><br> <p class="field"> {{ form.name }}</p><br> <p class="field"> {{ form.surname }}</p><br> <p class="field"> {{ form.phone }}</p><br> <label id="file1" … -
Django POST shows in form, but doesn't come through to the next view
I have a simple form such as: <form action = "{% url 'endresult' %}" form method = "POST"> {% csrf_token %} <div class="well"> <h4 style="margin-top: 0"><strong> Student Details </strong></h4> <div class="row"> <div class="form-group col-md-4"> <label/> Student ID <input class="form-control" type="text" name = "studentpost" placeholder= "{{student.studentid}}" readonly> </div> </form> </div> The student ID does show up in my form, but when I try to get the results from endresult it shows up as a blank, if i try to call the studentid i get none. Why is this? def endresult(request): postedstudent = request.POST.get('studentpost') print(f"postedstudent : {postedstudent }") studentid = request.POST.get('student.studentid') print(f"studentid : {studentid }") return render(request, 'submitted.html') Here is my output: posteduser: ntname: None -
Error in accessing file in S3-Bucket using Django
I am using Django-mailbox, AWS-EC2 instance and AWS-S3 , So I am trying to send an attachment with mail and receive it on S3 bucket and I am successful to achieve this. Next while accessing that attachment file from saved path, it showing me following error, however file is saved successfully in given path, you can see in folder dir. My folder structure is as follows Let me know if any further details needed.