Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 3rd party API Event Loop?
I'm quite new to back-end development so please forgive my ignorance. I need to connect my Django backend to a 3rd party API to fetch live location data from GPS trackers. This needs to be done server side as it triggers other events, so it can't just be run in the browser. What's the best way to go about doing this please? So far I have thought of something like an event loop which calls the API every 60 seconds, but can I run this on a separate thread for example? Is that even the best thing to do? Is it possible to do something like a websocket form my backend to the 3rd party? What's the best way of keeping this data updated? Finally, how does a solution like this scale, what if I had 5,000 vehicle trackers which all needed updating? Any advice would be greatly appreciated. Thank you. -
Can't use assertTemplateUsed with unitest.TestCase
Please help, i'm fairly new to Django and not sure what's the best way to proceed with my unit-tests. So, i have a large django app, and it has dozens of views-methods, and the postgresql schemas get pretty complex. I've read that if I use "from django.test import TestCase" then the test database is flushed after running each unit-test. I wanted to prevent from flushing the db in between unit-tests within the same class, so i started using "from unittest import TestCase". That did the trick and the db is preserved in between unit-tests, but now the statement self.assertTemplateUsed(response, 'samplepage.html') gives me errors AttributeError: 'TestViews' object has no attribute 'assertTemplateUsed'. What can I do? Is there an alternative to 'assertTemplateUsed' that can be used with unittest.TestCase? Many thanks in advance! -
How to extend an IIS request - Django
How can I extend the waiting time for e.g. downloading a file? I use ISS and tried to change the Request Timeout from 90 to 300 in FastCGI Settings, but that didn't help. If the file download request takes longer than 90 seconds, I have a 500 error. The entire site is based on python / Django. -
How to share my list to other user (Django)
Hello guys i'm a begginer in Django and i made a Shopping-list-app from wathing videos on youtube. I can make list in my app and i want to share my list to other user, but i do't know how really do that. I would be happy if someone could help me. model.py I tried to use models.ManyToManyField but i know don't what should i do in View.py to app the list from a user to other user from django.db import models from django.db import models from django.contrib.auth.models import User class Liste(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=30, verbose_name = "Titel") item1 = models.CharField(max_length=30, blank=True, verbose_name = "1") preis1 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item2 = models.CharField(max_length=30, blank=True, verbose_name = "2") preis2 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item3 = models.CharField(max_length=30, blank=True, verbose_name = "3") preis3 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item4 = models.CharField(max_length=30, blank=True, verbose_name = "4") preis4 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item5 = models.CharField(max_length=30, blank=True, verbose_name = "5") preis5 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") @property def rate(self): total = (self.preis1) + (self.preis2) + (self.preis3) + (self.preis4) … -
Django get objects that have certain ManyToMany relations
suppose we have two models like this: class User(models.Model): name = models.CharField(max_length=255) date_joined = models.DateField() class Group(models.Model): title = models.CharField(max_length=255) users = models.ManyToManyField(User) we get a queryset of users: user_qs = User.objects.filter(date_joined__range=['2022-01-01', '2022-01-05']) how can I get the list of Group objects that have all users of user_qs in their users? django==3.2 -
Filter foreign key in DetailView Django
I ran into a problem with the queryset query, I need to display certain tags for each article that are related to this article. Each article has tags associated with the article id. model.py class NewsDB(models.Model): title = models.CharField('Название',max_length=300) text = models.TextField('Текст статьи') img = models.ImageField('Фото',upload_to='News',null='Без фото') avtor = models.ForeignKey('Journalist', on_delete=models.PROTECT) date = models.DateField() def __str__(self): return self.title class Meta: verbose_name = 'News' verbose_name_plural = 'News DataBase' class Hashtags(models.Model): News=models.ForeignKey('NewsDB',on_delete=models.PROTECT) Hashtag=models.CharField('Хештег',max_length=150,null='Без темы') def __str__(self): return self.Hashtag view.py class Show_post(DetailView): model = NewsDB template_name = 'navigation/post.html' context_object_name = 'newsDB' def get_context_data(self,**kwargs): hashtags = super(Show_post,self).get_context_data(**kwargs) hashtags['hashtags_list'] = Hashtags.objects.filter(News=self.pk) return hashtags -
Extended fields in custom Django User model not appearing
I am trying to extend the default Django user model to include other fields and enable users to update this information. This is what I have in models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver #extending user model to allow users to add more profile information class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) city = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=50, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() api.py: from rest_framework import generics, permissions, mixins from rest_framework.authentication import TokenAuthentication from rest_framework.response import Response from .serializers import RegisterSerializer, UserSerializer from django.contrib.auth.models import User from rest_framework.permissions import AllowAny #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer #remove this if it doesn't work authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "message": "User Created Successfully. Now perform Login to get your token", }) and serializers.py: from django.contrib.auth.models import User from accounts.models import Profile from rest_framework import serializers #added more imports based on simpleJWT tutorial from rest_framework.permissions import IsAuthenticated from django.db import models from django.contrib.auth import authenticate from … -
May not set both `read_only` and `required` within two different serializers
First Serializer: class RecipeSerializer(serializers.ModelSerializer): step_of_recipe = RecipeStepsSerializer(many=True, required=False) ingredients = serializers.StringRelatedField(many=True, read_only=True) # <---- by_cook = serializers.StringRelatedField(read_only=True) Second Serializer: class RecipeCreateSerializer(serializers.ModelSerializer): step_of_recipe = RecipeStepsSerializer(many=True, required=True) ingredients = serializers.StringRelatedField(many=True, required=True) # <---- Traceback: web_1 | File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked web_1 | File "<frozen importlib._bootstrap>", line 688, in _load_unlocked web_1 | File "<frozen importlib._bootstrap_external>", line 883, in exec_module web_1 | File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed web_1 | File "/code/apps/recipe/urls.py", line 2, in <module> web_1 | from apps.recipe.views.recipe import RecipeView, RecipeCreateView web_1 | File "/code/apps/recipe/views/recipe.py", line 3, in <module> web_1 | from apps.recipe.serializers.recipe import RecipeSerializer, RecipeCreateSerializer web_1 | File "/code/apps/recipe/serializers/recipe.py", line 57, in <module> web_1 | class RecipeCreateSerializer(serializers.ModelSerializer): web_1 | File "/code/apps/recipe/serializers/recipe.py", line 61, in RecipeCreateSerializer web_1 | ingredients = serializers.StringRelatedField(many=True, web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/relations.py", line 123, in __new__ web_1 | return cls.many_init(*args, **kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/relations.py", line 143, in many_init web_1 | list_kwargs = {'child_relation': cls(*args, **kwargs)} web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/relations.py", line 237, in __init__ web_1 | super().__init__(**kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/relations.py", line 117, in __init__ web_1 | super().__init__(**kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/fields.py", line 336, in __init__ web_1 | assert not (read_only and required), NOT_READ_ONLY_REQUIRED web_1 | AssertionError: May not set both `read_only` and `required` As … -
Testing: Can't log in with superuser using Selenium
I have Selenium running tests and when login in with the superuser created from the shell works fine but when login in with a superuser made from test setUp it doesn't accept the credentials. Any idea why is this behavior happening? from django.test import TestCase from django.contrib.auth.models import User from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class FunctionalTestCase(TestCase): def setUp(self): self.username = 'mysuperuser' self.email = 'admintesting@gmail.com' self.password = 'mysecretpassword7' try: admin_user = User.objects.create_superuser(self.username, self.email, self.password) admin_user.save() except: print("Failed") def test_admin_can_navigate_to_courses(self): options = webdriver.ChromeOptions() options.add_argument(" - incognito") self.browser = webdriver.Chrome(executable_path='./chromedriver', options=options) self.browser.get("http://localhost:8000/accounts/login/") username_input = self.browser.find_element_by_id("id_username") password_input = self.browser.find_element_by_id("id_password") username_input.send_keys(self.username) password_input.send_keys(self.password) self.browser.find_element_by_xpath("//input[@type='submit']").click() self.browser.get('http://localhost:8000/site/me') def tearDown(self): self.browser.quit() -
Django adding colon to the path out of nowhere
I have a pretty simple Django project based on the one from the tutorial that I am slowly morphing into my own app. It was working fine locally. I tried to deploy it to Heroku, so I made a few changes, but it was still working fine locally (I am still working on getting it to work on Heroku). But then I ran it once more and out of nowhere I am getting this error: Invalid argument: 'C:\\Users\\cusack\\PycharmProjects\\pythonProject\\website\\:\\index.html' So it is adding :\\ or \\: to the path for some reason. I have looked at settings.py, views.py, urls.py, and I can't find anywhere where I have told it to do this. My urls.py file looks (partially) like this: urlpatterns = [ path('', views.index, name='index'), path('images/random.png',views.my_image,name='randomImage'), path('admin/', admin.site.urls) ] The main page and admin both give this error, but 'images/random.png' works just fine. For the admin page, it is adding the extra :\\ before admin\\index.html. My views.py for this index is trivial: def index(request): return render(request, 'index.html') It happened when I was playing around with DEBUG and ALLOWED_HISTS, although changing them back to True and [] didn't seem to help. Any idea where this could be coming from? -
Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax
I've been working on a Django project, I'm using Pycharm community edition 2021 and Django version as 4.0.3, the problem is that , whenever I reload my site there would be no pictures shown which I want to display from another website. Error would be like "Indicate whether to send a cookie in a cross-site request by specifying its Same Site attribute", I have tried much more method to resolve this adding removing cookies but unable to solve it, as I dnt know whether these same site cookies would be in IDE , Django or chrome? {% extends 'base.html'%} {% block body %} <div class="container my-4 mx-4 py-8 px-8" > <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="https://api.unsplash.com/search/photos?&client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100 " alt="..."> </div> <div class="carousel-item"> <img src="https://api.unsplash.com/search/photos?client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="https://api.unsplash.com/search/photos?client_id=wIXk0jpTFTYBNuisfNDCRmfWDt- ZDTXZhBtviWWN7U8&query=office" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs- target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs- target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> {% endblock body %} -
how to place the images in the select of my template to make the language change?
it is very very basic but my inexperience does not make me see the error. Well, the flags don't appear, but it is the folder and also the path, because I have other images that have the same path, only instead of flags it says brands <select class="selectpicker" data-width="fit"> <option><img src="{%static 'assets/images/flags/spain.jpg' %}" alt="">English</option> <option><img src="{%static 'assets/images/flags/us.jpg' %}" alt="">Español</option> </select> -
Python Django "surrogates not allowed" error on model.save() call when text includes emoji character
We are currently in the process of building a system that stores text in a PostgreSQL DB via Django. The data gets then extracted via PGSync to ElasticSearch. At the moment we have encountered the following issue in a testcase Error Message: UnicodeEncodeError: 'utf-8' codec can't encode characters in position 159-160: surrogates not allowed We identified the character that causes that issue. It is an emoji. The text itself is a mixture of Greek Characters, "English Characters" and as it seems emojis. The greek is not shown as greek, but instead in the \u form. Relevant Text that causes the issue: \u03bc\u03b5 Some English Text \ud83d\ude9b\n#SomeHashTag \ud83d\ude9b\ translates to this emoji:🚛 As it says here: https://python-list.python.narkive.com/aKjK4Jje/encoding-of-surrogate-code-points-to-utf-8 The definition of UTF-8 prohibits encoding character numbers between U+D800 and U+DFFF, which are reserved for use with the UTF-16 encoding form (as surrogate pairs) and do not directly represent characters. PostgreSQL has the following encodings: Default:UTF8 Collate:en_US.utf8 Ctype:en_US.utf8 Is this an utf8 issue? or specific to emoji? Is this a django or postgresql issue? -
django ModuleNotFoundError: No module named 'debug-toolbar'
I just tried to install the django-debug-toolbar. I believe I followed all the steps as indicated in the docs. I am using docker, so I included the following in my settings: if os.environ.get('DEBUG'): import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] After installing, I ran docker-compose build then docker-compose up -d. docker-compose logs and docker-compose exec web python manage.py collectstatic show the error ModuleNotFoundError: No module named 'debug-toolbar' The only thing I think I did differently from the docs is that I use pipenv. I exited docker-compose and then installed via pipenv install django-debug-toolbar. Debug toolbar is in my pipfile. FWIW I'm never sure if I'm supposed to exit docker-compose before install a module via pipenv (or if it matters). -
(django rest) JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError
In my django rest framework project when post data it works but when i have added validators it gives me error. here's serializers.py(with validator code) def starts_with_r(value): if value['0'].lower() != 'r': raise serializers.ValidationError('Name Should start with R') return value class StudentSerializer(serializers.Serializer): name=serializers.CharField(max_length=100, validators=[starts_with_r]) roll =serializers.IntegerField() city=serializers.CharField(max_length=100) views.py( this part to handle post request if request.method == 'POST': json_data=request.body stream=io.BytesIO(json_data) pythondata=JSONParser().parse(stream) serializer=StudentSerializer(data=pythondata) if serializer.is_valid(): serializer.save() res={'msg':'Data Created'} json_data=JSONRenderer().render(res) return HttpResponse(json_data,content_type='application/json') json_data=JSONRenderer().render(serializer.errors) and myapp.py from where i am trying to post data import requests import json URL="http://localhost:8000/studentapi/" def post_data(): data={ 'name':'rayan', 'roll':170, 'city':'Cumilla' } json_data=json.dumps(data) r= requests.post(url=URL, data=json_data) data=r.json() print(data) when i try to post data without the validators it works but when with validators it gives this error File "C:\Users\ITS\Desktop\django-rest\myapp.py", line 45, in <module> post_data() File "C:\Users\ITS\Desktop\django-rest\myapp.py", line 25, in post_data data=r.json() raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -
How to load entities with manytomany relationships in django
class Category(models.Model): name= models.CharField(max_length=50) @staticmethod def get_all_categories(): return Category.objects.all() def __str__(self): return self.name class SubCategory(models.Model): name= models.CharField(max_length=50) categories = models.ManyToManyField(Category) def __str__(self): return self.name @staticmethod def get_all_subcategories(): return SubCategory.objects.all() class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) category= models.ManyToManyField(SubCategory) def __str__(self): return self.name @staticmethod def get_products_by_id(ids): return Products.objects.filter (id__in=ids) @staticmethod def get_all_products(): return Products.objects.all() def productdetail(request,id): product1 = Products.objects.get(id = id) subcategoryname = product1.category.name categories = Category.get_all_categories() How to load a product, subcategory and category heirarchy in the view function -
Trouble with routing in django - page not found
I am not able to perform routing. error at /home: enter image description here urls.py: enter image description here views.py: enter image description here -
how to select an item multiple time in django m2m field in form
I am a beginner and learning django, here i want to let the user to select items multiple times in a m2m field, for example here i have a icecream model with flavor class linked to it in a m2m rel, when the form is displayed in the template i want user to select 1 option many times. my models: class IceCream(models.Model): hold_choice = ( ('Cone', 'Cone'), ('Cup','Cup'), ) type_name = models.ForeignKey('IceCreamType', on_delete=models.CASCADE, null=True, blank=True) flavor = models.ManyToManyField(Flavor, verbose_name='total scopes') toppings = models.ManyToManyField(Topping) holder = models.CharField(max_length=4, choices=hold_choice, default='Cone') number_of_icecreams = models.PositiveIntegerField(default=1) def __str__(self): return str(self.type_name) @property def total_scope(self): return self.flavor_set.all().count() the flavor model has some options: class Flavor(models.Model): CHOCOLATE = 'Chocolate' VANILLA = 'Vanilla' STRAWBERRY = 'Strawberry' WALLNUT = 'Wallnut' KULFA = 'Kulfa' TUTYFRUITY = 'Tuttyfruity' choices = ( (CHOCOLATE, 'chocolate scope'), (VANILLA, 'vanilla scope'), (STRAWBERRY, 'strawberry scope'), (WALLNUT, 'wallnut scope'), (KULFA, 'kulfa scope'), (TUTYFRUITY, 'tutyfruity scope'), ) flavor = models.CharField(max_length=20, choices=choices, null=True) def __str__(self): return self.flavor now if i display the form for it, how could it be possible for user to select 1 item(or scopes) many times, and also the method i've created in IceCream model doesnt work and gives the error IceCream has no attribute flavor_set. the … -
Axios call inside an axios response
I'm having issue when I try to do an axios call whithin the scope of the response const url = 'http://localhost:8000/session/'; axios.get(url).then(response => { console.log(response) const sessionEnCours = response.data.results.filter(session => session.fin_session == null).map(session => { axios.get(session.client).then(client => { session.client = `${client.prenom} ${client.nom}` }) return session }) sessionEnCours.map(session => console.log(session)) setSession(sessionEnCours) }) }, []); I have a Django API, so I have hyperlink models and get url as a foreign key. Whenever I'm trying to replace this url with the customer name with my little trick, it is not modified. Thank you for your help -
How to implement a better use of Django ORM?
I need to get a queryset where there are certain 2 users. My model: class ChatRoom(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="room_user1") user2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="room_user2") My qs: def by_users(self, user1, user2): return self.get_queryset().filter( (Q(user1=user1) | Q(user2=user1)) & (Q(user1=user2) | Q(user2=user2) ) Right now the query looks like this, is there any way to optimize it, make it optimal? -
Flask + sqlalchemy get class object from database
I'm builing Flask application using SqlAlchemy and i'd like to retrive hashed_password using db_session.query. here's my user model: import sqlalchemy from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from .db_session import SqlAlchemyBase class User(SqlAlchemyBase, UserMixin): __tablename__ = 'users' id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True) name = sqlalchemy.Column(sqlalchemy.String, nullable=True) surname = sqlalchemy.Column(sqlalchemy.String, nullable=True) age = sqlalchemy.Column(sqlalchemy.Integer, nullable=True) position = sqlalchemy.Column(sqlalchemy.String, nullable=True) speciality = sqlalchemy.Column(sqlalchemy.String, nullable=True) address = sqlalchemy.Column(sqlalchemy.String, nullable=True) email = sqlalchemy.Column(sqlalchemy.String, index=True, nullable=True) def set_password(self, password): self.hashed_password = generate_password_hash(password) def check_password(self, password): self.hashed_password = None return check_password_hash(self.hashed_password, password) you can see that here is no password coloumn but I add user.hashed_password in set_password func here is register app.route: @app.route('/register', methods=['GET', 'POST']) def reqister(): form = RegisterForm() if form.validate_on_submit(): if form.password.data != form.password_again.data: return flask.render_template('register.html', title='Регистрация', form=form, message="Пароли не совпадают") db_sess = db_session.create_session() if db_sess.query(User).filter(User.email == form.email.data).first(): return flask.render_template('register.html', title='Регистрация', form=form, message="Такой пользователь уже есть") user = User( name=form.name.data, email=form.email.data, surname=form.surname.data, age=form.age.data, position=form.position.data, speciality=form.speciality.data, address=form.address.data ) user.set_password(form.password.data) db_sess.add(user) db_sess.commit() return flask.redirect('/login') return flask.render_template('register.html', title='Регистрация', form=form) I call user.set_password at the bottom of the func and try to check password here: @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): db_sess = db_session.create_session() user = db_sess.query(User).filter(User.email == form.email.data).first() if user and … -
Using Javascript validation checks in a Django Project
I have to make a registration page in a project that uses Django as the backend framework.. In the registration page, I have to input the names, email, password and mobile... During registration, I need to validate email if its a valid format, check if the mobile number is of 10 digits and check if the password is a strong one.. I want to do it using javascript... I have written the code for the form and also the javascript function... But while running on the server I am unable to get the desired validation checks and alerts... Please help what should i do? signup.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> {% load static %} <link rel="stylesheet" href="{% static 'signup1.css'%}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Register</title> <!--Javascript form validator--> <link rel="stylesheet" href="{% static './register.js' %}"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="card"> <div class="text-center"> <h1>Signup</h1> <h6>Register yourself</h6> </div> <form style="text-align: top;" name="myForm" method="POST" action="" onsubmit="validate()" > {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label"><b>First Name</b></label> <input type="text" name="first_name"placeholder="First Name" class="form-control" id="name" required aria-describedby="emailHelp"> </div> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label"><b>Last Name</b></label> <input type="text" name="last_name"placeholder="Last Name" class="form-control" id="name" required aria-describedby="emailHelp"> </div> … -
Formset with request.post not initializing correctly
I am having an issue using formsets and request.POST. Whenever I initialize the formset without request.POST it works as intended, but will not send the data through as the form is never valid. If I include request.POST (as I have done on all my other forms in the view) the formset doesn't seem to initialize correctly. No data gets through, I can't see any form fields, and I get a html warning saying: (Hidden field TOTAL_FORMS) This field is required. (Hidden field INITIAL_FORMS) This field is required. Here is a very simplified version of what I am doing in my project. This is bare minimum and the project itself is much more involved. But this should be the heart of the problem I am having. The intent of this very basic form is that my formset would have 3 forms, each one initialized with a letter, 'a', then 'b', then 'c'. views.py def MyView(request): my_formset = formset_factory(my_form) my_list = ['a', 'b', 'c'] if request.method == 'POST': my_formset = formset(request.POST, initial=[{'field1':x} for x in my_list]) #If I remove 'request.POST' then the form initializes correctly, but will never pass .is_valid() if my_formset.is_valid(): print('valid') else: print('invalid') else: my_formset = formset(initial=[{'field1':x} for x in … -
python manage.py runserver in cmd
(hafi) C:\Users\User\Desktop\hafi>python manage.py runserver C:\Users\User\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\Users\User\Desktop\hafi\manage.py': [Errno 2] No such file or directory -
Does python web frameworks like Flask/Django have a build process?
I have recently started learning CI/CD concepts. In the tutorials, they used a react website to show the build stage. I was wondering do we have a build phase for applications developed using frameworks like Django/flask? For these applications, we generally run a single command to start the application directly from source code like: python manage.py runserver python app.py Also, in general, is to possible (and okay?) for a web application not to have a build phase? Any knowledge here would be helpful. Thanks in advance!