Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Merge two values from form.Model in defined CharField
I try to merge two values from dropdown "on the fly" to a HTML input field model.py class ProjectID(models.Model): project_id = models.CharField(max_length=120, unique=True) def __str__(self): return self.project_name class ProjectName(models.Model): project_name = models.CharField(max_length=120, unique=True) def __str__(self): return self.project_name class Project(models.Model): combine_name = models.CharField(max_length=50, unique=True) project_id = models.ForeignKey(ProjectID, related_name='p_number', on_delete=models.CASCADE) project_name = models.ForeignKey(ProjectName, related_name='p_name', on_delete=models.CASCADE) def __str__(self): return f"{self.project_id}_{self.project_name}" views.py class AddProject(generic.FormView): template_name = 'project/project-add.html' form_class = ProjectAddForm success_url = reverse_lazy('project:project-dashboard') urls.py urlpatterns = [ path('', views.dashboard, name='project-dashboard'), path('add/', views.AddProject.as_view(), name='project-add') ] forms.py: class ProjectAddForm(forms.ModelForm): class Meta: model = Project fields = ['project_id', 'project_name', 'combine_name'] project-add.html {% block main-body %} <div class="container"> <form method="post" class="form card p-3 mt-5"> {% csrf_token %} <div class="row align-items-start"> <div class="col-md-4" id="option_a"> {{ form.project_id|as_crispy_field }} </div> <div class="col-md-4" id="option_b"> {{ form.project_name|as_crispy_field }} </div> </div> <div class="row align-items-center"> <div class="col-md-8">{{ form.combine_name|as_crispy_field }}</div> </div> {% endblock main-body %} I try to merge form.project_id form.project_name if the dropdowns are selected and appears into the field form.combine_name With jquery the result failed because I guess it's not possible to handle with templatetags $('#option_a, #option_b').change(function() { var val = $('#option_a').val() + $('#option_b').val(), new_price; $("#new_option").text(val); -
How unable to run pipenv install due to python version incompatibility
I imported a python folder that came with Pipfile and Pifile.lock in it. I tried to run pipenv install in my VScode terminal window but I got a warning saying: "Warning: Python 3.9 was not found on your system... Neither 'pyenv' nor 'asdf' could be found to install Python". I was expecting pipenv install to install the application dependencies and then create a virtual environment which I can go into using pipenv shell. But all to no avail. In my machine, I have python 3.11.4. Would downgrading the version of my machine to python 3.9 solve the problem? or is there a better way to go about this? Looking forward to your assistance. Thanks -
Order management system in the ecommerce website
The problem is about the logic of the implementation of an order management system in an ecommerce website I try to implement an order management system using django in an ecommerce website can anyone help me in the implementation of the oms in the ecommerce website using stripe and paypal in the process of the payement -
The local server can't reach the statics files with app engine
Im following the Running Django on the App Engine standard environment guide but at the step where I can launch the local server using python manage.py runserver using the Google secret and proxy the local files are giving a 404 error. However, when I deploy the app it works perfectly. I ran manage.py collectstatic and I try to modify the app.yaml but it didn't work. this the structure of the project : ├── app.yaml ├── cloud-sql-proxy ├── config │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqllite3 ├── home │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── main.py ├── manage.py ├── noxfile_config.py ├── README.md ├── requirements-test.txt ├── requirements.txt ├── static │ ├── admin │ └── home ├── templates │ └── registration and the home/static/ look like this home/static └── home ├── cgv.pdf ├── css ├── font ├── img ├── js the settings.py contain : STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = "/static/" STATICFILES_DIRS = [] the static files are called like this in the … -
how to use subquery or parent query in prefetch queryset in django
Class User(models.Model): buyer = models.OnetoOne( "payments.Buyer", on_delete=models.SET_NULL, related_name="user", null=True, blank=True ) class Order(models.Model): test = models.ForeignKey("itests.Test", on_delete=models.SET_NULL, null=True, default=True, related_name="orders") buyer = models.ForeignKey( "payments.Buyer", on_delete=models.SET_NULL, related_name="orders", null=True, blank=True ) class Sessions(models.Model): test = models.ForeignKey("itests.Test", on_delete=models.SET_NULL, null=True, default=True, related_name="sessions") user = models.ForeignKey( "payments.User", on_delete=models.SET_NULL, related_name="user_sessions", null=True, blank=True ) Sessions.objects.filter(valid=True).prefetch_related('user__buyer__orders') will prefech user's buyer relation orders and Sessions.objects.valid().prefetch_related('test__orders') will fetch only test orders but i need only objects or orders which are belong to same session user and same test in single query like tss.prefetch_related(Prefetch('user__buyer__orders',queryset=Order.objects.filter(test=F('test'), buyer=F('user__buyer')))) buyer orders should be the same session test -
How to send a http response and then execute code, all inside a function?
I'm using Django and I have set a webhook for some events that I need to receive. How can i run some code after sending a response? Something like in this pseudo-code: def my_webhook(request): # doing some stuff yield HttpResponse('200') # doing some other stuff Does it make sense to use a request_finished signal to do this? In the django docs I see that when possibile it should be better to avoid signals -
Argument missing
Using: Django/Python I'm trying to delete files... it's showing this error: TypeError at /deletar_arquivo/18/ DeletarArquivoAnamnese() missing 2 required positional arguments: 'pk' and 'id_anamnese'. template: {% if arquivos_anamnese %} <section class="row width-100 d-flex ver-anamnese-info-queixa"> <main class="col-xxl-12 width-100 d-flex flex-column"> <div class="row mt-2 d-flex mt-width-100 ver-anamnese-info-queixa-perg"> {% for arquivo in arquivos_anamnese %} <div class="col-md-1"> <a class="arquivos-ver-anamnese-box" href="{{ arquivo.arquivo.url }}" target="_blank"> {% if arquivo.arquivo|is_pdf %} <img class="arquivos-ver-anamnese-pdf" src="{% static 'icons/pdf.png' %}" alt="{{ arquivo.arquivo.name }}"> {% else %} <img class="arquivos-ver-anamnese-img" src="{{ arquivo.arquivo.url }}" alt="{{ arquivo.arquivo.name }}"> {% endif %} </a> <form method="post" action="{% url 'deletar_arquivo' arquivo_id=arquivo.id %}"> {% csrf_token %} <button type="submit" class="delete-arquivo-ver-anamnese"><i class="fi fi-sr-cross-circle"></i></button> </form> </div> {% endfor %} </div> <div class="space-px"></div> <div class="space-px"></div> </main>{# col #} </section> {% endif %} views: def VerAnamnese(request, pk, id_anamnese): cliente_anamnese = get_object_or_404(Cad_Clientes, pk=pk) form_anamnese = get_object_or_404(Anamnese, id_anamnese=id_anamnese, id_paciente=cliente_anamnese) if form_anamnese.exame_sin_vitais_altura and form_anamnese.exame_sin_vitais_peso: imc = calcular_imc(peso=form_anamnese.exame_sin_vitais_peso, altura=form_anamnese.exame_sin_vitais_altura) else: imc = "" # define um valor nulo para o imc if form_anamnese.exame_sin_vitais_altura: alt = cm_m(form_anamnese.exame_sin_vitais_altura) print(alt) else: alt = "" # Recupere os objetos ArquivosAnamnese associados à instância de form_anamnese arquivos_anamnese = ArquivosAnamnese.objects.filter(Anamnese_arquivo=form_anamnese) return render(request, "base/base_ver_anamnese.html", {'cliente': cliente_anamnese, 'form': form_anamnese, 'imc': imc, 'altura': alt, 'arquivos_anamnese': arquivos_anamnese, 'id_anamnese': id_anamnese}) def DeletarArquivoAnamnese(request, arquivo_id, pk, id_anamnese): cliente_anamnese = get_object_or_404(Cad_Clientes, pk=pk) form_anamnese … -
Wagtail autogenerated slug with id
I want to create PersonPage without title field, but with fields “surname” and “name” and also I want it to generate slug (at saving) “surname-name-id” where “id” is private key (id, or page_ptr_id) from database. What should I use to solve that issue? I tried to create custom form and make class PersonPage based on that form — it helped me get rid of title, but I have no access to id -
django-import-export "Errors: line number : 1 - 'id' " - "KeyError: id"
I have a model for driving schools in Denmark. When I try to import them form and .xlsx file, I get the following error: Errors Line number: 1 - 'id' 43959328, 2023-03-20, None, Autoskolen.com ApS, Langgade 3 - 4262 Sandved, 4262, Sandved, Anpartsselskab, 855300 Køreskoler, None, None, Nej, None, None, 1 Traceback (most recent call last): File "C:\PATH\lib\site-packages\import_export\resources.py", line 713, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\PATH\lib\site-packages\import_export\resources.py", line 375, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\PATH\lib\site-packages\import_export\resources.py", line 362, in get_instance import_id_fields = [ File "C:\PATH\lib\site-packages\import_export\resources.py", line 363, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' I am using the import_export package for the import. This is how my code looks like: admin.py: from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .models import Koereskoler #Post class KoereskoleAdmin(ImportExportModelAdmin, admin.ModelAdmin): ... admin.site.register(Koereskoler, KoereskoleAdmin) models.py: from django.db import models from datetime import date from django.core.validators import RegexValidator from django.utils import timezone from django.contrib.auth.models import User def default_user(): return User.objects.get(id=1).pk class Koereskoler(models.Model): **CVR_nummer = models.IntegerField(unique=True, primary_key=True, default=00000000)** startdato = models.DateField(default=timezone.now) ophoersdato = models.CharField(max_length=255, blank=True, null=True) navn = models.CharField(max_length=255) adresse = models.CharField(max_length=255) postnr = models.IntegerField(default=0000) by = models.CharField(max_length=50, null=True) virksomhedsform_type_choices = ( ('Enkeltmandsvirksomhed', 'Enkeltmandsvirksomhed'), ('Anpartsselskab', 'Anpartsselskab'), ('Aktie', 'Aktie'), ('Interessentskab', 'Interessentskab'), ('Andelsselskab … -
Python/Django: Custom user model doesn't get saved to database when submitting a form
so I am experimenting with custom user models in Django for a school project. I created some custom fields inheriting from the AbstractUser class, wrote a custom UserManager and registered the model in the admin page, finally rendering a template from a form which extends the UserCreationForm and uses my CustomUser as a model(which all seems to work fine, all the fields are visible in the admin, also in adding and detail view). Also I can add users directly from the admin page, that is working fine. However, when I submit the form, I get redirected and get [26/Jul/2023 13:10:40] "POST /register/ HTTP/1.1" 302 0 in the terminal but the user is not saved in the database. Following you can find my files. models.py import datetime from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password, first_name, last_name, birth_date, credit_card, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, birth_date=birth_date, credit_card=credit_card) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("Superuser must have is_staff=True.")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must have is_superuser=True.")) … -
How to show value from choices in react native?
I have a react native app and I am using django for the backend. And I try to display a selected dropdown choice from the django app in the reac native app. Django backend: So I have this part of model: pet_list = models.CharField(max_length=2, choices=PetChoices.choices, default=PetChoices.EMPTY, verbose_name="Huis- en Hobbydierenlijst") description = models.TextField(max_length=1000, blank=True, null=True, verbose_name="Beschrijving") and serializer: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ['id', 'name',"sort", "sc_name", "uis", "cites", "pet_list", 'description', "feeding", "housing", "care", "literature", 'images', 'category'] def get_animal(self, obj): return obj.get_animal_display() and for react. I am using a accordion: <List.Accordion title="Hobbydierenlijst" expanded={LegislationExpanded} onPress={() => setLegislationExpanded(!LegislationExpanded)}> <Text>{item.pet_list}</Text> </List.Accordion> <List.Accordion title="Beschrijving" expanded={ReviewExpanded} onPress={() => setReviewExpanded(!ReviewExpanded)}> <Text>{item.description}</Text> </List.Accordion> And I am using the Accordion in this component: export const SubCategoryScreen = ({ route, navigation }) => { const [subCatgoryList, setSubCategoryList] = useState([]); const [isLoading, setLoading] = useState(true); const [searchAnimal, setSearchAnimal] = useState(""); //accordion const { toggle, showAccordion } = useContext(ToggleContext); const { accordionItems } = useContext(AccordionItemsContext); const handleSearch = (query) => { setSearchAnimal(query); }; const filteredData = subCatgoryList.filter((item) => item.name.toLowerCase().includes(searchAnimal.toLowerCase()) ); useEffect(() => { fetchSubCategoryData(route.params.subcategories).then((data) => { if (data.animals.length > 0) { setSubCategoryList(data.animals); setLoading(false); } else { setSubCategoryList(data.subcategories); setLoading(false); } }); }, [route]); return ( <SafeArea> {isLoading && ( <LoadingContainer> … -
I have renamed my csrftoken using django's CSRF_COOKIE_NAME, I made similar changes in front end. But X-CSRFToken is missing in req headers
I am using two django instances. Both of them are setting the same csrftoken variable, which is causing conflicts. One of the csrftoken cookie is overwritten by other csrftoken cookie. So I am getting CSRF Failed: CSRF token missing or incorrect.. -
Not always sometime getting the "Forbidden (403) CSRF verification failed. Request aborted." Error in Django web application
I have one login form in Django template as given below:- <form action="{% url 'doLogin' %}" class="form-group" method="post"> {% csrf_token %} <div class="row"> <input type="text" name="username" id="username" class="form__input" placeholder="Username" required> </div> <div class="row"> <!-- <span class="fa fa-lock"></span> --> <input type="password" name="password" id="password" class="form__input" placeholder="Password" required> </div> <div class="row"> <input type="submit" value="Submit" class="btn"> </div> </form> The view Functions are defined as given below:- def loginUser(request): return render(request, 'login_page.html') def doLogin(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: messages.error(request, 'Invalid Login Credentials!! Remember Username and Password are case sensitive!!!') return render(request, 'login_page.html') In settings.py file I have included following parameters with value given below:- ALLOWED_HOSTS = ['gyanbharatimau.co.in'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SESSION_EXPIRE_AT_BROWSER_CLOSE = True CSRF_TRUSTED_ORIGINS = ['https://gyanbharatimau.co.in'] Now its working fine in development as well as in production environment. But sometime in production environment (Not always I guess 2 or 3 times daily) login attempt is failing with following error message:- Forbidden (403) > CSRF verification failed. Request aborted. When i enabled the debug in production i am getting following details:- Help Reason given for failure: CSRF token … -
Why django cant find a photo?
i wrote in html file, django cant find a photo this is a media files structure class Recipe(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d/", default=None, verbose_name="Фото") ingredients = models.TextField(null=True, blank=True) directions = models.TextField(null=True, blank=True) def __str__(self): return self.title maybe problem in models On site i see img icom instead full image -
Django Validators not working in shell command
Django Validators not working in shell command, it works just on Django Forms and Django Admin but not in shell commands. I have this: Validator def validate_cuit(value): """ Must be exactly 11 numeric characters """ if len(value) != 11: raise CuitValidationException('CUIT should have 11 characters') if not value.isdigit(): raise CuitValidationException('CUIT should only contain numeric characters') return value Exception class CuitValidationException(ValidationError): pass Model class Empresa(models.Model): name = models.CharField(max_length=120, validators=[validate_name]) cuit = models.CharField(max_length=11, validators=[validate_cuit]) If I do this, I get no error e = Empresa.objects.create(name="Testing Case", cuit='1') The only way I found to solve this is by working on the save method: def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.name = validate_name(self.name) self.cuit = validate_cuit(self.cuit) return super().save(force_insert, force_update, using, update_fields) But I'm sure it shouldn't be neccesary, can you help me with this? -
Dynamically modifying fields in django Rest Framework
Okay so I have two classes one is Book and the other one is Category. Book and Category are linked by a foreign key named category which is a Book field. See the code class Category(models.Model): class Meta: verbose_name_plural = "Categories" category = models.CharField(max_length=20) def __str__(self): return self.category class Book(models.Model): book_title = models.CharField(max_length=20) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.book_title And below are the serializer classes class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) class CategorySerializer(DynamicFieldsModelSerializer): class Meta: model = Category # only show the category field fields = ['category'] class BookSerializer(serializers.ModelSerializer): # this will show the category data which is related to this Book category = CategorySerializer() class Meta: model = Book fields = '__all__' And now I want that when I get the data of the book using @api_view, I should … -
AWS update TLS version from tls1.1 to tls1.2 in django using SES smtp
Recently I have received an email from AWS that has identified few endpoints using AWS SES for sending mails. We have identified TLS 1.0 or TLS 1.1 connections to AWS APIs from your account that must be updated for you to maintain AWS connectivity. Please update your client software as soon as possible to use TLS 1.2 or higher to avoid an availability impact. We recommend considering the time needed to verify your changes in a staging environment before introducing them into production... Now AWS has only provided me ip address (which is my server's IP), message Id, and tls version. I have multiple projects running on that server and using the same SES to send mails. Region | Event | Message ID | Source IP | TLS Version <region-of-my-aws-account> | SMTP Message | <smtp-message-id> | <ip-address> | TLSv1 | Im still unsure which ones are using which TLS version. I want to pinpoint my project which is using TLS 1.1/1.0 Is there a way maybe I can print TLS version along in my log files while sending mail? my settings are as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = '<AWS SMTP endpoint>' EMAIL_HOST_USER = os.getenv('AWS_SES_SMTP_USERNAME') EMAIL_HOST_PASSWORD = os.getenv('AWS_SES_SMTP_PASSWORD') EMAIL_USE_TLS = … -
Language selection navbar
Below is my code that works pretty fine and it changes the language of my website, but I want the navbar to change the link 'language' to 'russian' or 'spanish' and etc everytime the user chooses the language. I mean if the user chooses english, in navbar there should be 'english', not just 'language'. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Languages </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for lang in languages %} <li> <a class="dropdown-item" href="/{{ lang.code }}/"> {{ lang.name_local }} </a> </li> {% endfor %} </ul> </li> -
Passing kwargs from Resource to widget
I've been working with django import_export and I wanted to pass kwargs from the resource to the clean field of my custom widget validator. how can i do that here's my code resources.py class UserResource(ModelResource): identifier = Field( column_name="identifier", attribute="identifier", widget=RegexWidget(), ) class Meta: model=User widgets.py class RegexWidget(CharWidget): def clean(self, value, row=None, **kwargs): regex = kwargs.get("regex", None) ... In the test I've tries something like the following UserResource.import_data(dataset, regex=r"U\{4}d\Z") but the kwargs from the clean method of the widget is {} -
EC2 instance and EC2 hosted sql is crashing
I have a copied one django project and deleted the mirgation files other than init.py and deployed that to a new EC2 instance with new url.But whenever i am performing any sql operation like insertion,updation my ec2 instance is getting crashed after sometime of getting this error.Even i couldnt open the admin page med_new/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 33, in inner wargs) med_new/venv/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection connect(**conn_params) med_new/venv/lib/python3.10/site-packages/pymysql/connections.py", line 353, in init med_new/venv/lib/python3.10/site-packages/pymysql/connections.py", line 664, in connect lError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)") After this the ec2 is crashing always.What fix i have to do for that I want the connection between the sql and ec2 to be stable -
Django model list from ManyToManyField other model
I'm looking into creating some kind of dashboard to do some easy server admin tasks online. As much as possible stored in the database, so I could configure there tasks online instead of programming them. What I'm trying to achieve in my data model is the following: I have a model for Applications: class Application(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name In my Server model I have ManyToManyField mapping to my Applications model so I could select one or more applications which run on this server: from applications.models import Application class Server(models.Model): name = models.CharField(max_length=20,blank=False, null=False) application = models.ManyToManyField(Application, blank=True, related_name='applications') ip = models.CharField(max_length=15, blank=True) dns = models.CharField(max_length=100, blank=True) To support multiple server types (web server, database), I have a Servertype model: from applications.models import Application class Servertype(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) type = models.CharField(max_length=20, blank=False, null=False) order = models.IntegerField(null=False) def __str__(self): return "%s - %s" % (self.application, self.type) class Meta: ordering = ["application", "order"] Now I want to map these last 2 together, so I could link up Server and Servertype, but limit the Servertype choices to whatever is chosen as Application in Server, and is defined for this Application in Servertype. But I'm not fully sure how … -
How to receive and send form data in Django to Javascript?
I'm trying to make Django receive data from a form, then process it and output it into JavaScript. I've tried to follow Django's tutorial on making a form and it seems to work, however when I click the submit button I simply get transfered to http://127.0.0.1:8000/your-name/. I suppose i have to do something in views but I'm not entirely sure what exactly. How do I process the data and send it to JS? HTML <form action="/your-name/" method="post"> <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ current_name }}"> <input type="submit" value="OK"> Views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import NameForm def home(request): return render(request, 'index.html') def get_name(request): # if this is a POST request we need to process the form data if request.method == "POST": # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): print("yesss") # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect("/thanks/") # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, "index.html", {"form": form}) Forms.py from django import forms class NameForm(forms.Form): … -
cookiecutter-django template django.db.utils.ProgrammingError: relation "django_celery_beat_periodictask" does not exist
I generated a django app using the cookiecutter template and got an error that celery_beat_periodictask does not exist. I ran the following docker-compose command: docker-compose -f local.yml up -d --build Checked the logs for individual services (services in the docker-compose file)your text using: docker-compose -f local.yml logs I got the following error: File "/usr/local/lib/python3.11/site-packages/psycopg/cursor.py", line 723, in execute local_celerybeat | raise ex.with_traceback(None) local_celerybeat | [2023-07-26 11:46:23,580: WARNING/SpawnProcess-1] django.db.utils.ProgrammingError: relation "django_celery_beat_periodictask" does not exist local_celerybeat | LINE 1: ...ango_celery_beat_periodictask"."description" FROM "django_ce I decided to add the dynamically generated docker IP address to the settings.local file and this error disappears. Is there anyway to fix this issue before running the docker-compose command? -
Why Django migrate command not able to create tables in database for specific app
I've a model named Attendance and it contain following migrations applied in postgresql db. attendance [X] 0001_initial [X] 0002_delete_leave [X] 0003_alter_holiday_options_alter_shift_options [X] 0004_delete_holiday_alter_shift_holidays [X] 0005_delete_shift [X] 0006_initial [X] 0007_alter_leave_options [X] 0008_alter_leave_comment_alter_leave_is_regularized [X] 0009_attendance [X] 0010_alter_attendance_options_attendance_created_at_and_more [X] 0011_attendance_status [X] 0012_attendance_is_regularized [X] 0013_alter_attendance_is_regularized [X] 0014_remove_attendance_date_attendance_start_date_and_more [X] 0015_attendance_end_date [X] 0016_alter_attendance_end_date [X] 0017_alter_attendance_end_date_and_more [X] 0018_leavetype_remove_leave_half_day_and_more [X] 0019_leave_leave_type when I run python manage.py migrate with or without app label it does not create tables in db. I've not set managed=False and tried to delete all migrations from django_migrations table but no luck. -
Why doesn't Django set the cookie when the view is called
I am trying to set and unset a Django cookie based on a form with a checkbox. When the checkbox is checked I would like the cookie to be set. Passing the value of the checkbox to the view is working correctly, but setting and unsetting the cookie is not. This is the view: def filter(request): tasks = list() if request.POST.get('today') == 'yes': tasks.extend(Task.objects(when='today')) print('get tasks today') response = render(request, 'index.html', {'tasks': tasks}) if request.POST.get('today') == 'yes': response.set_cookie('today', 'yes') print('set cookie today') else: response.set_cookie('today', 'no') print('cookie not set today') return response Whether or not to set the cookie is determined by this code: {{request.COOKIES.today}} <form action="filter" method="POST"> {% csrf_token %} <input type="checkbox" name="today" value="yes" {% if request.COOKIES.today == 'yes' %}checked{% endif %}> Today</div> <input type="submit" value="Show" class="btn btn-warning col-12 btn-sm"/> </form> In my template I use {{request.COOKIES.today}} to check the value of the cookie. What's happening is strange. If I click the checkbox the cookie is not set, as I expect it to be and the checkbox is not checked when the page reloads. But if I select the checkbox again, then the cookie is set and the checkbox is selected. Am I making a mistake somewhere, or missing something. …