Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
creating a delay in an html render in django?
I'm making a chatbot for practice in Django. When the user sends a message, the chatbot responds a few seconds later. I can display the text of the user and chatbot be in the template below. I'm unsure of how to create this delay. I understand that using javascript we can use the timeout() function: setTimeout(() => { console.log("World!"); }, 2000); Currently this is what I have: {% extends 'chat.html' %} {% block chatStream %} {% for item in chat %} <p> <b>user:</b> {{item.user}} <br> <b>bot:</b> {{item.bot}} <br> </p> {% endfor %} <form action="/send/" method = "post">{% csrf_token %} <input type="text" name="userMessage"> <input type="submit" value="Send to smallest_steps bot"> </form> {% endblock %} How do I create the delay between the user and bot? Thanks -
How do i make a counter that works for me on django Models
i have a question. i am trying to make some counter for my models. i have model- personeel and kwalification. i want to make a couter that counts how mutch personeel got the same kwalification like if 2 personeel got ehbo then it counts 2. def kwalificatietotaal(request): count = Kwalificaties.objects.annotate(ehbo=Count('wel')) teller = 0 if count == count: teller += 1 print(count) return render(request, 'accounts/kwalificatieTotaal.html') class Kwalificaties (models.Model): objects = None TREIN_SOORTEN = ( ('Traxx', 'Traxx'), ('Intercity Direct', 'Intercity Direct'), ('Intercity Nieuwe Generatie', 'Intercity Nieuwe Generatie'), ('Intercity Rijthuig', 'Intercity Rijthuig') ) E_H_B_O = ( ('Wel', 'Wel'), ('Niet', 'Niet'), ) EXTRA_KENNIS = ( ('Bio werkzaamheden', 'Bio werkzaamheden'), ('Kuil werkzaamheden', 'Kuil werkzaamheden'), ('Aardwind werkzaamheden', 'Aardwind werkzaamheden'), ('Airco Monteur', 'Airco Monteur'), ('Z.Z-Deuren Monteur', 'Z.Z-Deuren Monteur'), ('Vooropnamen Elektrisch', 'Vooropnamen Elektrisch'), ('Rijbevoegd Monteur', 'Rijbevoegd Monteur'), ('MTC', 'MTC'), ('EBKC', 'EBKC'), ('Heftruck kwalificatie', 'Heftruck kwalificatie'), ('Hoogwerker kwalificatie', 'Hoogwerker kwalificatie') ) naam = models.ForeignKey(Personeel, null=True, on_delete=models.SET_NULL) treinen = MultiSelectField(max_length=200, choices=TREIN_SOORTEN) ehbo = MultiSelectField(max_length=200, choices=E_H_B_O) extra = MultiSelectField(max_length=200, choices=EXTRA_KENNIS) -
Import models function
I created a models within my page but when I attempted to run the page I received an error response celery_beat_1 | class ClassManager(models.Manager): celery_beat_1 | NameError: name 'models' is not defined I searched for fixes to this error online and most of the responses said to implement the import from django.db import models function. However, this is something I already have configured in my models page. Any idea on how to proceed forward? -
When to use each model relationship in Django?
I've been reading through the Django documentation and looking over some of the other answers on the site for a couple of hours now, yet I still can't get it to sink in. I know this isn't Django specific, but the examples I use will be from a Django project. My question boils down to when is it appropriate to use each: Many-to-many relationships Many-to-one relationships One-to-one relationships One-to-one, more or less makes sense to me. Now for the other two. While I understand the differences between them in isolation, when it comes to using them practically in a project, I get confused. Here is an example: class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=64) description = models.TextField() class Watchlist(models.Model): user = models.ForeignKey(User, related_name='watchlist', on_delete=models.CASCADE) item = models.ManyToManyField(Listing) class Comment(models.Model): user = models.ForeignKey(User, related_name='comments', on_delete=models.SET_NULL) comment = models.TextField() Would this be the correct use of Many-to-one(ForeignKey) and Many-to-many? Should Watchlist.item be a ForeignKey? Or is M2M correct? Wouldn't it simplify to make the 'Watchlist' part of the User class? (give them an empty list to populate with listing ID's) Why is Watchlist.user not a One-to-one relationship, if each watchlist belongs to a single user, and a user can only have … -
Serpy serializer change the field name
I have the following django code using serpy serializer: class UnitTypeSerializer(TypeSerializer): nameLocal = LocalizationSerializer() um = serpy.Field() It is serialize as 'nameLocal': {'key': 'INTEG', 'en_GB': '', 'ro_RO': None}, 'um':1 I would like to change "nameLocal" to "local" -
Get the value of an IntegerChoices object in Django?
Suppose I have the following Django (3.2) code: class AType(models.IntegerChoices): ZERO = 0, 'Zero' ONE = 1, 'One' TWO = 2, 'Two' a = AType.ZERO How do I get "Zero" (the string associated with a)? This is very similar to this question, except here we only have the IntegerChoices object, and not an associated model object. -
Django behind reverse proxy ?next= issue
I have deployed a Django application behind an nginx reverse proxy. This proxy handles multiple Django applications So the main url is for example https://www.example.com and then I use the reverse proxy to redirect to the specific Django application using subdirectory for example https://www.example.com/myapp The problem is that if I logout from myapp and try to access a page that requires login the redirect link is wrong, instead of https://www.example.com/myapp?next=/mainpage it gives me https://www.example.com/?next=/myapp/mainpage which is wrong since "myapp" cannot listen to requests from https://www.example.com/ Is there any way I can force Django to understand that the default url is https://www.example.com/myapp and not https://www.example.com? Thanks -
Django: Form is not saved and "matching query does not exist" error
I'm trying to create an app to import thanks to an uploaded .csv file data to my database. This is my code and when I try to submit a new file the form is not saved in the database and I'm redirected to the home. I can't also access the file If I create it in admin because I get this error Dataset matching query does not exist. I think my problem is within the ForeignKey and the OneToOneField that I'm not able to save properly? Only the model File is compiled by the user, while Dataset should be filled from the information in the file and linked to the file and the user automatically . Thank you all for your help! VIEWS @login_required def file_upload(request): data = None if request.method == 'POST': file_form = FileForm(request.POST, request.FILES) data_form = DatasetForm(request.POST, request.FILES) raw_file= request.FILES if file_form.is_valid() and data_form.is_valid(): data = request.FILES['file_upload'] data = pd.read_csv(data, header=0, encoding="UTF-8") data_form.instance.user = request.user.profile file_form.instance.user = request.user.profile file_form.instance.filename = raw_file['file_upload'].name Dataset.objects.create( name_user_A = data.iloc[0,1], name_user_B = data.iloc[1,1], [...] ) data_form.save() file_form.save() return redirect('upload_file') else: return redirect('home') else: form = FileForm() context = { 'data': data, 'second_row': second_row, 'file_form': file_form, 'message': message, } return render(request, 'upload_file.html', context) … -
Django simple_jwt auth worked with blank token
My project is running jwt authorization based on the simple_jwt library. Despite the fact that I do not pass the Authorization: Bearer token header, the request passes and returns 201, but if I pass the wrong token, everything works as it should and 401 is returned. My settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'phone_number', 'USER_ID_CLAIM': 'client_phone_number', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } MyView: class SetPin(generics.CreateAPIView): """Change or set pin code""" serializer_class = serializers.PinSerializer -
django filtering not chained tables
How i can select values from not chained tables in django class Products(models.Model): id = models.CharField(...) name = models.CharField(...) price = models.FloatField(...) image = models.ImageField(...) timestamp = models.DateTimeField(...) class HistoryPrice(models.Model): id = models.CharField(...) name = models.CharField(...) price = models.CharField(...) timestamp = models.CharField(...) Can i get image from Product for a minimal price in HistoryPrice query like this: query_history = HistoryPrice.objects.filter(product__id=product).annotate(min_price=Min('price')) -
django-filter: Passing parameter to field_name from view
I have two views that are using the same FilterSet and wanted to pass "field_name" as a parameter to the FilterSet. So far I have tried overriding the init method on the FilterSet with no luck. Example code: class FirstViewSet(viewsets.ModelViewSet): filter_backends = (filters.DjangoFilterBackend,) filter_class = MyFilter FIELD_NAME_TO_FILTER_ON = "some_field" class SecondViewSet(viewsets.ModelViewSet): filter_backends = (filters.DjangoFilterBackend,) filter_class = MyFilter FIELD_NAME_TO_FILTER_ON = "some_other_field" class MyFilter(filters.FilterSet): my_data = filters.CharFilter(field_name=FIELD_NAME_TO_FILTER_ON) My goal is to pass FIELD_NAME_TO_FILTER_ON from the view to the FilterSet. -
Django ORM better way to manipulate django ORM query to find related data
Models: class Tweets(models.Model): date_created = models.DateTimeField(default=now, verbose_name="Created on") tweet_data = models.TextField(verbose_name='tweet message') user = models.ForeignKey(User,on_delete=DO_NOTHING) class UserFollowers(models.Model): follower_user = models.ForeignKey(User,on_delete=CASCADE,related_name="follower") followee_user = models.ForeignKey(User,on_delete=CASCADE,related_name="followee") The UserFollowers table has record for who follows whom. Here, I need to get all tweets posted by people I follow Current approach: myfollowees = UserFollowers.objects.filter(follower_user=user_idx) print(myfollowees) myfolloweeslist = [] for ele in myfollowees: myfolloweeslist.append(ele.followee_user.id) my_timeline_tweets = Tweets.objects.filter(user_id__in = myfolloweeslist) generate the my followee list (list of people I follow) fetch tweets where tweet is posted by userid and is also present in myfolloweelist I would like to know if there is a better way to handle this. I tried this and it worked for just one value of user_idx but not for others: my_timeline_tweets = Tweets.objects.filter(user__follower = user_idx) -
Django form using model_formset not submitting
I am trying to create a screen to display all users in my app and then have the ability to update the displayed fields for the users. Basically an admin view of the users. I would like to be able to update multiple users at once by hitting submit. I used modelformsets to accomplish this, and also copied the html from the answer to another question so that the forms would be displayed inline (see below). Html template: <div class="card-body"> <form action="{% url 'bugtracker:users' %}" method='POST'> <table id="formset" class="form"> {{ formset.non_form_errors.as_ul }} {{ formset.management_data }} {% csrf_token %} {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <button class="btn btn-primary" type="submit">Submit</button> </form> </div> The view: @login_required def users(request): # users = User.objects.all() UserFormSet = modelformset_factory(User,fields=('username','first_name','last_name','email','is_contributor','is_projectmanager','is_administrator'), extra=0) … -
Django unable to restrict Model creation passing no parameter to objects.create()
I'm doing a site using Python, Django and pytest and the TDD method. One of my goals is to don't allow create a Item in database if I don't pass any arguments as parameters to the Item.objects.create(). I have this tests: def test_not_possible_to_create_items_with_empty_name(self): with pytest.raises(IntegrityError): item = Item.objects.create() Pytest fails at this test and says it's not raising: Failed: DID NOT RAISE <class 'django.db.utils.IntegrityError'> I was not sure if it's not raising or the type of error it raises is different, so I made a test to see if it's raising: def test_something(self): item = Item.objects.create() And this test is passing, so it's not raising. My Model looks like this: class Item(models.Model): name = models.TextField( null=False, blank=False, unique=True, ) I want to be unable to create a invalid name like "", but it's not raising as well: self = <item.tests.test.TestItemModel object at 0x7f79fd448910> def test_not_possible_to_create_item_with_blank_name(self): with pytest.raises(IntegrityError): item = Item.objects.create(name="") Failed: DID NOT RAISE <class 'django.db.utils.IntegrityError'> -
Django: How to cascade an update through multiple models?
I'm writing a Django based application to keep track of objects (Objekt) and their maintenance tasks. Objekts can be linked to a location. Location (0/1) --- (n) Objekt (1) --- (n) Task Location, Objekt and Task all have a status field with the following values: RED = "red" YELLOW = "yellow" GREEN = "green" STATUS = [ (RED, "Overdue tasks"), (YELLOW, "Pending tasks"), (GREEN, "All good"), ] I want that the Location map marker changes its color based on the status of the related Objekts and ultimatelly Tasks. I've tried to follow django best practices and create a fat model. from django.db import models from locationapp.models import Location from taskapp.models import Task from rules.contrib.models import RulesModel class Objekt(RulesModel): RED = "red" YELLOW = "yellow" GREEN = "green" STATUS = [ (RED, "Overdue tasks"), (YELLOW, "Pending tasks"), (GREEN, "All good"), ] name = models.CharField(max_length=200) description = models.TextField(blank=True) location = models.ForeignKey( Location, on_delete=models.SET_NULL, null=True, blank=True ) status = models.CharField(max_length=6, choices=STATUS, default=GREEN) def set_status(self): if Task.objects.filter(objekt=self.id).filter(status=Task.RED).exists(): self.status = Objekt.RED elif Task.objects.filter(objekt=self.id).filter(status=Task.YELLOW).exists(): self.status = Objekt.YELLOW else: self.status = Objekt.GREEN But somehow I'm not sure about my concept here... How can an update on Task trigger an update on the related Objekt. And how would … -
What could be good achitecture for softwares that use intense working servers?
I am working on an application that turns client's geographic polygon files (geojson, shapefile, kml) and do some hard processing (temporal and spatial interpolation) using these data. The hard processing should be done on the application server side and when it is finished, the interpolation results should be available to the user as maps, charts and tables. I am currently working with Python/Django but it does not seems to be a good choice given the framework strict architecture. What is the best architechture to build this app? -
why my form wont save to the database after adding a new model to it
as soon as I migrate another model and before I even try to add other content to the form, my form stops saving to database. It was saving just fine until I migrated a new model. my form. class AccessionForm(forms.Form): last_name = forms.CharField(label = False, widget=forms.TextInput(attrs={'placeholder': 'Last Name', 'style': 'height: 70px; width: 280px', 'class': 'form-control'})) first_name = forms.CharField(label = False, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'style': 'height: 70px; width: 280px', 'class': 'form-control'})) midIntl= forms.CharField(label = False, widget=forms.TextInput(attrs={'placeholder': 'M', 'style': 'height: 70px; width: 70px', 'class': 'form-control'}), required=False) birthdate = forms.DateField(label = False, widget=NumberInput(attrs={'type': 'date','style': 'height: 30px; width: 130px', 'class': 'form-controls'})) age = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Age (xxx)xxx-xxxx', 'style': 'height: 30px; width: 45px', 'class': 'form-control'})) GENCHOICES = [('N', 'Gender'),('M','Male'),('F','Female'),('O', 'Other')] gender = forms.ChoiceField(label='Gender', choices=GENCHOICES) ssn=forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'SSN xxx-xx-xxxx', 'style': 'height: 30px; width: 250px', 'class': 'form-control'})) address=forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Address', 'style': 'height: 30px; width: 270px', 'class': 'form-control'})) cistzip = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'City State Zip', 'style': 'height: 30px; width: 270px', 'class': 'form-control'})) phone=forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Phone (xxx)xxx-xxxx', 'style': 'height: 30px; width: 170px', 'class': 'form-control'})) patientId=forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Patient ID', 'style': 'height: 30px; width: 170px', 'class': 'form-control'})) # Speciman info PHYCHOICES = [('N', 'None Selected'),('N', 'Joseph Aoki, M.D.'),('N', 'Glen Furuya, M.D.'),('N', 'Mayuko Imai, M.D'),('N', 'Martin Ishikawa, M.D.'),('N', 'Tai-Yuan David Lin, M.D. … -
how to override value in javascript prg with value from python program
Good afternoon, I have an assignment where I have to modify existing code in Django. It displays the sample row set with the number of rows entered from the screen. If the number entered is more that 500 it should return 20 rows and change the value in the input field to 20. How I can code it? The html for this field is the rowRequired: {numRows: '20'} I am new to JS and will highly appreciate help -
Django Admin Form fields don't update when change form is saved
In the admin form for a model. Before I submit the form. I want to edit/add a foreign key model field, using the Django admins popup change form. When I submit, I want the fields to update with the newly added data that was created/edited in that popup change form. class Button(models.Model): name = models.CharField(max_length=200) location = models.ForeignKey('Location', on_delete=models.CASCADE) class Location(models.Model): name = models.CharField(max_length=200, help_text="Start here, slug will be created from name.") software = models.ForeignKey('Software', on_delete=models.CASCADE) Can't seem to find any help on this subject. Any suggestions or help would be great. Maybe it can't be done? -
Select2 more filter in Django
i have this code below, where i'm using Select2 in my select component, it's working fine, as i'm writing it's looking, but i've already searched the internet to find examples of how to customize the query set that runs in the widget, some help ? select2 works very well class ConsumidorWidget(s2forms.ModelSelect2Widget): search_fields = [ "nome__icontains", "email__icontains", ] class ConsumoForm(forms.ModelForm): class Meta: model = Consumo fields = ('id', 'consumidor', 'mesconsumo', 'anoconsumo', 'valorapagar', 'valorhidrometro', 'dataleitura', 'datamissao', 'datavencimento', 'foipago',) exclude = ('bairro',) mesconsumo = forms.ChoiceField() widgets = { "consumidor": ConsumidorWidget, } -
Count data in stored procedure mysql
We have a system containing a school protocol where we want to be able to insert a class and the subject of the class and then be able to see an overview af all the students attendance of this specific subject in the specific class. I tried to create a stored procedure with no luck. Our data tables looks like the following: We would like to make it so when you give 2 values (keaclass_is and subject_id) in the Stored Procedure you will get back a view of how many times a username_fk has been attending a subject out of all the possible occurrences with the same keaclass_id. Therefore we need to check the amount of occurrences the subject has had on the date too. As an example we want the outcome to look like the following: So Nadi6548 has been attending subject_id 2, 4 out of 4 possible occurrence and nico4108 has only been attenting subject_id 2, 1 out of 4 possible occurrence. -
When placing the Django formset in the template table it doesn't work
Something strange happens in the code, the formset looks giant (I understand that it is because it is outside the table) but in the end it works, that is, when you click on the plus sign, the form fields appear duplicated or tripled I mean, the form looks unstyled but it works. When placing the empty_form inside the table it no longer works but it does fit with the styles and it looks good, that is, it looks good but it does not work. I don't understand what I'm doing wrong <div class="table-responsive"> <table class="table table-bordered table-nowrap align-middle"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_price}} </td> <td> <div> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="add_more" value="+" /> </td> </tr> <tr id="formset"> {{ formset.management_form }} {% for form in formset %} <td> {% render_field form.codigo class="form-control" %} </td> <td> {% render_field form.descripcion class="form-control" %} </td> <td> {% render_field form.quantity class="form-control" %} </td> <td> {% render_field form.unit_price class="form-control" %} </td> <td> {% render_field form.total_price class="form-control" %} … -
Stuck in App DB model structure in Django. (Job safety checklist App)
I want to create an App which is more like a checklist app which will have multiple questions (like a polls) like below but more than one. in response there will be 3 choices, Yes, No, and NA. for e.g. Q.1. Is BA staff equipped with Protective equipments? Ans. i.) Yes , ii.) No , iii) N/A Q.2. Weather is in good condition to climb to Work? Ans. i.) Yes , ii.) No , iii.) N/A Like this there will be a checklist with about 7-8 similar questions. and for each logged in user a seperate instance for complete checklist will be saved. My Solution (not scalable) : To create a model like... class Checklist: qus1 = model.CharField(...choices = yesnochoices) qus2 = model.CharField(...choices = yesnochoices) and so on... but this won't be good as professional and much scalable. ???????? Could you please suggest how should i made this.. other than the approach like above.? -
i encounterd a list index out of range error ,my view is as follows;
def login_view(request): if request.user.is_authenticated: return redirect('/dashboard') if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] cache.set('email',email) fact = User.objects.filter(email=email).values('username') username = fact[0]['username'] username = username.encode(encoding='UTF-8') password = password.encode(encoding='UTF-8') -
Pre-fill a Django ChoiceField inside a formset
I have a formset with a Runner field that should have some value from a Runner model. I use select2 widget to fill this value: when user types something, I use Ajax to query appropriate rows from the database. I want now to keep the values that this field stores when I submit my formset in case that there is some error and I have to show this form again. If I define this field as ChoiceField with choices=[], open the form and select some runner (e.g. with id=123), then after I send a POST request and try to initialize my formset with FormsetResult(data=request.POST), I get an error that the value provided is not presented in the choices list which is true. I tried to add this value to choices in the form constructor: def __init__(self, *args, **kwargs): runner_id = None if self.fields['runner'].initial: runner_id = kwargs['initial'].get('runner') runner = models.Runner.objects.filter(pk=runner_id).first() if runner: self.fields['runner'].choices = [('', ''), (runner_id, runner.get_name())] , but this still doesn't work after I submit the form: initial values are now empty, and in case of formsets, POST dictionary has ugly field names like form-0-runner which makes it hard to extract the value that I need. Another option is …