Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / GeoDjango / PostGis - Filter FeatureCollection
Currently i have a very basic django model containing a PointField: from django.contrib.gis.db import models from django.utils.translation import gettext_lazy as _ from api.models import AbstractModel class SampleEntity(AbstractModel): point = models.PointField(_('point')) My goal is to filter all rows and check if the point is in a certain polygon... In order to create a polygon i receive the following payload (FeatureCollection): { "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "source": "© GeoBasis-DE / BKG 2013", "features": [{ "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [10.453980128926366, 47.55557895879648], [10.438876535127962, 47.52349211089603], [10.44055084477551, 47.5135694350795], [10.431323512106337, 47.5036776164676], [10.442767953986108, 47.4846168990274], [10.45131095387671, 47.485685093946636], [10.463220692620368, 47.48277492286606], [10.468022327337152, 47.47691846929882], etc.. ] ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [9.617342617593987, 47.568803310179476], [9.628007474077956, 47.570911279233016], [9.628870213746309, 47.56638028461108], [9.638605938479984, 47.56693417152559], [9.653552559008789, 47.55698746615904], [9.679038885003902, 47.55702134414172], [9.682804387548277, 47.55244003193477], [9.675623645853232, 47.54522412435771], etc.. ] ] } }] } Next i need to somehow convert my FeatureCollection to a valid "GeoDjango" Polygon in order to filter in the database: geoms = [] for feature in payload["features"]: geoms.append(GEOSGeometry(str(feature["geometry"]))) geometry = GeometryCollection(geoms) rows = SampleEntity.objects.filter(point__within=geometry) print(rows) # <- Error Raises: django.db.utils.InternalError: Relate Operation called with a LWGEOMCOLLECTION type. This is unsupported. HINT: Change argument 1: … -
django ValueError : attribute has no file associated with it
I have an annoying error that I'm not able to fix it. If the article has all 4 photos it's ok, if it doesn't have all 4 photos I got ValueError. I tried to solve this with an if statement but it seems it doesn't work. Any tips? html <div class="other"> {% if object.photo_1 %} <div class="list-one-images"> <img class="hover-shadow cursor" onclick="openModal();currentSlide(1)" src = "{{ object.photo_1.url }}"> </div> {% endif %} {% if object.photo_2 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(2)" class="hover-shadow cursor" src = "{{ object.photo_2.url }}"> </div> {% endif %} {% if object.photo_3 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(3)" class="hover-shadow cursor"src = "{{ object.photo_3.url }}"> </div> {% endif %} {% if object.photo_4 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(4)" class="hover-shadow cursor" src = "{{ object.photo_4.url }}"> </div> {% endif %} </div> model: class Oglas(models.Model): agent = models.ForeignKey(Agent, on_delete = models.DO_NOTHING) title = models.CharField(max_length=120) address = models.CharField(max_length = 120) area = models.CharField(max_length=120) description = models.TextField(blank = True) price = models.IntegerField() bedrooms = models.DecimalField(max_digits=2, decimal_places=1) bathrooms = models.DecimalField(max_digits=2, decimal_places=1, blank = True, null = True) garage = models.IntegerField(default = 0) sqft = models.IntegerField() kategorii = (('prodava', 'prodava'),('iznajmuva','iznajmuva')) kategorija = models.CharField(max_length = 10, choices= kategorii, null = True) lot_size = models.DecimalField(max_digits=5, decimal_places=1) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') … -
How to solve 'module' object is not iterable in django
I have created a Django application and initially the code worked perfectly but when I restarted the development server I started having 'module' object not iterable exception. This is my code views.py import datetime from django.contrib import messages from django.shortcuts import render from forms.forms import * from django.core.mail import send_mail from django.http import HttpResponse from patients.models import * def doctor_view(request, id): patients = Patients.objects.get(id=id) if request.method == "POST": form = DoctorForm(request.POST) if form.is_valid(): f = form.save(commit=False) date = datetime.datetime.now() f.date_seen = date f.save() messages.info(request, 'patient profile was successfully updated !!!') else: form = DoctorForm(instance=patients) date = datetime.datetime.now() return render(request, 'doctors/templates/patient_registration.html', {'form': form, 'title': 'Patient Treatment', 'patients': patients, 'date': date, 'messages': messages}) ``` urls.py from django.urls import path from . import views urlpatterns = [ path('<int:id>/', views.doctor_view, name='doctor-views'), ]``` Exception Traceback Internal Server Error: /doctor/1/ Traceback (most recent call last): File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\SERU\Desktop\School Projects\DAS_project\doctors\views.py", line 42, in doctor_view {'form': form, 'title': 'Patient Treatment', 'patients': patients, 'date': date, 'messages': messages}) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return … -
Generic detail view PostDetailsText must be called with either an object pk or a slug in the URLconf
I am stuck trying to figure out how to fix this error. I'm trying to list all available categories and to display post a single overview. I know what the error is referring to (path), but I don't understand how to fix it. Here is my main url.py file urlpatterns = [ path('', PostDetailsText.as_view(), name='post_more_details'), ] These are my views for lisitng and details: class CategoryListing(TemplateResponseMixin, View): model = Post template_name = 'publications/posts/listing_posts.html' def get(self, request, category=None): categories = Category.objects.annotate(total_posts=Count('posts')) posts = Post.objects.annotate(total_modules=Count('modules')) if category: category = get_object_or_404(Category, slug=category) posts = posts.filter(category=category) return self.render_to_response({'categories': categories, 'category': category, 'posts': posts}) class PostDetailsText(DetailView): model = Post template_name = 'publications/posts/posts_details.html' The urls of the app: urlpatterns = [ path('category/<slug:category>/', views.CategoryListing.as_view(), name='categories_listing'), path('<slug:slug>/', views.PostDetailsText.as_view(), name='post_details'), ] This is how it looks like my html for listing the items: <div class="contents"> <h3>Categories</h3> <ul id="modules"> <li {% if not category %}class="selected"{% endif %}> <a href="{% url 'post_more_details' %}">All</a> </li> {% for s in categories %} <li {% if category == s %}class="selected"{% endif %}> <a href="{% url 'categories_listing' s.slug %}"> {{ s.subject }} <br><span>{{ s.total_posts }} posts</span> </a> </li> {% endfor %} </ul> </div> <div class="module"> {% for post in posts %} {% with category=post.category %} … -
Webpack configuration for react and django app
I am planning to make a boilerplate in GitHub between React and Django To facilitate me later When I start a project I chose the connection method React as Django app django-admin startapp frontend The problem I am facing now is that I am using the Django templates. I cannot split packages using wepback because there must be {load static} {static ''index.js"} However, I cannot use Splitchuncks in configuring a webpack or HTML plugin to insert script tags into HTML. The entire code must be inside one js file and that too with CSS webpack.config.js const path = require("path"); const webpack = require("webpack"); // const TerserPlugin = require('terser-webpack-plugin'); const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const devMode = process.env.NODE_ENV !== "production"; module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, { test: /\.css$/, use: [ devMode ? "style-loader" : MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", ], }, { test: /\.(ttf|eot|woff|woff2|jpg|jpeg|png|gif|mp3|svg|ico)$/, loader: "file-loader", options: { outputPath: path.resolve(__dirname, "./static/images"), }, }, ], }, optimization: { minimize: true, // splitChunks: { // chunks: 'all', // name: false, // }, }, plugins: [ new HtmlWebpackPlugin( Object.assign( {}, … -
Django- update a DateField model entry to be a string as a default
I have a function in my Django model: def add_default_date This function, if called from the view, checks to see if publish_date is None and if it is, I'd like to change publish_date to be text: "Date Needed". However right now when I do this I get an error: "'Date Needed' value has an invalid date format. It must be in YYYY-MM-DD format.". It appear that I'm trying to assign a string to a DateField but it's not working. Is there anyway to do this? Models.py: class Byte(models.Model): """Model for databyte content.""" publish_date = models.DateField(blank=True, null=True) def add_default_date(self): if self.publish_date is None: self.publish_date = "Date Needed" Views.py: bytes = Byte.objects.order_by( F('publish_date').desc(nulls_last=True) ) for b in bytes: Byte.add_default_date(b) b.save() -
Curl command doesn't work in config file on AWS
I have a Django web application that is deployed to AWS elastic beanstalk (Python 3.7 running on 64bit Amazon Linux 2/3.1.3). I am trying to run the following config file files: "/usr/local/bin/cron_tab.sh": mode: "000755" owner: root group: root content: | #!/bin/bash exec &>> /tmp/cron_tab_log.txt date > /tmp/date source /var/app/venv/staging-LQM1lest/bin/activate cd /var/app/current python manage.py crontab add exit 0 container_commands: cron_tab: command: "curl /usr/local/bin/cron_tab.sh | bash" This file placed in the .ebextentions folder. All other config files are working properly. However, this one is not working. Also, I have tried to run the container_commands code manually on SSH and it gives output such as below. curl: (3) <url> malformed I also checked the /tmp folder but there is no cron_tab_log.txt. I checked /usr/local/bin the cron_tab.sh is located there. I just want this Django-crontab run after the deploy and it doesn't work. How can I handle this issue? -
upgrade django2 to 3 DigitalOcean droplets missing css files
I just install fresh image of django from DigitalOcean droplets marketplace and its work perfectly but its version 2 so I try to upgrade it to 3 and everything went fine except admin page missing 2 file [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav_sidebar.css, line 0) [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav_sidebar.js, line 0) -
Django user model custom fields names
How to rename fields of the user model? I want to rename the fields first_name to firstName, last_name to lastName with AbstractUser class User(AbstractUser): email = models.EmailField('email address',unique=True) firstName = models.CharField("First Name", max_length=150) lastName = models.CharField("Last Name", max_length=150) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'username', 'firstName', 'lastName', ] The above code works, but it does not rename the fields what it does is add the fields firstName and lastName Any ideas or suggestions? -
how to create enable registered users to create their own staff user in django
How to enable registered users on my website to create their own staff users ? Their staff user should be able to login in registered users dashboard . I am very new to coding so please help , how should i move forward ? -
React - Can't get my Axios to POST to my backend URL? Backend URL's work just fine via tests
I'm testing out a new user registration form. I've used this exact same form set-up for my login page, it works just fine, users can login with their credentials and connect to the backend. However, this time when I try to reflect the same method onto my registration form, I'm getting a forbidden 403 error from django. I've tested out the URL path using Postman and Swagger, they both work fine (without headers). Which is why you see the 201 white response in my terminal above. The 403 only occurs when I try to register via my React Frontend app. Here is my Axios post request: const onSubmit = (data, e) => { console.log(data); axiosInstance .post(`user/register/`, { email: data.email, username: data.username, first_name: data.first_name, last_name: data.last_name, password: data.password, subscribed: data.subscribed, }) .then((res) => { history.push('/login'); console.log(res); console.log(res.data); }); }; Here is the code of my React registration form. export default function SignUp() { const { register, control, errors: fieldsErrors, handleSubmit } = useForm() const history = useHistory(); const initialFormData = Object.freeze({ email: '', username: '', first_name: '', last_name: '', password: '', subscribed: false, }); const [formData, updateFormData] = useState(initialFormData); const handleChange = (e) => { updateFormData({ ...formData, ...e, // Trimming any … -
How can you return a value according to the radio field selected?
I'm making a checkout page with radio selection to choose from stripe and paypal. When the user selects Stripe it should direct to the Stripe checkout and when the user selects Paypal, it should go to the paypal one. HTML: <form method="POST" class="post-form"> {% csrf_token %} <div class="col-md-12"> {% for value, name in form.fields.payment_option.choices %} <div class="radio"> <label><input type="radio" name=paymentMethod id="{{ name.id }}"class="mr-2">{{ name }}</label> </div> {% endfor %} </div> </div> <div class="form-group"> <div class="col-md-12"> <div class="checkbox"> <label><input type="checkbox" value="" class="mr-2"> I have read and accept the terms and conditions</label> </div> </div> </div> {% if name in form.fields.payment_option.choices == stripe %} <button type="submit" class="btn btn-primary py-3 px-4" action="{% url '' %}">Place an order</button> {% endif %} </form> urls.py: urlpatterns = [ path('', views.index, name='index'), path('shop/', views.shop, name="shop"), path('about/', views.about, name="about"), path('blog/', views.blog, name="blog"), path('contact/', views.contact, name="contact"), path('checkout/', views.checkout, name="checkout"), path('cart/', views.cart, name="cart"), path('product-single/<slug:slug>/', views.productpage, name="productpage"), path('add-to-cart/<slug:slug>/', views.add_to_cart, name="addtocart"), path('remove-from-cart/<slug:slug>/', views.remove_from_cart, name="removefromcart"), path('payment/<payment_option>/', PaymentView.as_view(), name='payment') ] -
Django, google app engine, bucket No 'Access-Control-Allow-Origin'
Hello i've a problem that i can't solve. Now i've a simple django project and i'm close to finishing. a few days ago i upload my static files and media files to google cloud sql-bucket. Normally everything was fine for media files but when i upload static files something started to happens. Here some of error messages(30+): Access to script at 'https://storage.googleapis.com/denka_metal_static_bucket/debug_toolbar/js/toolbar.js' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/denka_metal_static_bucket/debug_toolbar/js/toolbar.js net::ERR_FAILED Access to font at 'https://storage.googleapis.com/denka_metal_static_bucket/Fonts/jost/Jost-500-Medium.woff2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Also normally django wasn't accept my static files because of they are in somewhere else but i loaded django-cors-headers (i don't know is it full name.) and django accept most of css docs. Here is my settings.py (I cut some parts when i paste here): ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'honeypot', 'ckeditor', 'ckeditor_uploader', 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'Product.apps.ProductConfig', 'captcha', 'admin_honeypot', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ( 'http://127.0.0.1:8000', 'http://localhost:8000', 'https://storage.googleapis.com', 'https://googleapis.com', ) CSRF_TRUSTED_ORIGINS = [ … -
Class based views
I'm experimenting with class based views as I've not worked with them yet. I'm also pretty new to Django. I'm having trouble correctly using slug or pk and setting up my URL's in my products app. My Project level urls.py: from django.conf import settings from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('home.urls', namespace='home')), path('products/', include('products.urls')), path('checkout/', include('checkout.urls')), ] urls.py(product app): from django.urls import path from .views import ItemDetailView urlpatterns = [ path('', ItemDetailView.as_view(), name='products'), ] views.py(products app): from django.shortcuts import render from django.views.generic import DetailView from home.models import Item def products(request): context = { 'items': Item.objects.all() } return render(request, "products/products.html", context) class ItemDetailView(DetailView): model = Item template_name = "products/product.html" I have tried adding <slug>/ to the products url pattern but that doesn't work. I'm pretty sure I need to adjust my url's but I'm not sure how. -
don't show checkbox type boolean on models.py
i have models item filed itm_stop: class item(models.Model): itm_stop=models.BooleanField(verbose_name='item stop',default=False) in file forms.py: from django import forms,modelsForm class itemsForm(modelsForm.Form): class Meta: model =item fields = "__all__" in file views.py : from .forms import itemsForm def items_create(request): if request.method == 'POST': form = itemsForm(request.POST, request.FILES) else: form = itemsForm() return render(request, 'items/items.html',{"items" :form}) in file Templates item.html: {% load widget_tweaks %} {% for field in items %} <!-- append to an attribute --> <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} When I do the presentation, I cannot display the checkbox, and it appears as an empty box on the page, and I did not find the reason for that -
Redirecting to Home Page if session not found
I'm creating a form where data is coming from previous form and i'm storing that data in session. If user directly visits second page than I want the user to redirect to first page, but I can't find any way to do it. Is it possible? my code(second page) def get(self, request): a = request.session['a'] since a is not set if user directly visits this page I want him to redirect to first page if session not found. -
Username appearing in django migrations over custom User model with no username
I have written a custom User model, with no username. Still it appears in migrations as primary key and throws unique constraint error while adding new user. Here is my User Model Manager: class UserManager(BaseUserManager): def create_user(self, password,email=None, phone=None, **extra_fields): if not email and not phone: raise ValueError("User must have an email address or phone number") if email: email = self.normalize_email(email) user = self.model(email=email,**extra_fields) elif phone: user = self.model(phone=phone,**extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.model( email=self.normalize_email(email), is_staff=True, is_admin=True, is_superuser=True, ) user.set_password(password) user.save() return user Here is my User Model: class User(AbstractUser): email = models.EmailField(unique=True, verbose_name='email address', max_length=255, null=True ) phone = models.CharField(unique=True, verbose_name='phone number', max_length=10, null=True ) name = models.CharField(max_length=300,null=True) profile_pic = models.ImageField(null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return str(self.email) def has_perm(self, perm, obj=None): "Does the user have a specific permission?" return True def has_module_perm(self, app_label): "Does the user have permissions to view the app `app_label`?" return True Now,The migrrations: migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. … -
How to create an object that has an ImageField within the test code?
I'm creating something like a blog post, the blog post can contain multiple images. To be able to include a variable number of images, I created a new model called Image. This model contains a ForeignKey to the user that owns it, and an ImageField. Code: class Image(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) image = models.ImageField(upload_to=get_image_upload_path) In the post model, I have a ManyToManyField for the Image model. this way, I can have a variable number of images. images = models.ManyToManyField('Image', blank=True) I'm trying to test my code. In one of the tests, I'm trying to create a couple of images, then create a post with the images being passed to in a list. How do I create an instance of the model Image within the tests and provide it an image? image = Image.objects.create(user=self.user, image=...) What should be written instead of ... here? -
Django admin dynamically add to list_display depending on related model
I'd like to dynamically include some extra fields in the list_display of the admin for one of my models. I plan on overriding get_list_display to append a string representing a ModelAdmin method but how can I dynamically create the ModelAdmin methods? class Type(models.Model): ... modules = models.ManyToManyField(Module) class User(AbstractBaseUser): ... type = models.ForeignKey(Type) class UserModuleRecord(User): class Meta: proxy=True @admin.register(UserModuleRecord) class UserModuleRecordAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name'] def get_queryset(self, request): return ( super().get_queryset(request) .annotate_the_additional_list_display_values() ) def get_list_display(self, request): list_display = super().get_list_display(request) modules = Module.objects.all() for module in modules: list_display.append('module_%s' % module.id) return list_display In the above example if get_list_display returns [..., 'module_1', 'module_2'] that means I need methods for module_1 and module_2. Additionally is it possible to create something similar to how get_FOO_display works so there's only one admin method required? -
Hello, my database was changed from 11G to oracle 19C,
my database was changed from 11G to oracle 19C, with that I used the form of authentication using "sid", the error I was giving was 12505, currently the database uses the form "Service Name" , when changing the information in the python django format, stopped giving error 12505, however, now it is giving error ORA-28040. will I need to make any changes to the code? because I only made changes to the database data, putting it in the format that accepts the service_name -
How to import data from csv file to the default Django User model?
I know there is an import-export package which allows us to import data from csv file to our own models by making changes in the admin.py file, but I am not able to do this if I want to import data from csv file to the default User model present in Django. Is there any way to do that? -
django redirect throw 302 and not redirecting
views.py from django.shortcuts import redirect, render ... if request.method == "POST": if request.POST.get("go_to_review"): app = Appointment.objects.get(id=request.POST.get("go_to_review"), status="COMPLETED") has_review = Feedback.objects.filter(appointment=app) print(f"has view : {bool(has_review)}") if bool(has_review): return redirect("patient:patient_profile") my urls.py ... path("", patient_dashboard_view, name="patient_dashboard_view"), path("profile/", PatientProfileSetting.as_view(), name="patient_profile"), ... server log is as : ... HTTP GET /static/img/favicon.png 200 [0.00, 127.0.0.1:58430] has view : True HTTP POST /patient/ 302 [0.04, 127.0.0.1:58458] value of user inside the get_data HTTP GET /patient/profile/ 200 [0.19, 127.0.0.1:58458] ... actually it renders the other view(when i put a print statement on other view it prints that, but redirecting mean it doesn't render that view in screen but it switches to that. As I'm new to django correct me if explained wrong). ~thanks in advance -
IntegrityError at /friendreques/ NOT NULL constraint failed: core_user.pending error in Django
IntegrityError at /friendreques/ NOT NULL constraint failed: core_user.pending. How to overcome this error. user_s = User.objects.get(username = request.user) user_s.pending = edited user_s.save() In pending model is pending = models.TextField() -
Django Form upload to AWS S3 with Boto3 results in empty file
I am having a multipart/form-data form that should upload to a S3 bucket, using Boto3. All is happening as expected, but at the end, the file at the S3 bucket has 0 bytes. forms.py: class DropOffFilesForm(forms.ModelForm): file = forms.FileField(error_messages={'invalid_type': _("Please upload only PDF, JPG, PNG, XLS(x), DOC(x) files")}, validators=[ FileTypeValidator(allowed_types=['application/pdf', 'image/*', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], allowed_extensions=['.pdf', '.png', '.jpg', '.doc', '.docx', '.xls', '.xlsx'])], required=False) description = forms.CharField(widget=forms.Textarea, label=_("Description"), required=False) def clean_description(self): data = self.cleaned_data['description'] return data class Meta: model = DropOffFiles exclude = ['filename',] fields = ['file', 'description'] views.py: file_form = DropOffFilesForm(request.POST, request.FILES) if file_form.is_valid(): file_form = file_form.save(commit=False) s3 = boto3.client('s3', region_name=settings.AWS_ZONE, aws_access_key_id=settings.AWS_KEY, aws_secret_access_key=settings.AWS_SECRET) file = request.FILES['file'] if file: file_type = file.content_type extension = file.name.split(".")[-1] # construct file name and location filename = calculate_md5(file) + '.'+extension # save the file try: response = s3.upload_fileobj(file, 'bucketname', filename) except ClientError as e: logging.error(e) return False file_form.filename = filename file_form.dropoff = dropoff file_form.save() Happy for any suggestion. -
How do I send all form data from one view to another with sessions in Django
So I already know how to send and receive one value from InputWebView to DisplayWebView but I need to send all values from my form and receive it on the other side to process further. How do I do that? <form method="POST" action=""> {% csrf_token %} {{ form.non_field_errors }} {{ form.web_input }} <input type="submit"> </form/> def InputWebView(requests): form = WebInputForm(request.POST or None) if request.method == 'POST': if form.is_valid(): request.session['web_input'] = request.POST['web_input'] return redirect('add_web') def DisplayWebView(request): var = request.session.get('web_input')