Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login/authentication system not really working
I'm a newbie in django and I'm having some problems, what I'm trying to do is a simple login system in Django with a custom backend and using postgresql as the main db. The problem is, my authentication and login function is apparently working normally but the user is not actually logged in, I wrote a custom message to let me know when the user is logged in and my index is protected against anonymous user, so I basically can't access. This code from my views.py @login_required(login_url='signin') def index(request): return render(request, 'index.html') def signin(request): now = datetime.now() if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] print(username, password) user = UserBackend.authenticate(UserBackend(), username=username, password=password) if user is not None: login(request, user, backend='core.backends.UserBackend') print('Logged In') #### This print/checking is working fine! return redirect('/') #return render(request, 'index.html') else: messages.info(request, 'Invalid Username or Password! Try again') return redirect("signin") #else: return render(request,'signin.html') #user = auth.authenticate(username=username, password=password) return render(request, 'signin.html') This is my user class from models.py class user(AbstractBaseUser): id = models.AutoField(primary_key=True) username = models.TextField() real_name = models.TextField() email = models.TextField() password = models.TextField() description = models.TextField() last_login = models.DateField() created_at = models.DateField() is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Meta: managed = False db_table … -
How to access the field of a model which sits in 2 ForeignKey connections to the model, from where it being accessed?
Question might sound confusing but here is what I want to do. So, I somehow want to access the name of the course from the lesson model to create a file path to save videos class Course(models.Model): name = models.CharField(max_length=80) ... class Section(models.Model): name = models.CharField(max_length=80) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='sections') ... class Lesson(models.Model): name = models.CharField(max_length=80) section = models.ForeignKey(Section, on_delete=models.CASCADE) video = models.FileField(upload_to=f'courses/{section.course.name}/{section.name}/') Interpreter does not complain when I want to access the name of a section through this: section.name. But when I try the same approach and try to access the course name section.course.name I get this error: video = models.FileField(upload_to=f'courses/{section.course.name}/{section.name}/') AttributeError: 'ForeignKey' object has no attribute 'course' So what would be the best approach to access the name field of a course model? Thanks in advance!!! -
How to filter data in table based on user selection in form in Django?
I have Data model with records and these records are presented in web page. I have created function which prepares table with records from Data model and returns required structure of these data in pu.html web page. And I would like to filter these data based on user selection in a form on the same webpage. Therefore I created second model Manager_selection where user selection is stored and I get from this model last value based on which data are filtered in my function which prepares table with records. And what I need is to somehow include function for form in Views to be able to save user selection and based on which data will be filtered as my View is based on model Data, but form is based on model Manager_selection. models.py: Data model - includes detail data for each project (date, document_number, amount, project, account, company,...) Projects model - includes data about project (code, mo - project manager, vps - site manager, ...). This model is connected with Data model 1:N connection, so one project can have multiple Data records Employee model - includes first, second name and position - it is connected with Project model 1:N - … -
How to render results from API based on the user's search using Django
As you can see in the picture below I'm trying to have the user search for a given country, start/end date and get the result of "Confirmed Cases" and "Date" back from the API, but I'm not sure how to do it. Image I tried using this API, to fill the drop-down menu of the countries --> https://api.covid19api.com/summary but this is the other API that I have to use but while changing the parameters for the country and dates --> https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z Here are snippets of my code: views.py def home(request): # second_response = requests.get('https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json() second_response = requests.get('https://api.covid19api.com/summary').json() my_list = [] for i in range(0, len(second_response['Countries'])): my_list.append(second_response['Countries'][i]['Country']) if request.method=='POST': selected_country = request.POST['selected_country'] print('here', selected_country) return render(request, 'home.html', {'my_list': my_list}) home.html <div class="container justify-content-center"> <form action="{% url 'home' %}" method="post"> {% csrf_token %} <label for="selected_country" style="margin-right: 5px;"> Select a Country, Start & End Dates : </label> <select name="selected_country" > {% for object in my_list %} <option value="">{{object}}</option> {% endfor %} </select> <label for="startdate"></label> <input type="date" id="startdate"> <label for="enddate"></label> <input type="date" id="enddate"> <input type="submit" value="Search" /> </form> </div> PLUS: when I click on "search" i should get the value of the selected_country because I tried printing it, but it doesn't show for some … -
How can Django keep an API user logged in without a browser or return token?
https://github.com/mugartec/django-ninja-auth/blob/bf36b4583a37213001131678d5ecda07f92ba2f6/ninja_auth/api.py#L33 It doesn't return any token, so how to does it identify them post-login for subsequent requests? -
When deployment I got this error [error] 9#9: *1 connect() failed (111: Connection refused) while connecting to upstream Nginx 502 Bad Gateway
I have a project that contains Django - Docker - Postgresql - Nginx I followed this tutorial for adding SSL to my project using LetsEncrypt Link Before following this tutorial, my project was live on digitalocean succesfully. After that i got nginx 502 gateway error on my browser and when i check the certificate, certificate is verified and my connection is secure. When i check the log of proxy container on terminal i saw the [error] 9#9: *1 connect() failed (111: Connection refused) while connecting to upstream error upstream: uwsgi://my_ip:9000. my docker-compose-prod-yml file: version: "3.9" services: app: build: context: . dockerfile: ./Dockerfile restart: always command: /start environment: - DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY} - DJANGO_ALLOWED_HOSTS=${DOMAIN} depends_on: - postgres proxy: build: context: ./docker/proxy restart: always depends_on: - app ports: - 80:80 - 443:443 volumes: - certbot-web:/vol/www - proxy-dhparams:/vol/proxy - certbot-certs:/etc/letsencrypt environment: - DOMAIN=${DOMAIN} certbot: build: context: ./docker/certbot command: echo "Skipping..." environment: - EMAIL=${ACME_DEFAULT_EMAIL} - DOMAIN=${DOMAIN} env_file: - ./.env volumes: - certbot-web:/vol/www - certbot-certs:/etc/letsencrypt/ depends_on: - proxy postgres: image: "postgres:latest" container_name: postgres_data volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=te7eyp9cc - POSTGRES_DB=dj-crm-tenant ports: - "54320:5432" volumes: certbot-web: proxy-dhparams: certbot-certs: postgres_data: my defult-ssl-conf.tpl file: server { listen 80; server_name ${DOMAIN} www.${DOMAIN}; location /.well-known/acme-challenge/ { root /vol/www/; } … -
Why does Django randomly break when I use a deleted model in a migration?
I inherited a messy project, so as I've been cleaning up, I've deleted a lot of models. Sometimes, I have to copy date out of the model into another one before deletion. I've been writing migrations that do both. Everything is working fine - sometimes. And seemingly randomly, sometimes it doesn't work. Process: Make the necessary changes to the codebase, including deleting the model and references to it. Create a migration which: copies data out of model deletes the model Here's an example of what such a migration would look like: from django.db import migrations, models def doit(apps, schema_editor): OldModel = apps.get_model("myapp", "OldModel") NewModel = apps.get_model("myapp", "NewModel") for obj in OldModel.objects.all(): ...transform and save data in NewModel... class Migration(migrations.Migration): dependencies = [("myapp", "0001_initial")] operations = [ migrations.RunPython(doit, reverse_code=migrations.RunPython.noop), migrations.DeleteModel(name="OldModel"), ] Sometimes the migration runs as expected. Other times the migration fails with: LookupError: App 'myapp' doesn't have a 'OldModel' model. I cannot find any notable difference between the migrations that work and the migrations that blow up this way. I've had multiple examples of each, and have wracked my brain trying to spot the difference. My understanding is that the apps object passed to your function by the RunPython() method … -
How to remove square brackets when rendering dictionary items in django
I am working on a django project whereby I am saving values to the database of a Model instance. The project is a resume parser which seems to be getting the values as a dictionary. I have succesfully saved the data but when rendering the output does not look good as it renders with the square brackets and quotes. Is there a way I can render them as a list? Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', upload_to='profile_images') bio = models.TextField() resume = models.FileField('Upload Resumes', upload_to='resumes/', null=True, blank=True,default='resume.docx') name = models.CharField('Name', max_length=255, null=True, blank=True) email = models.CharField('Email', max_length=255, null=True, blank=True) mobile_number = models.CharField('Mobile Number', max_length=255, null=True, blank=True) education = models.CharField('Education', max_length=255, null=True, blank=True) skills = models.CharField('Skills', max_length=1000, null=True, blank=True) company_name = models.CharField('Company Name', max_length=1000, null=True, blank=True) college_name = models.CharField('College Name', max_length=1000, null=True, blank=True) designation = models.CharField('Designation', max_length=1000, null=True, blank=True) experience = models.CharField('Experience', max_length=1000, null=True, blank=True) total_experience = models.CharField('Total Experience (in Years)', max_length=1000, null=True, blank=True) whatsapp = models.URLField(null=True, blank=True) facebook = models.URLField(null=True, blank=True) twitter = models.URLField(null=True, blank=True) linkedin = models.URLField(null=True, blank=True) languages = models.CharField(max_length=1000, null=True, blank=True) profession = models.CharField(max_length=100, null=True, blank=True) nationality = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.user.username My views.py @login_required def myprofile(request, … -
In django with apache2 and wsgi, only some print statements to stderr end up in error_log
I am running django 3.2 with apache2 and mod_wsgi on a centos system. When I print to stderr or stdout from the settings.py file, I can see all of those in the default apache error_log. But, when I print to stderr or stdout in the rest of the project, they don't end up in error_log -- I can't find them anywhere. Here is the code for the print statements in my settings.py file, and these same type of print statements in a views.py file don't show up anywhere: print("read dot_env_file: " + str(dot_env_file)) print("DB_IMAGE: %s" % DB_IMAGE) print(sys.stderr, "MEDIA_ROOT: [" + str(MEDIA_ROOT) + "]") Here are the messages in error_log (I'm showing these since it says "wsgi:error" and so I thought it might be helpful): [Fri Dec 16 12:13:48.418738 2022] [wsgi:error] [pid 21770] read dot_env_file: /var/www/exprdb/.env [Fri Dec 16 12:13:48.474130 2022] [wsgi:error] [pid 21770] DB_IMAGE: None [Fri Dec 16 12:13:48.474169 2022] [wsgi:error] [pid 21770] <_io.TextIOWrapper name='<stderr>' encoding='utf-8'> MEDIA_ROOT: [/var/www/dj_media/] I don't have any special ErrorLog directives in the apache config. I don't have any LOGGING configuration in django's settings.py. Do you know how to fix this? What other details should I provide to you? -
django admin when field is autocomplete it overrides ModelForm filter
having issue on django admin. I want one of my foreign key field to be searchable and I achieved that making it autocomplete. class CollectionAdmin(VersionAdmin, admin.ModelAdmin): form = CollectionForm autocomplete_fields = ["task"] I also filter that foreign key in ModelForm. class CollectionForm(forms.ModelForm): class Meta: model = Collection fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.fields.get("task"): self.fields["task"].queryset = self.fields["task"].queryset.filter( status=TaskStatus.ASSIGNED ) When task is not autocomplete field in Collection my filter works as expected. However, when task is autocomplete field in Collection, filter does not work. Instead of my filter in form, task admin get_queryset method is called which is not what I want. TaskAdmin get_queryset method just filters by user, however I want more filter as you see above, for TaskStatus as well. def get_queryset(self, request): qs = super().get_queryset(request) if request.user.groups.filter(name=settings.COPYWRITER_GROUP).exists(): return qs.filter(assigned_to=request.user) return qs Repeating, form init filter works if field is not autocomplete. I tried removing task from autocomplete of Collection and it worked. I want my form filter not overridden if field is autocomplete. -
PayPal API integration with Django
I am integrating PayPal API with Django back-end (Reactcjs for front-end) in my project with the help of sandbox accounts (@business & @personal account). What I did till now is I have a client_id and a secret used for generating access_token from paypal. import requests import base64 def PaypalToken(client_ID, client_Secret): url = "https://api.sandbox.paypal.com/v1/oauth2/token" data = { "client_id":client_ID, "client_secret":client_Secret, "grant_type":"client_credentials" } headers = { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Basic {0}".format(base64.b64encode((client_ID + ":" + client_Secret).encode()).decode()) } token = requests.post(url, data, headers=headers) return token x = PaypalToken(my_client_ID, my_client_Secret) print(x.text) <code> This gonna provide me a token then I use that token to post json object on paypal. <pre> headers = {"Content-Type": "application/json", "Authorization": 'Bearer' + token} url = https://api.sandbox.paypal.com/v2/checkout/orders data = '{ "intent": "CAPTURE", "application_context": { "return_url": "https://www.example.com", "cancel_url": "https://www.example.com", "brand_name": "EXAMPLE INC", "landing_page": "BILLING", "shipping_preference": "SET_PROVIDED_ADDRESS", "user_action": "CONTINUE" }, "purchase_units": [ { "reference_id": "PUHF", "description": "Sporting Goods", "custom_id": "CUST-HighFashions", "soft_descriptor": "HighFashions", "amount": { "currency_code": "USD", "value": "220.00", "breakdown": { "item_total": { "currency_code": "USD", "value": "180.00" }, "shipping": { "currency_code": "USD", "value": "20.00" }, "handling": { "currency_code": "USD", "value": "10.00" }, "tax_total": { "currency_code": "USD", "value": "20.00" }, "shipping_discount": { "currency_code": "USD", "value": "10" } } }, "items": [ { "name": "T-Shirt", "description": "Green … -
Termux - Android(pip install --only-binay :all: mysqlclient --user)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? ^C $ pip install --only-binary :all: mysqlclient --user ERROR: Could not find a version that satisfies the requirement mysqlclient (from versions: none) ERROR: No matching distribution found for mysqlclient I am trying to execute python web based Django project in Android. How to solve this error?How can I able to install required mysqlclient in termux? -
JavaScript: Close Modal on correct Values
Good Day, I am currently nearly done creating a Modal with Vanilla JS, at present, my "Age Gate" does check if the age of the user is less than 18 and displays a error of 'Invalid Credentials', I have tried to go further by trying to close the modal on the correct value and then the modal to close, Please see my code below for the JS: const modal = document.getElementById("myModal"); const form = document.querySelector('form'); const loading = document.getElementById("loading"); const btnSubmit = document.getElementById('btnSubmit'); // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }; // Functions function onlyNumbers(e) { const ageGate = document.querySelectorAll('.ageGate'); const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; const errMsgDiv = document.getElementById('errorMsg'); let containsNumber = false ageGate.forEach(input => { if(numbers.some(num => input.value.includes(num))) containsNumber = true; }) if (containsNumber || ageGate.value !== numbers && ageGate.value == '' || ageGate[2].value < 2004) { let paragraph = document.createElement('p'); paragraph.innerHTML = 'Invalid Credentials'; errMsgDiv.append(paragraph); e.preventDefault() } else if (containsNumber = true) { btnSubmit.remove() loading.classList.remove('hide') } }; and now the Modal html: <div id="modal"> <div class="modal-content"> <div class="flex-container"> <div> <img src="{% static … -
User with correct credentials not login in django
views.py url.py login.html After login it should redirect to the Home page ,I got some solution and I tried that but it's not working for me -
how to store data in model which contain foreign key in Django
models.py class event_details(models.Model): e_id = models.AutoField(primary_key= True) class participants(models.Model): p_id = models.AutoField(primary_key= True) p_name = models.CharField(max_length=30) def __str__(self): return str(self.p_id) class event(models.Model): e_id = models.ForeignKey(event_details,on_delete = models.CASCADE, related_name = 'event_id') p_id = models.ForeignKey(participants, on_delete=models.CASCADE, related_name = 'pp_id') view.py def add_user(request): if request.method == 'POST': name =request.POST.get('name') reg = participants( e_id = 1, p_name = name, ) reg.save() return render(request,'web/Registration.html') Try to Store Participate name But Error that "participants.e_id" must be a "event_details" instance. can help me to solve it by store data in participants model -
how can I call my image in django media directory?
When I call image from template it works when I call it like this, <img src=http://127.0.0.1:8000/media/img/profile/8.jpg class="avatar rounded-circle img-thumbnail" alt="avatar"> I tried to do the same using url src = {{MEDIA_URL}}/img/profile/8.jpg src = "{{MEDIA_URL}}/img/profile/8.jpg" src = "media/img/profile/8.jpg" it did not worked I tried different variations of it by doing changes as above. my settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '/media/') my views.py def view_profile(request): user_files = UserFiles.objects.all() user_fields = Profile.objects.all() context = { 'title': 'profile', 'files': user_files, 'user_fields': user_fields, } return render(request, 'member/profile.html', context) my models.py class UserFiles(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def profile_image_upload_path(instance, filename): return f'img/profile/{filename}' picture = models.ImageField( upload_to=profile_image_upload_path, blank=True) def profile_letter_upload_path(instance, filename): return f'files/letter/{filename}' letter = models.FileField(upload_to=profile_letter_upload_path, blank=True) def profile_medical_upload_path(instance, filename): return f'files/medical/{filename}' medical = models.FileField( upload_to=profile_medical_upload_path, blank=True) def __str__(self): return self.user.username my urls.py urlpatterns = [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) can someone show me how to show files in my frontend using this tag or similar syntax, {% for fields in user_fields %} <div class="form-group row"> <label for="staticEmail" class="col-sm-2 col-form-label"> {{fields.label}}</label> <div class="col-sm-10"> <input type="text" readonly class="form-control-plaintext" id=" {{fields.name}}" value="{{fields.value}}"> </div> </div> {% endfor %} -
Trying to upload my project to pythonanywhere.com and getting errors
I need help. I'm trying to upload my project to pythonanywhere.com and getting errors. Who knows the solution? I tried to google and find a solution to the problem. But the results were in vain, like Sisyphean labor errors -
My models.py file is printing an error that does not makes sense to me
Here's my models.py: from django.db import models from django.contrib.auth.models import AbstractUser categories = ( ('car', 'CAR'), ('motorcycle', 'MOTORCYCLE'), ('car and motorcycle', 'CAR AND MOTORCYCLE'), ) yn = ( ('Free', 'FREE'), ('Ocupied', 'OCUPIED') ) class User(AbstractUser): pass class Slot(models.Model): status = models.CharField(max_length=20, choices=yn, default="True") def __str__(self): return f'slot {self.id} is {self.status}' class Parking(models.Model): title = models.CharField(max_length=140, default="unknown") category = models.CharField(max_length=20, choices=categories, default="car") img_src = models.CharField(max_length=200, default="../../static/capstone/img/parking4.jpg") slots = models.ManyToManyField(Slot) def __str__(self): return self.title class Slot(models.Model): status = models.CharField(max_length=20, choices=yn, default="True") def __str__(self): return f'slot {self.id} of {self.status} is {self.available}' When i try to run the server, this error is consoled: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: capstone.Parking.slots: (fields.E300) Field defines a relation with model 'Slot', which is either not installed, or is abstract. The Slot model is installed, i already made the migrations. But it's not functioning. I tried to reestart the terminal, but it didn't worked too. -
Getting NoReverseMatch error when trying to redirect user after form upload
I am getting the error NoReverseMatch in Django when I try to redirect the user to a new url after processing a form upload and succesfully saving the form. Here is my views.py @login_required def profile(request): if request.method == 'POST': profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile) files = request.FILES.getlist('resume') resumes_data = [] if profile_form.is_valid(): for file in files: try: # saving the file resume = profile_form.cleaned_data['resume'] parser = ResumeParser(file.temporary_file_path()) data = parser.get_extracted_data() resumes_data.append(data) profile_form.instance.name = data.get('name') profile_form.instance.email = data.get('email') profile_form.instance.mobile_number = data.get('mobile_number') if data.get('degree') is not None: profile_form.instance.education = ', '.join(data.get('degree')) else: profile_form.instance.education = None profile_form.instance.company_names = data.get('company_names') profile_form.instance.college_name = data.get('college_name') profile_form.instance.designation = data.get('designation') profile_form.instance.total_experience = data.get('total_experience') if data.get('skills') is not None: profile_form.instance.skills = ', '.join(data.get('skills')) else: profile_form.instance.skills = None if data.get('experience') is not None: profile_form.instance.experience = ', '.join(data.get('experience')) else: profile_form.instance.experience = None profile_form.save() return redirect('users-profile') except IntegrityError: messages.warning(request, 'Duplicate resume found') return redirect('users-profile') profile_form.save() messages.success(request, 'Your profile is updated successfully') # return redirect(reverse('userprofile', kwargs={"id": request.user})) return redirect('userprofile') else: profile_form = UpdateProfileForm(instance=request.user.profile) return render(request, 'user/resumeprofile.html', {'profile_form': profile_form}) @login_required def myprofile(request, user_id): profile = Profile.objects.get(id=user_id) context = {'profile':profile} return render(request, 'user/profile.html', context) And here is my urls.py: urlpatterns = [ path('', jobs_views.home, name='home'), #this is home function inside the views.py in the … -
How to provide a URL link from one app's template to the homepage which is in the root urls.py in Django?
I have to give a link to the homepage which happens to be the login page of my website, from an app's template, that is: <small style="margin-top: 5px;">To login<a href="{% url 'login' %}" class="login">Click Here</a></small> Now, the problem in the URL tag is that the link is available in the root urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.login, name='login'), ] How do I do this? -
Django product is not adding to cart
I am trying to add cart to my website using Django I have some problems: I cant add product to my cart and for some reason I do not have choice of quantity of this product this is my page that`s what i need this is my cart urls.py path('cart/', cart_detail, name='cart_detail'), path('cart/add/<int:post_id>/', cart_add, name='cart_add'), path('cart/remove/<int:post_id>/', cart_remove, name='cart_remove'), views.py @require_POST def cart_add(request, post_id): cart = Cart(request) post = get_object_or_404(Posts, id=post_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(post=post, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart_detail') def cart_remove(request, post_id): cart = Cart(request) post = get_object_or_404(Posts, id=post_id) cart.remove(post) return redirect('cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'store/detail.html', {'cart': cart}) def product_detail(request, post_id, slug): product = get_object_or_404(Posts, id=post_id, slug=slug, available=True) cart_product_form = CartAddProductForm() return render(request, 'store/detail.html', {'product': product, 'cart_product_form': cart_product_form}) my form in html file <form action="{% url 'cart_add' post.id %}" method="post"> {{ cart_product_form }} {% csrf_token %} <input type="submit" value="Add to cart"> </form> cart.py from decimal import Decimal from django.conf import settings from .models import Posts class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, post, quantity=1, update_quantity=False): post_id = str(post.id) if post_id not in self.cart: self.cart[post_id] = … -
Django updateview (cbv and fbv) to upload multiple files not working
I am trying to upload files (single and multiple) with an updateview (cbv and fbv) via an update template but I keep getting a 'This field is required' error when i submit and the files don't get uploaded of course. All required fields are filled with valid data types and the file upload fields are optional, so I don't understand where this error is coming from. I strongly suspect there's an error in my view specifically in the 'if form.is_valid():' section. I tried using both fbv and cbv, still i get the same error. I have even created a seperate model for the multiple files upload field and a seperate form class that extends the updateform class, still i get the same error. I am stumped. Please whatever help can be rendered will be highly appreciated. Thanks. this is the model for the multiple files upload field class shareCapitalFiles(models.Model): # Foreign key coopform = models.ForeignKey(CoopForm, on_delete=models.CASCADE) # Attach evidence of share capital attach_share_capital = models.FileField('Attach Share Capital', upload_to="documents", blank=True) this is my forms.py # Update Form class updateCoopForm(forms.ModelForm): nature_registration = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': 'flex inline-flex', 'cursor': 'pointer'}), choices=CoopForm.REGISTRATION_TYPE) have_bye_laws = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': 'flex inline-flex', 'cursor': 'pointer'}), choices=CoopForm.BYE_LAWS_CHOICES) attach_bye_laws = forms.FileField(required=False) class Meta: model … -
Upload to S3 Bucket from Django Models directly
I'm currently developing a Django application, and my images and staticfiles are initially uploaded to a local path, then when I run collect-static, it pushes everything to the S3 bucket. I was wondering if there is a way to remove intermediaries and directly upload the files and images to the S3 bucket. -
I am getting mistake Please Help Me Guys TY
# CHANGING THE COMPANY def change_company(request,pk): item = get_object_or_404(Companies, pk=pk) if request.method == "POST": form = CompaniesForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('display_companies') else: form = CompaniesForm(instance=item) return render(request, 'change_company.html', {'form':form}) here is my view The view companies.views.change_company didn't return an HttpResponse object. It returned None instead. Showing this mistake when i click on button in order to change my company table -
Django variables from forms to templates
I'm building a website and i'm trying to make the user able to change his credentials. I've made a form for this: newUsername = forms.CharField( label="Enter your new username here*", required=True, widget=forms.TextInput(attrs={ 'class': 'userChangeCredentials', 'value': "{{ user.username }}" })) newEmail = forms.EmailField( label="Enter your new e-mail adress here*", required=True, widget=forms.EmailInput(attrs={ 'class': 'userChangeCredentials', 'value': '{{ user.email }}' })) newPassword = forms.CharField( label="Enter your new password here", required=False, widget=forms.PasswordInput(attrs={ 'class': 'userChangeCredentials', 'value': '' })) passwordConfirmation = forms.CharField( label="Confirm your existing password here*", required=True, max_length=256, widget=forms.PasswordInput(attrs={ 'class': 'userChangeCredentials', 'value': '' })) The problem is, that the values in the widget dictionary are passed as raw text and i want them to be variables. This is the output: Do i need to change something inside of html? My html: <form id="UserForm" action="{% url 'user' name=user.username %}" method="POST"> {% csrf_token %} {{ form|safe }} <input class="userChangeCredentials" type="submit"></input> </form> I tried to make the text raw like this: widget=forms.EmailInput(attrs={ 'class': 'userChangeCredentials', 'value': r'{{ user.email }}' }) But it didn't help. I am seeking for the answer for like a week and i wasn't able to find any question on this theme. I've read the oficial Django form page, but there is nothing about this exact thing. …