Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dockerize a django app with nginx and gunicorn using supervisor
I have a dockerized project built with django and nginx. The app runs gunicorn to serve the python project and nginx to serve static files. The problem was that nginx serves the assets in a different port and this is not suitable for production nor testing specially if I am running my projects with Kong and Konga and I need to run the app in the port 8010. To face this problem I tried to implement supervisor but I haven't been able to make it run properly. This the project structure: blacklist/ asgi.py settings.py urls.py wsgi.py blacklist_app/ controllers/ migrations/ templates/ uploaded_files/ urls.py models.py views.py etc (app's files) config/ nginx/ nginx.conf uwsgi/ uwsgi.ini supervisor/ supervisord.conf docker-compose.yml Dockerfile manage.py requirements.txt #docker-compose.yml version: '3' services: web: container_name: subida-excel build: . command: gunicorn -w 10 --timeout 86400 -b 0.0.0.0:8011 blacklist.wsgi volumes: - ./db.sqlite3:/code/db.sqlite3 ports: - "8010:8010" networks: - kong-net environment: - ALLOWED_HOST=${SUBIDAEXCEL_HOSTS} - DEBUG=${SUBIDAEXCEL_DEBUG} - BASE=${SUBIDAEXCEL_URLBASE} networks: kong-net: external: true volumes: db.sqlite3: #/config/uwsgi.ini [uwsgi] socket = 127.0.0.1:8011 chown = www-data:www-data uid = www-data gid = www-data chdir = /code/ processes = 4 threads = 2 wsgi-file = /code/blacklist/wsgi.py #/config/nginx/nginx.conf server { listen 8010; server_name _; location /static { alias /code/assets/; try_files $uri $uri/ =404; … -
Combining ListView and DetailView
I need your help please. I need to combine a ListView and a DetailView in a single template. I have list items appearing on the left and so I want when someone clicks one of the list item, the details should show on the left. Picture is here of what I want to achieve views.py class RequestDetail(LoginRequiredMixin, DetailView): model = Request fields = ['content', 'author_group', 'assign_to', 'ref_code'] template_name = 'request/request_detail.html' def in_requests_progress(request): context = { 'in_requests_in_progress': Request.objects.filter(assign_to=request.user.profile.department).filter(status='Progress') } return render(request, 'request/in_inprogress.html', context) -
Question about model connections in Django
There are two models: class Author(models.Model): first_name = models.CharField(max_length=150, help_text="Фамилия") second_name = models.CharField(blank=True, max_length=150, help_text="Имя") third_name = models.CharField(blank=True, max_length=150, help_text="Отчество") def __str__(self): return '{0} {1} {2}'.format(self.first_name, self.second_name, self.third_name) def get_absolute_url(self): return reverse('author-detail', args=[str(self.id)]) class Book(models.Model): title = models.CharField(max_length=200, help_text="Название книги") author = models.ManyToManyField('Author', help_text="Автор") year = models.CharField(max_length=4, help_text="Год издания") def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) On the page with information about the book I want to display its author, but what I do does not work: <p><strong>Автор:</strong> {{ book.author }}</p> Also a problem with the author id. This line is broken: {{ author.get_absolute_url }} -
How do I migrate the original starting tables from Wagtail back
I have a wagtail website in development where due to a mistake, I lost the initial tables that Wagtails loads into your database with names like auth_group_permissions and wagtailcore_page. With normal Django migrations, a migration file is made everytime you run makemigrations and you can access them in your app directories. But I cannot find any file that would load the initial tables into my database. Clearly, there are Wagtail apps in my Django settings.py file, but no corresponding maps or migration files. Where can I find this code? And how do I get the tables back into my database? Thank you in advance! -
Facing Connection Error In After Deploy Command With Travis CI and Django Postgres "Could Not Connect To Server"
In my Travis.yaml, I specify that I want to deploy to Google App Engine, and that all works without a problem. After deploy, I specify: after_deploy: - bash ./fastestfollowup/gae_deploy.sh This runs: python3 ./fastestfollowup/manage.py migrate And I get the traceback: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/cloudsql/fastest-follow-up-backend:us-central1:fastest-follow-up-backend-instance/.s.PGSQL.5432"? Other things about the situation that are relevant: I am able to run migrations when connecting to the production server via my local database I set my Travis Service accounts as: App Engine Admin App Engine Deployer Cloud Build Editor Cloud SQL Admin Storage Admin I manually kept the SQL server alive to make sure it wasn't just timing out to not effect (If you see redundant or over sharing on these accounts let me know). If I'm able to connect when I'm working locally, why am I not able to connect via Travis? Full Travis.yaml: language: python services: - postgresql python: 3.7 env: global: - secure: XLK0DRhRBBbECQUldG9LWB4Jpc6LwmRmaQBJFf9j7UCKB...... before_install: - echo $super_secret_password | gpg --batch --yes --passphrase-fd 0 fastest-follow-up-backend-ad30efeabbd5.json.gpg install: - pip install -r fastestfollowup/requirements.txt script: - python fastestfollowup/manage.py test deploy: provider: gae keyfile: "./fastest-follow-up-backend-ad30efeabbd5.json" project: fastest-follow-up-backend … -
Django url unit test comparison of expected view function fails
class TestsUrls(SimpleTestCase): def test_index_url_is_resolved(self): url = reverse('index') self.assertEquals(resolve(url).func, index) I am trying to unit test url to see if it returns the expected view. This assertion fails even though it looks like the functions are the same. I am using function based views, not class based views. Does that have something to do with it? AssertionError: <function index at 0x11db7cb70> != <function index at 0x11d860ae8> -
How to send POST/GET requests from Django Website to Spring Rest api?
I have a form in a submit.html file: {% extends 'base.html' %} {% block content %} <div class="container"> <h1>Here you submit a new job</h1> <form class = "form" method="post"> <label for="Company">Company Name:</label> <input type="text" value="{{ user.username }}" name="Company" id="Company"> <br> <label for="position">Position:</label> <input type="text" name="position" placeholder="e.g Web Developer"> <br> <button type="submit">Submit</button> </form> </div> {% endblock %} I also have another project built on Java Spring, and it provides the following api : http://myhost:port/projectname/api/addposition?compName=Google&category=Developer where it actualy takes the username as the compName and the position input as category parameters. I've searched for a way but I mostly found examples for inside requests, not to other api. I'm trying to find a way to send a request to this api, using post method.This api can use either params via the url or data sent to it (like json for example) Sorry if question is not clear, it`s my first question on stack :) Any help will be appreciated. -
How to serach for books in google api
I am trying to display all the books from google api based on a passed value and then insert them into the database. I can't visualize how to pass value to the class responsible for getting response. Solution which currently I'm trying to use is dajngo forms. Below is a fragment of my code. views: class GoogleImportBook(FormView): model = Book form_class = GoogleImportForm template_name = "API/search_for_book.html" success_url = reverse_lazy("books_api") def book_search(self, value): param = {"q":value, "key":settings.API_KEY} api_url = "https://www.googleapis.com/books/v1/volumes" response = requests.get(url=api_url, params=param) items = response.json()["items"]["volumeInfo"] for item in items: print(item["title"]) forms.py class GoogleImportForm(forms.ModelForm): q = forms.CharField() class Meta: model = Book fields=["q"] I assume than using regular django forms is not a good practice for worki with REST in django. -
ImportError: No module named django.core.wsgi - Ubuntu 18.04
[2020-02-14 16:15:21 +0000] [17066] [INFO] Listening at: http://0.0.0.0:5000 (17066) [2020-02-14 16:15:21 +0000] [17066] [INFO] Using worker: sync [2020-02-14 16:15:21 +0000] [17070] [INFO] Booting worker with pid: 17070 [2020-02-14 16:15:21 +0000] [17070] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 377, in import_app __import__(module) File "/home/ubuntu/client_portal/client_portal/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi [2020-02-14 16:15:21 +0000] [17070] [INFO] Worker exiting (pid: 17070) [2020-02-14 16:15:21 +0000] [17066] [INFO] Shutting down: Master [2020-02-14 16:15:21 +0000] [17066] [INFO] Reason: Worker failed to boot. I've tried everything pip3 install gunicorn I'm able to run it on the virtual machine but not on the Ubuntu 18.04 server. The wsgi code is also accurate and I'm running the same code in another server Ubuntu 16.04 as well it works there but it is failing here. -
Django/Python page does not update with changed information
I am self taught, so excuse any newbie statements; I am figuring out Python by internet searches, books for dummies and this great site. I am building a chess to prove out a concept. I am writing it out in Python 3.6.9 and Django. The user makes a move and the posted information is updated to a table on Sqllite3 that details what piece is in which square. I then redraw the chess board in simple divs to display a chessboard based on the table and use a HttpResponse to push it out to webpage (not using a form and it goes out directly from the related view.py; no Ajax, Javascript or any plug ins). The background updates to the Sqllite3 tables and logic generally work (I have one lookup issue) but the updates do not make it to the webpage. It used to but I had tweaked it with a variety of updates that should have nothing to do with a how the page refreshes. Clicking page retrieval button, clearing the cache (Firefox browser) or closing/reopening the browser does not mean I will get an updated chessboard even though I can see the tables are properly updated in Sqllite. … -
Is there a Django module that models postal addresses (and is also compatible with Django 2.0+)?
I'm using Django 2.0 and Python 3.7. I would like to create an address model (but not necessarily specific to US addresses). This would have at the minimum street postal code city state/province country Before I roll my own, I thought there may already be something out there. However the only thing I can find -- https://pypi.org/project/django-address/ , is not compatible with the version of Django I'm using. Is there another Django module that provides functionality to model an address in a Django model I create that is also compatible with later versions of Django? -
Django Saving and loading messages
i am making chat app using django, and i follow the tutorial in youtube and documentation and i follow everything they say, but i still get the error chat/ __init__.py consumers.py routing.py templates/ urls.py views.py This is my code in consumers.py this is the script in my room.html, i already have script in ReconnectingWebSocket.js <script> var roomName = {{ room_name_json }}; var username = {{ username }}; var chatSocket = new ReconnectingWebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; var author = message['author']; var msgListTag = document.createElement('li'); var pTag = document.createElement('p'); pTag.textContent = message.content; if (author === username){ msgListTag.className='sent'; } else{ msgListTag.className = 'replies'; } msgListTag.appendChild(pTag); document.querySelector('#chat-log').appendChild(msgListTag); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { var messageInputDom = document.getElementById('#chat-message-input'); var message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'command': 'new_message', 'message': message, 'from': username })); messageInputDom.value = ''; }; </script> class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Message.last_10_messages() content = { 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): author = data['from'] author_user =User.objects.filter(username=author)[0] message = Message.objects.create( author=author_user, content=data['message'] ) … -
Django - Fetching data works on Shell but returns " object is not iterable" on debug
I'm new to Django, and I'm trying to fetch data from different tables with ForeignKeys. I have a model Clients and other Trip. Trip has a ForeignKey to Clients. I wanna fetch the Trips to each Client, and output on an HTML page. When I run ls = Clients.objects.get(nif=123123123) and then ts = Trip.objects.filter(client = ls) I am able to retrieve the data I want from the Trip model. But when I try doing so on django, I get a Exception Value: 'Clients' object is not iterable. This is my models.py: class Clients(models.Model): first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome") last_name = models.CharField(max_length=30, verbose_name="Apelido") address = models.CharField(max_length=200, verbose_name="Morada") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) class Trip(models.Model): trip_id = models.CharField(max_length=20, null=True, verbose_name="Ref. Viagem") client = models.ForeignKey(Clients, null=True, on_delete=models.SET_NULL, verbose_name="Cliente") out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida") hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel") in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso") This is my views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Clients, Hotels, Trip def client(request, nif): ls= Clients.objects.get(nif=nif) ts= Trip.objects.filter(client = ls) context = {'ls': ls, 'ts' : ts} return render(request, "backend/client.html", context) This is my urls.py: from django.urls import path … -
How to update datetime in graphene-django
import the libraries import graphene from graphene_django.types import DjangoObjectType from .models import Proyecto, TipoProyecto from applications.tipoproyecto.schema import TipoProyectoInput Input Graphen call the model and input values class ProyectoType(DjangoObjectType): class Meta: model = Proyecto class ProyectoInput(graphene.InputObjectType): idProyecto = graphene.ID() tipoProyecto = graphene.Field(TipoProyectoInput) codigooc = graphene.String() nombre = graphene.String() descripcion = graphene.String() fechainicio = graphene.types.datetime.DateTime() fechafin = graphene.types.datetime.DateTime() fechacreacion = graphene.types.datetime.DateTime() fechamodificado = graphene.types.datetime.DateTime() Create project create a new project class CreateProyecto(graphene.Mutation): class Arguments: input = ProyectoInput(required=True) ok = graphene.Boolean() proyecto = graphene.Field(ProyectoType) @staticmethod def mutate(root,info,input=None): ok = True tipoProyecto = TipoProyecto.objects.get(pk=input.tipoProyecto.idTipoProyecto) if tipoProyecto is None: return CreateProyecto(ok=False, proyecto=None) proyectoInstance = Proyecto( tipoProyecto=tipoProyecto, codigooc=input.codigooc, nombre=input.nombre, descripcion=input.descripcion, fechainicio=input.fechainicio, fechafin=input.fechafin, fechacreacion=input.fechacreacion, fechamodificado=input.fechamodificado, ) proyectoInstance.save() return CreateProyecto(ok=ok, proyecto=proyectoInstance) My error in the update is dont't save the datetimefield I don't save the dates in proyectoInstance because graphene expected a string or object-type class UpdateProyecto(graphene.Mutation): class Arguments: idProyecto = graphene.Int(required=True) input = ProyectoInput(required=True) ok = graphene.Boolean() proyecto = graphene.Field(ProyectoType) @staticmethod def mutate(root, info,idProyecto, input): ok = True proyectoInstance = Proyecto.objects.get(pk=idProyecto) if proyectoInstance: ok = True tipoProyectoInstance = TipoProyecto.objects.get(pk=input.tipoProyecto.idTipoProyecto) if tipoProyectoInstance is None: return UpdateProyecto(ok=False, proyecto=None) proyectoInstance.codigooc = input.codigooc if input.codigooc else proyectoInstance.codigooc, proyectoInstance.nombre = input.nombre if input.nombre else proyectoInstance.nombre, proyectoInstance.descripcion = input.descripcion if input.descripcion else proyectoInstance.descripcion, … -
ValueError at /admin/marketing/marketingpreference/add/, too many values to unpack (expected 2)
I'm try to my User model email in Marketing app. I was following the marketing app tutorial from video. but in that video that program doesn't show error. when i was write same program it's show error: ValueError at /admin/marketing/marketingpreference/add/ too many values to unpack (expected 2) from django.db import models from django.db.models.signals import post_save, pre_save from .utils import Mailchimp from accounts.models import User class MarketingPreference(models.Model): user =models.OneToOneField(User, on_delete=models.CASCADE) subscribed = models.BooleanField(default=True) mailchimp_subscribed = models.NullBooleanField(blank=True) mailchimp_msg= models.TextField(null=True, blank=True) timestamp =models.DateTimeField(auto_now_add=True) update =models.DateTimeField(auto_now= True) def __str__(self): return self.user.email def marketing_pref_update_receiver(sender, instance, *args, **kwargs): if instance.subscribed != instance.mailchimp_subscribed: if instance.subscribed: status_code, response_data = Mailchimp().unsubscribe(instance.user.email) else: status_code, response_data = Mailchimp().subscribe(instance.user.email) if response_data['status'] == 'subscribed' : instance.subscribed = True instance.mailchimp_subscribed = True instance.mailchimp_msg = response_data else: instance.subscribed = False instance.mailchimp_subscribed = False instance.mailchimp_msg = response_data pre_save.connect(marketing_pref_update_receiver, sender=MarketingPreference) def make_marketing_pref_receiver(sender, instance, created, *args, **kwargs): if created: MarketingPreference.objects.get_or_create(user=instance) post_save.connect(make_marketing_pref_receiver, sender=User) and my utils.py class Mailchimp(object): def __init__(self): super(Mailchimp, self).__init__() self.key = MAILCHIMP_API_KEY self.api_url = "https://{dc}.api.mailchimp.com/3.0".format(dc=MAILCHIMP_DATA_CENTER) self.list_id = MAILCHIMP_EMAIL_LIST_ID self.list_endpoint = '{api_url}/lists/{list_id}'.format(api_url=self.api_url, list_id=self.list_id) def get_member_endpoint(self): return self.list_endpoint + "/members" def check_valid_status(self, status): choices = ['subscribed','unsubscribed','cleaned', 'pending'] if status not in choices: raise ValueError("Not a valid choice for email status") return status def add_email(self, email,status = "subscribed"): self.check_valid_status(status) … -
Updating only part of an HTML page using Django
I have an HTML (annotator.html) page where the top half contains a table. I have JavaScript code that pulls data out of the data model when the user selects a row in the table and displays that data in a div below the table. My Javascript looks like this: $('#radiological tbody').on( 'click', 'tr', function () { if ( $(this).hasClass('selected') ) { $(this).removeClass('selected'); } else { //first unselect any other selected row dt_table.$('tr.selected').removeClass('selected'); //then select row of interest $(this).addClass('selected'); var rowIndex = dt_table.row('.selected')[0]; var row = dt_table.rows(rowIndex); var id = row.data()[0]['id']; var url = '/report/' + id + '/'; window.location = url; And correctly populates the bottom half of my page but also updates the top half. I Just want the bottom half refreshed. My report view looks like this: def report_page(request, id): template_name = "annotator.html" data = Radiology2.objects.get(id=id) context = {"data": data} context["title"] = title context["version"] = version context["id"] = id return render(request, template_name, context) It seems like using AJAX is the way to go I just can't figure out how to implement it. -
no such table: wagtailcore_site
I'm hosting two websites on ubuntu server and both having postgresql, the first one is working prefect but the second give me this error no such table: wagtailcore_site Request Method: GET Django Version: 2.2.10 Exception Type: OperationalError Exception Value: no such table: wagtailcore_site Exception Location: /home/project2/.venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /home/project2/.venv/bin/python3.7m Python Version: 3.7.3 database settings for first website: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'project_one', 'USER': 'project_one', 'PASSWORD': '123', 'HOST': '127.0.0.1', 'PORT': '', } } database settings for second website: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'project_two', 'USER': 'project_two', 'PASSWORD': '123', 'HOST': '127.0.0.1', 'PORT': '', } } from the error it seems that django try to run sqllite instead of postgresql, I dont know why ! Notes: python manage.py migrate command working without any problem whith the second database. SQL lite is working, the problem only with postgresql in the second project. I'm using nginx and gunicorn. I think the problem maybe with the HOST and PORT settings in both settings maybe they conflicting each other? ( I try change the port and host also but didn't solve it) thanks. -
Django PasswordResetView - Where to find the code that actually sends the email?
So, I am looking at the Django PasswordResetView because I am trying to debug an issue with some emails not arriving. https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.views.PasswordResetView All I see in the view is this: class PasswordResetView(PasswordContextMixin, FormView): email_template_name = 'registration/password_reset_email.html' extra_email_context = None form_class = PasswordResetForm from_email = None html_email_template_name = None subject_template_name = 'registration/password_reset_subject.txt' success_url = reverse_lazy('password_reset_done') template_name = 'registration/password_reset_form.html' title = _('Password reset') token_generator = default_token_generator @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { 'use_https': self.request.is_secure(), 'token_generator': self.token_generator, 'from_email': self.from_email, 'email_template_name': self.email_template_name, 'subject_template_name': self.subject_template_name, 'request': self.request, 'html_email_template_name': self.html_email_template_name, 'extra_email_context': self.extra_email_context, } form.save(**opts) return super().form_valid(form) Where is the actual code that sends the email? -
Django - 'WSGIRequest' object has no attribute 'post'
I'm trying to implement a likes functionality in a posts application (similar to Instagram posts), but when I submit the form for the like button, I keep getting this error saying that 'WSGIRequest' object has no attribute 'post'. The view code is as follows: @login_required def like_view(request, post_id): if request.method == 'POST': post = get_object_or_404(Post, id=post_id) obj = '' try: obj = Like.objects.get(user=request.user, post=post) user_like = Like() user_like.user = request.user user_like.post = post post.likes += 1 user_like.save() post.save() context = {'post' : post, 'post_id' : post_id} return render(request, context=context) except Like.DoesNotExist: user_like = Like() user_like.user = request.user user_like.post = post post.likes += 1 user_like.save() post.save() context = {'post' : post, 'post_id' : post_id} return render(request, context=context) else: post = get_object_or_404(Post, id=post_id) context = {'post' : post, 'post_id' : post_id} return render(request, context=context) Here's the template: <div class="col-sm-12 col-md-8 col-lg-12 bg-dark text-light mb-3 p-0"> <div class="media pt-3 pl-3 bg-dark text-light"> <a href="{% url 'users:detail' post.user.username %}"> <img src="{{ post.profile.picture.url }}" alt="{{ post.user.get_full_name }}" style="height: 35px; width: 35px;" class="mr-3 rounded-circle"> </a> <div class="media-body"> <p style="margin-top: 5px;">{{ post.user.username }}</p> </div> </div> <img src="{{ post.photo.url }}" alt="{{ post.title }}" class="img-fluid mt-2"> <p class="mt-3 ml-3"> <a href="#" class="heart-icon" style="font-size: 20px;" onclick="document.getElementById('likeButton').submit()"> <i class="far fa-heart"></i> </a><a … -
Is there a built-in for "required_together" fields?
I have a model with latitude and longitude. Both are optional but, if someone specifies one of them, I want the other become required too. -
POST request not working for Django form and Django formset
I have a form, ApplyJobForm and a Formset, ApplyJobFormset. GET method works when I pass the form and the formset to a view, but for the post request the form and the formset is_valid() isn't working, after clicking submit it returns me to a view without saving. I am unable to save the form with the formset, I don't know what I'm doing wrong here. Here are my codes. models.py class Applicants(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants') experience = models.IntegerField(blank=True, null=True) cv = models.FileField(upload_to=user_directory_path) degree = models.CharField(choices=DEGREE_TYPE, blank=True, max_length=10) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.get_full_name()} Applied' class Certification(models.Model): applicant = models.ForeignKey(Applicants, on_delete=models.CASCADE, related_name='applicant_certifications') name = models.CharField(max_length=50) certification = models.FileField(upload_to=user_directory_path, blank=True) def __str__(self): return f'{self.user.get_full_name()} certificate' forms.py class ApplyJobForm(forms.ModelForm): class Meta: model = Applicants fields = ('job', 'degree', 'experience', 'cv') exclude = ('job',) labels = { 'degree': 'Degree', 'experience': 'Experience', 'cv': 'CV', } widgets = { 'degree': forms.Select(attrs={ 'class': 'form-control', } ), 'experience': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'cv': forms.FileInput( attrs={ 'class': 'form-control', } ), } ApplyFormset = modelformset_factory( Certification, fields=('name', 'certification'), extra=1, widgets={ 'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Certification name' } ), 'certification': forms.FileInput( attrs={ 'class': 'form-control', 'placeholder': 'Upload certification' } ) } … -
Request.POST.get not working for me in django, returning default value
I am trying to get input from a html form in django , python code below Second pic is my html code -
django rest framework update method
should i use is_valid() function for validating my user data in put() function in drf? because when i use it ,is_valid.errors says that model with this username and email is already exists!i can't understand the errors meaning,because i think should be something saved before i want to update serializers.py class UserCreateSerializers(ModelSerializer): class Meta: model = User fields = ('name','email','family',"username","password","profile_pic") def update(self, instance, validated_data): print("from update try") #more dry for i in validated_data.keys(): if hasattr(instance,str(i)) and str(i) !="password": setattr(instance,str(i),validated_data.get(str(i))) elif hasattr(instance,str(i)) and str(i) =="password": instance.set_password(validated_data.get('password')) setattr(instance,"username",validated_data.get('new_username')) instance.save() views.py def put(self,request): username = request.data['username'] user = User.objects.get(username = username) serialized = UserCreateSerializers(data = request.data) if serialized.is_valid(): serialized.update(user,serialized.validated_data) return Response(data ={"status":"api_user_update_ok"} , status = status.HTTP_201_CREATED) else: print(serialized.errors) return Response(data = {"status":"api_user_update_failed","error":serialized.errors.get('email')[0]},status = status.HTTP_400_BAD_REQUEST) client data with put method : name:user family:useri username:user2 password:1234 new_username:user22 email:user@gmail.com error is : {'email': [ErrorDetail(string='user with this email already exists.', code='unique')], 'username': [ErrorDetail(string='user with this username already exists.', code='unique')]} Bad Request: /api/v0/registration/signup and the server response is : { "status": "api_user_update_failed", "error": "user with this email already exists." } thanks for your help. -
Django Receives mail from multiple email
I have a 10 email address, I want whenever someone mail me to those mail in my list, it will forward this mail to my mail personal@example.com and this email not in that 10 lists. is there any way i can do with Django or python? if possible, how can I do it? -
Django -File field not showing the selected file name
When I fill out the form and select an image to use, it all works fine and it gets uploaded and saves to my model as expected but for some reason the field wont show the name of the file I am trying to use File upload field This is my forms.py, and I am using crispy forms to render my form to the template. {{forms|crispy}} I am wondering is there anyway I can make it so it does show the name of the file I have chosen class TeamCreateForm(forms.ModelForm): class Meta: model = Team fields = ['name','image','looking_for_members','interests' ] You can see in the photo that it doesn't change but it does add the image as expected, I am using crispy forms to style the form.