Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors
Background I've got a Django app that is heavily iobound, so per docs I've read, I'm trying to get gunincorn working with gevent for the best performance. Error dev1 | Patching Started dev1 | /app/Dev/wsgi.py:19: MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors, including RecursionError on Python 3.6. It may also silently lead to incorrect behaviour on Python 3.7. Please monkey-patch earlier. See https://github.com/gevent/gevent/issues/1016. Modules that had direct imports (NOT patched): ['urllib3.util (/usr/local/lib/python3.9/site-packages/urllib3/util/__init__.py)', 'urllib3.util.ssl_ (/usr/local/lib/python3.9/site-packages/urllib3/util/ssl_.py)']. dev1 | monkey.patch_all(thread=False, select=False) dev1 | Patching Done dev1 | /usr/local/lib/python3.9/site-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated dev1 | "class": algorithms.Blowfish, dev1 | /usr/local/lib/python3.9/site-packages/gunicorn/workers/ggevent.py:38: MonkeyPatchWarning: Patching more than once will result in the union of all True parameters being patched dev1 | monkey.patch_all() dev1 | /usr/local/lib/python3.9/site-packages/gunicorn/workers/ggevent.py:38: MonkeyPatchWarning: Patching more than once will result in the union of all True parameters being patched dev1 | monkey.patch_all() dev1 | /usr/local/lib/python3.9/site-packages/gunicorn/workers/ggevent.py:38: MonkeyPatchWarning: Patching more than once will result in the union of all True parameters being patched dev1 | monkey.patch_all() ... Setup wsgi.py # Needs to happen first print("Patching Started") from gevent import monkey monkey.patch_all(thread=False, select=False) # monkey.patch_all() from psycogreen.gevent import patch_psycopg patch_psycopg() print("Patching Done") import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Dev.settings') application … -
Django - Admin user only able to create data. FOREIGN KEY constraint failed for normal users
I'm creating a simple CRUD application to brush up on my Django skills (it's been a long time!) but I'm getting the below errors when I have a non-admin users create anything, either via the frontend or the sites backend: FOREIGN KEY constraint failed I'm also getting this error when I'm logged in as the admin user and try to update the user field in the Django Admin panel. The functionality itself works, as I can create activities through the frontend and backend when I'm logged in as the superuser. I've also tried deleting migrations etc.. but there doesn't seem to be any resolutions. The site itself uses Django's allauth models, but with custom models to fit the general purpose, but I'm still using the AllAuth user model as my foreign key, as the other model is a UserProfile: Below is my models.py file for the activities: class Activity(models.Model): class Meta: verbose_name_plural = 'Activities' activity_id = models.AutoField(primary_key=True) host = models.ForeignKey(User, on_delete=models.CASCADE, related_name="activity") name = models.CharField(max_length=254, null=False, blank=False) date = models.DateField() start_time =models.TimeField() end_time = models.TimeField() location = models.CharField(max_length=40, null=False, blank=False) description = models.CharField(max_length=140, null=False, blank=False) available = models.BooleanField(default=True) def __str__(self): return str(self.activity_id) With the view: def create_activity(request): if request.method == … -
Offloading extensive calculations in save method of Django custom FileField
I'm building a gallery webapp based on Django (4.1.1) and Vue. I want to also upload and display videos (not only images). For supporting formats, that don't work in a video html tag, I'm converting these formats to mp4 via pyffmpeg. For that I created a custom field for my model based on FileField. In it's save method I take the files content, convert it and save the result. This is called by the serializer through a corresponding ViewSet. This works, but the video conversion takes way too long, so that the webrequest from my Vue app (executed with axios) is running into a timeout. It is clear, that I need to offload the conversion somehow, return a corresponding response directly and save the data in the database as soon as the conversion is finished. Is this even possible? Or do I need to write a custom view apart from the ViewSet to do the calculation? Can you give me a hint on how to offload that calcuation? I only have rudimentary knowledge about things like asyncio. TL;DR: How to do extensive calculations asychronous on file data before saving them to a model with FileField and returning a response before … -
Django admin displays datetime fields inconsistently in Django admin view and in rendered tables
I have a model that is an activity object to save api JSON data for database queries. The api sends a start date (UTC) and a local start date. I am experiencing an inconsistent treatment of the UTC time value and the local time value. Model class ActivityObject(models.Model): name = models.CharField(max_length=50) distance = models.DecimalField(max_digits=8, decimal_places=2) moving_time = models.DurationField() elapsed_time = models.DurationField() total_elevation_gain = models.DecimalField(max_digits=5, decimal_places=2) type = models.CharField(max_length=15) start_date = models.DateTimeField() start_date_local = models.DateTimeField() average_speed = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) max_speed = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) average_cadence = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) has_heartrate = models.BooleanField(blank=True, null=True) average_heartrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) max_heartrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) activity_logged_time = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return 'id %s----name %s----start date %s----start date local %s----logged date %s' % (self.id, self.name, self.start_date, self.start_date_local, self.activity_logged_time) The unexpected behavior is that the field values inside the object are reversed. I get the values from API and convert the JSON to datetime objects. start_date = a_row['start_date'] start_date_pretty = convert_json_to_datetime(start_date) print('start date ', start_date_pretty) start_date_local = a_row['start_date_local'] start_date_local_pretty = convert_json_to_datetime(start_date_local) print('start date local ', start_date_local_pretty) Relevant JSON key and values: "start_date": "2022-11-04T21:01:20Z", "start_date_local": "2022-11-05T08:01:20Z", I have USE_TZ = True -
Django migrations dont work. Have to delete the db and start fresh eveery time
I have a django project which works fine. However, each time there is a change in my models (when I add attributes to my model), the migrations stop working. There is usually some sort of error or the migrations will not execute. The only way for me to make the migrations to work is to drop the database and start fresh. This is a very strange behavior and cannot work in a live/production environment. I recently had to delete the db in the production environment and it was very messy. Is there a way to fix this ? Isnt this strange that Django makes it harder to work with migrations when it claims that migrations make everything easy. Am I doing something wrong ? I dont know where to start from. -
How can I create an API index using multiple DRF routers?
I'm trying to build an API using DRF with the following structure (example): api/ ├── v1/ │ ├── foo/ │ │ ├── bar/ │ │ │ └── urls.py # There's one `rest_framework.routers.DefaultRouter` here │ │ ├── bar2/ │ │ │ └── urls.py # There's one `rest_framework.routers.DefaultRouter` here │ │ ├── __init__.py │ │ └── urls.py │ ├── foo2/ │ │ ├── bar3/ │ │ │ └── urls.py # There's one `rest_framework.routers.DefaultRouter` here │ │ ├── bar4/ │ │ │ └── urls.py # There's one `rest_framework.routers.DefaultRouter` here │ │ ├── __init__.py │ │ └── urls.py │ ├── __init__.py │ └── urls.py ├── __init__.py └── urls.py Intuitively, my endpoints would be https://api.example.com/v1/foo/bar/... https://api.example.com/v1/foo/bar2/... https://api.example.com/v1/foo2/bar3/... https://api.example.com/v1/foo2/bar4/... But I want that Api Root web page to be available from the https://api.example.com/v1 level. For example, when I ran curl https://api.example.com/v1 it would show me {"foo":"https://api.example.com/v1/foo/","foo2":"https://api.example.com/v1/foo2/"} and so on. That being said, I guess that the way to do it was to somehow "merge" those DefaultRouters. I'm aware that I could just router.registry.extend(some_other_router.registry), but that would make it all be at the same level and I explicitly needed it to be multi-level, as shown above. -
Having Trouble Adding Pagination In Class Views ( get_queryset )
Good day everyone, I'm trying to build a product category with pagination using class view (get_queryset). I followed a tutorial that did not actually cover this part that has get_queryset. I find it easier without get_queryset. PLEASE I urgently need help. Below is the class base views (views.py) class CatListView(ListView): template_name = 'category.html' context_object_name = 'catlist' paginate_by 12 def get_queryset(self): content = { 'cat': self.kwargs['category'], 'posts': Post.objects.filter(category__name=self.kwargs['category']).filter(status='published') } return content Template.html <nav aria-label="Page navigation example"> {% if is_paginated %} <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item" style="color:#000;"> <a class="page-link" href="?page={{page_obj.previous_page_number}}" style="color:#000; background:#98FB98;" >Previous</a> </li> {% else %} <li class="page-item disabled" style="color:#000;"> <a class="page-link" href="#" style="background:#E5E4E2;">Previous</a> </li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="page-item" style="color:#000;"> <a class="page-link active" style="background:#FF5E0E; color:#fff;">{{ i }}</a></li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item" style="color:#000;"> <a href="?page={{page_obj.next_page_number}}" class="page-link" style="color:#000; background:#98FB98;" >Next</a> </li> {% else %} <li class="page-item disabled" style="color:#000;"> <a class="page-link" style="background:#E5E4E2;">Next</a> </li> {% endif %} </ul> {% endif %} </nav> Kindly help me implement paginator. I appreciate your time and effort. Thanks a lot -
How to access contents of a SimpleArrayField in Python Django
I am currently working with a form class in Django. I need to be able to access data contained in a SimpleArrayField. class SignUps(forms.Form) people = SimpleArrayField(forms.EmailField(), label="name") Let's say a user fills out the form with the names "John Smith," "Jane Smith", "Mike Smith". I need to be able to access the names. I've tried various methods such as print(people["name"]) or print(people[0]) But I keep getting the error TypeError: 'SimpleArrayField' object is not subscriptable. I've tried to figure out to access fields from a SimpleArrayObject, but I don't see any examples in documentation. How would I go about getting the names from the people object? Is that even possible to do? -
How to add more fields and remove or change the text from django UserCreationForm?
Im building an django web page for a personal proyect with basic login/signUp system. My problem is that i want to add more input fields like name and lastname ando aslo modify the default text, basically to change it to another language. Thx for the help. :c I tried to create an CustomField but didn't work -
Add Javascript string variable INSIDE a django template variable
I have a chart that is populated by django template variables. I have an update chart function that updates the data after certain buttons are clicked. Instead of writing the same js function 7x, can I update the javascript function to call the correct data within a Django template variable? Basically, the btn_id will either be A, B, C, D, E, or F and I want the django template variable to display the correct data based on the btn_id value. var results = {{ all_test_results.A.curve_series.curve_series }}.map(function(val, i) { return val === 'None' ? null : val; }); becomes const btn_id = this.id.slice(-1); # A, B, C, D, etc var results = {{ all_test_results.{{ btn_id }}.curve_series.curve_series }}.map(function(val, i) { return val === 'None' ? null : val; }); I am sure there is a simple way to inject a js string into a Django template variable, right? -
In Django when i passed a query to insert a row, in Oracle Db the row is being inserted twice in the table
@api_view(['PUT']) def updateRule1(request, id): nums15 = 'OK' json_data = json.loads(request.body) # print(json_data) con = None cur = None try: con = cx_Oracle.connect('<server connection details>') cur = con.cursor() except cx_Oracle.DatabaseError as e: print("Problem establishing connection with Oracle DB", e) q = "INSERT INTO XXMSE.RE_PREDICATE (RULE_ID, PREDICATE_ID, INPUT_VALUE_ID1, MATHEMATICAL_VALUE, INPUT_VALUE_ID2, BOOLEAN_OPERATOR) VALUES ('1','2','2000000','equals','30000000','None')" print(q) sql5 = cur.execute(q) cur.execute(sql5) con.commit() if cur: cur.close() if con: con.close() return Response(nums15) DB screenshot 1 1 1 equals 2 AND 1 2 2000000 equals 30000000 None 1 2 2000000 equals 30000000 None I see that there are 2 rows inserted into the DB. Django version is 4.1.1 What would be the reason for duplicate rows? Appreciate your help I used breakpoint() and made sure that api is called getting once.There is no duplicate entries in the backend. -
How to create multiple filters in Django?
I want to create multiple filters in Django. The screen shot below explains it. The user may opt not to select some criteria. If the user does not select Available from, Available till and Advance then I will get the value as None in views.py. If he does not select Category or Capacity then I will get an empty list otherwise I will get a list of Category or Capacity. The problem arises when there is None or empty list. Although I have written the code and it works fine but I want to know if there is a better way to do it? My code may have problems if the complexity increases. forms.py class RoomForm(forms.Form): ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=ROOM_CATEGORIES, ) ROOM_CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=ROOM_CAPACITY, ) class TimeInput(forms.TimeInput): input_type = 'time' default=datetime.time() available_from = forms.TimeField( required=False, widget=TimeInput(), ) available_till = forms.TimeField( required=False, widget=TimeInput(), ) advance = forms.IntegerField( required=False, ) """Function to ensure that booking is done for future and check out is after check in""" def clean(self): cleaned_data = super().clean() … -
TypeError: Expected a job store instance or a string, got NoneType instead
Why I am getting this error?? I am trying to apscheduler in my django project. But the function is working very well. After sending some email it turns off automatically. here is my code : import logging from django.conf import settings from apscheduler.schedulers.blocking import BlockingScheduler from django.core.management.base import BaseCommand from django.core.mail import send_mail from django.core.mail import EmailMessage from ...models import * from django_apscheduler.jobstores import DjangoJobStore from apscheduler.triggers.cron import CronTrigger logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Running in the dark :)" def send_email_to_registered_users(self): assessment = Assessment.objects.all() mail_subject = "Newsletter" message = "Welcome to our newsletter" for i in assessment: sender = i.email email_send = EmailMessage(mail_subject, message, to=[sender]) email_send.send() print("email Sent") def handle(self, *args, **kwargs): scheduler = BlockingScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "d") scheduler.add_jobstore( self.send_email_to_registered_users(), trigger=CronTrigger(second="*/10"), id="send_email_to_registered_users", max_instances=10, ) logger.info("Printing Jobs!!! and sending!!") scheduler.start() -
Django Reversion - Viewing incompatible version data
Is there a way to view incompatible version data using Django-Reversion or after making a change to the model? I understand I wouldn't be able to revert or reinstate a previous version before the model change, but is there a way to simply view the data? Here's the model before the change: class Product(models.Model): product_code = models.CharField(max_length=120, blank=True, null=True) #max_length=required related_category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, blank = True, null=True) Then I added a 'discount' field: class Product(models.Model): product_code = models.CharField(max_length=120, blank=True, null=True) #max_length=required related_category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, blank = True, null=True) discount = models.BooleanField() when I try to access previous versions, I see an error - "Could not save XXXXX version - missing dependency." I tried accessing previous versions via admin site and also by calling Version.objects.get_for_model(Product). I was expecting to be able to view the historical versions, but instead I get an error (missing dependency). -
How to setup VueJs vite version (not Vue CLI) with Django
I have seen many people set up Vue with django using the Vue CLI, it is now deprecated. I tried to set it up with the new Vue way 'npm init vue@latest' that uses Vite, but wasnt successfull. I have been using the Vue CDN but it lacks the components stuff -
Django how to use annotate with ManyToManyfield?
I want to take two fields from my model, one is a float, and the other is a ManyToMany and do an arithmetic operation on them and add them in a field with annotate At one point it worked for me and then it didn't. I don't know what would be the correct way I show some things from my files. models.py from django.db.models import F, DecimalField class Tax(models.Model): name = models.CharField(max_length=50) porcent = models.IntegerField() def __str__(self): return self.name class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) code_number = models.IntegerField(verbose_name='Bar Code') image = models.ImageField(upload_to='products/') purchase_price = models.DecimalField(max_digits=10, decimal_places=2) sale_price= models.DecimalField(max_digits=10, decimal_places=2) tax = models.ManyToManyField(Tax, blank=True, related_name="tax") description = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views.py from django.shortcuts import render from .models import Tax, Product, Invoice from django.db.models import F, DecimalField class InvoiceDashboard(View): def get(self, request, *args, **kwargs): products=Product.objects.all().annotate(amount_tax = ((F('sale_price') / 100) * F('tax__porcent'))).annotate( price_total=(F('sale_price') + F('amount_tax')) ) context = { 'products': products, } return render(request, 'pos/cashier.html', context) pos/cashier.html {% extends 'pos/base.html' %} {% block content %} <tbody id="table_p"> {% for product in products %} <tr class="productO" id="{{ product.id }}" data-id="{{ product.id }}" data-saleprice="{{ product.sale_price … -
How to "force" the sharing the model instances between objects in django, when using prefetch_related()?
My question is: How to "force" the model instances to be shared? From output example below, Line 3 and Line 5 have Person(2) with different object instance ids. This means, there are 2 model instances of the same object, referenced from 2 different locations I would like to have them pointing to the exact same object instance. This way, there would be only 1 model instance of each object, referenced from multiple different locations Also, when a field is updated (for example, p2.name = 'p_two'), I would like to have it "visible" either by accessing the Person2 through any of Group12 or Group23, without the need to save and fetch data again. No need to save the model's state into database at this point. Documentation says: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#:~:text=One%20difference%20to,and%20CPU%20time. Example of: models.py class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return f'<{hex(id(self))} P({self.pk}) {self.name}>' class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(to=Person, through='Membership') def __str__(self): return f'<{hex(id(self))} G({self.pk}) {self.name}>' class Membership(models.Model): person = models.ForeignKey(to=Person, on_delete=models.CASCADE) group = models.ForeignKey(to=Group, on_delete=models.CASCADE) member_nickname = models.CharField(max_length=128) def __str__(self): return f'<{hex(id(self))} M({self.pk}) of {self.person} in {self.group}>' Example of tests.py class MyTests(TestCase): def test_object_ids(self): p1 = Person.objects.create(name='person1') p2 = Person.objects.create(name='person2') p3 = Person.objects.create(name='person3') g12 = Group.objects.create(name='group1') g23 = Group.objects.create(name='group2') … -
Django add multiple forms with dynamic fields and foreign key constraint to one page
I am new to Django and are currently struggling with the following problem: I have a database model consisting of the following: ` class monitor(models.Model): imap_address = models.CharField(max_length=200) imap_email = models.CharField(max_length=200) imap_password = models.CharField(max_length=200) smtp_address = models.CharField(max_length=200) smtp_email = models.CharField(max_length=200) smtp_password = models.CharField(max_length=200) receiver_email = models.CharField(max_length=200) def __str__(self) -> str: return self.imap_email class Email_filter(models.Model): mail = models.ForeignKey(monitor, on_delete=models.CASCADE) filter = models.CharField(max_length=200) def __str__(self) -> str: return self.filter class Subject_filter(models.Model): mail = models.ForeignKey(monitor, on_delete=models.CASCADE) filter = models.CharField(max_length=200) def __str__(self) -> str: return self.filter class Body_filter(models.Model): mail = models.ForeignKey(monitor, on_delete=models.CASCADE) filter = models.CharField(max_length=200) def __str__(self) -> str: return self.filter class Attachment_filter(models.Model): mail = models.ForeignKey(monitor, on_delete=models.CASCADE) filter = models.BooleanField() def __str__(self) -> str: return self.filter ` So I have one main model monitor and each monitor can have any numbers of filters. Now, I would like to create a page to modify the database with multiple forms. One form for each of the monitor objects in the database (and one empty form to add a new one). For each form, I would like to edit the single fields of the monitor, as well as dynamically add any number of filters. I am now looking around all day but did not really find anything. … -
Can I combine two querysets when one has a rank annotation and the other doesn't?
I am trying to write a search feature and can't figure out how to combine the results of a rank-annotated search and a non-rank-annotated search. Let's say I have the following model: class Song(models.Model): filename=models.CharField(max_length=120, db_index=True) title=models.CharField(max_length=120, db_index=True) title_vector=SearchVectorField(null=True, blank=True) I would like to let the user enter a single search term and search both title and filename. So if a user enters "space" as a search term, it should search for any song that has space in the title or filename. The query on the title vector looks like this. The idea is to order the results by rank so I can put the most relevant search results at the top. title_query_results = Song.objects.annotate( rank=SearchRank(F('title_vector'), query) ).filter( title_vector=query ) However, the filename query looks like this: file_query_results = Song.objects.filter( filename__icontains=query ) Because the file query results do not contain the rank annotation, I can't do a union on the results, because they have a different number of columns. Is there a way to get rank annotation for a query on the filename column? If not, what are my options for doing a union on the search results? For example, if I just wanted all the filename results to appear … -
how configured for Tk python 3.10.7
i have the next error, i try deploy project of the webservices with django rest framework. The message error is that Python not be configured fot tk. This deploy is in render.com any ideas? File "/opt/render/project/python/Python-3.10.7/lib/python3.10/turtle.py", line 107, in import tkinter as TK File "/opt/render/project/python/Python-3.10.7/lib/python3.10/tkinter/init.py", line 37, in import _tkinter # If this fails your Python may not be configured for Tk ModuleNotFoundError: No module named '_tkinter' -
How to importing database from csv file in django?
In my webapp I need put a page where the user can create a database from a csv fileupload. I try do this using a def how done in here https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/, but, dont work. I guess the models is working sucessfully, because the others forms. forms.py class FileFieldForm(ModelForm): title = forms.CharField(max_length=50) file = forms.FileField() class Meta: model = Colecao fields = '__all__' views.py class ColecaoCSVCreate(CreateView): login_url = reverse_lazy('login') form_class = FileFieldForm template_name = 'formulario/formulario_csv.html' success_url = reverse_lazy('listar_colecao') def post(self, request,*args,**kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES['sent_file'] if form.is_valid(): for f in files: reader = csv.DictReader(io.StringIO(f.read().decode('utf-8'))) data = [line for line in reader] return self.form_valid(form) else: return self.form_invalid(form) formulario_csv.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="sent_file"/> {% if request.user.is_authenticated %} <button type="submit" class="btn btn-outline-primary">Confirmar</button> {% endif %} <a href="/listar/colecao/"> <button type="button" class="btn btn-outline-danger">Cancelar</button> </a> </form> When I upload csv a guet the error MultiValueDictKeyError at /cadastrar/csv/colecao/ 'sent_file' -
I can't get the user to create session in Django using a custom login
I am doing a CRUD in Django, I am creating a custom Login class, I made a form based on AuthenticationForm, and for my view "class Login", I have an error when calling the login function and trying to assign the "user" so that django creates the session. I'm trying to get it out of the form but I get the error: 'WSGIRequest' object has no attribute 'form' I have tried to get the "user" without success #There is forms.py from django.contrib.auth.forms import AuthenticationForm class FormularioLogin(AuthenticationForm): def init(self, *args, **kwargs): super().init(*args,**kwargs) self.fields['username'].widget.attrs['class']= 'form-control' self.fields['username'].widget.attrs['placeholder']= 'Username' self.fields['password'].widget.attrs['class']= 'form-control' self.fields['password'].widget.attrs['placeholder']= 'Password' There is views.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.views.generic.edit import FormView from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.contrib.auth import login from .forms import FormularioLogin class Login(FormView): template_name = 'login.html' form_class = FormularioLogin success_url = reverse_lazy('index') @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return HttpResponseRedirect(self.get_success_url()) else: return super().dispatch(request, *args, **kwargs) def form_valid(self, form): login(self.request.form.get_user()) # --- Here is the problem --- return super().form_valid(form) -
forloop counter with htmx django
By following tutorials, I've managed to make a form which adds order items with htmx. Each new order item is a div row, not a table row. I also have a forloop counter for each row, but after a new order item is added, the counter doesn't update dynamically, only after the page refresh. The related (I think) code: order-create-update.html: {% extends 'partials/base.html' %} {% block content %} <style> .orderitem-form { border-bottom: 1px solid black; } </style> <div class="container-fluid" style="margin-top:80px"> {% include 'orders/order_form_full.html' %} <hr> <div class="row" style="margin-bottom:5px; border-bottom-style:solid; border-bottom-width:1px"> <div class="col-1" style="font-weight: bold">Item #</div> <div class="col-2" style="font-weight: bold">Material Category</div> <div class="col-2" style="font-weight: bold">Material Subcategory</div> <div class="col-4" style="font-weight: bold">Material</div> <div class="col-1" style="font-weight: bold">Quantity</div> <div class="col-1" style="font-weight: bold">Price/Unit</div> <div class="col-1" style="font-weight: bold">Action</div> </div> {% for orderitem in object.get_orderitems_children %} {% include "orders/order_item_inline.html" with object=orderitem %} {% endfor %} {% if new_orderitem_url %} <div id="orderitem-create"></div> {% endif %} <button type="button" class="btn btn-secondary" hx-get="{{ new_orderitem_url }}" hx-trigger="click" hx-target="#orderitem-create" hx-swap="beforeend">Add order item</button> </div> {% endblock %} order_item_inline.html: <div id="orderitem-{{ object.id }}"> <div class="row mt-1"> <div class="col-1">{{ forloop.counter }}</div> <div class="col-2">{{ object.material_category }}</div> <div class="col-2">{{ object.material_subcategory }}</div> <div class="col-4">{{ object.material }}</div> <div class="col-1">{{ object.quantity_ordered }}</div> <div class="col-1">{{ object.material.price }}</div> <div class="col-1"> <button type="button" class="btn btn-secondary … -
News scrapping in python
I want to get exact company name from given news article using regex in python?Can i get the code I have used this code result = re.search('\b'+company_name+'\b',string, flags=re.IGNORECASE) but this is not working for the company Local*..i am getting all the articles which contain local not local* -
How to preserve database table between tests in django?
How to preserve the database entries between tests in Django testing? python3 manage.py test tests --keepdb --keepdb preserves the database but not the table. The tables get flushed between the tests. Here is pseudo-code from django.test import TestCase class test_1(TestCase): def function_1(self): # Creates an entry in the database with file_path someModel.objects.create(file_path=file_path) class test_2(TestCase): def function_1(self): # needs the file_path to execute this function someModel.objects.get(file_path=file_path) <- this returns error since someModel does not have anything # Creates an entry in the database file_path_2 How can I preserve the database table between the tests so they can find the file path? This (talks about preserving the actual database and not the table) and this (creating a chain setUp does not work if I have 100´s tests that are chained) do not cover it.