Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django use the same variable in different functions
What I am trying to do is, fetching data from a third party app and show it on the page. I will get the data in get_context_data function and use the same data in get_initial method as well. I could not manage to do that. Is there any way to do that? Example Code class UpdateView(generic.FormView): template_name = 'test.html' form_class = myForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MYVARIABLE = fetch_data_from_3rd_party_app() context["MYVARIABLE"] = MYVARIABLE return context def get_initial(self): initial = super().get_initial() # I want to assign MYVARIABLE.data to initial["data"] here. initial["data"] = MYVARIABLE return initial -
displaying a date in django template using javascript
I'm not sure why the date won't display in this django template, using javascript and html: I've also found this helpful: how to display a javascript var in html body But following that, still can't get it to work. Currently I have: {% extends 'chattr.html' %} <section class=""> hello </section> <script> let d = new Date(); document.getElementById("date0").innerHTML = d; n = new Date(); y = n.getFullYear(); m = n.getMonth() + 1; d = n.getDate(); document.getElementById("date").innerHTML = m + "/" + d + "/" + y; </script> <p id="date"></p> {% block chatStream %} <b>smallest_steps:</b> <br> Hello! Please send me a message:) <span id="date0"></span> <br> <p id="date"></p> {% endblock %} and chattr.html <h1>ss</h1> {% block title %}{% endblock %} {% block chatStream %} {% endblock %} Thanks so much -
Django - sort json data from largest to smallest
i'm fetching the data from elasticsearch to html, but I want to sort the data in html from largest to smallest according to the amount, how can I do it? ex. of how i display error counts ( hiding div if is == 0) ; {% if test== 0 %} <div style="display: none;"><b>Test Service:</b> {{test}}</div> {%else%} <b>Test Service:</b> {{test}} <br> {%endif%} view; def dashcontrol(request): url = "http://XX/_search" headers = {'Content-type': 'application/json'} params = { TEST PARAM } print('OK') response = requests.get(url=url, json=params, headers=headers) data = response.json() test= data['hits']['total'] print(data['hits']['total']) print('BAŞARILI') return render(request, 'dashcontrol.html', {'test':test) -
How to send bloburls to FileForm in django
I have the following bloburl blob:http://127.0.0.1:8000/99bbb97e-79ee-4ac5-b553-796e1f5e897e How do I pass this to the Filefield in Django so that I can save this file ? My models.py looks something like this class UploadFile(models.Model): fileId = models.AutoField(primary_key=True) file = models.FileField(upload_to = file_upload_path) fileDescription = models.TextField() -
Best naming conventions for having multiple form fields, of same subject
Hey all simple question here, I have a Django form field like so player = forms.CharField(required=False, widget=forms.Textarea( attrs={ 'class': 'form-control'), max_length=200, help_text='Please enter a player name.') This charfield form takes a players name from the input, parses the DB, pulls stats of that player. Now, I want to add another player so on the front end, both player's stats can be compared like so player_2 = forms.CharField(required=False, widget=forms.Textarea( attrs={ 'class': 'form-control'), max_length=200, help_text='Please enter a player name.') If I want to do something like this, what's the proper naming convention I should make player_2? I learned it's not best practice to just add _2 to a variable name. Thoughts? -
Django display a video from model
I have a model that contains a video files uploaded to my media/videos folder. When i am on the admin page i can see the video and play it. I am now trying to render it on a template but it doesn't let me. Here is my model: class CheckList(models.Model): choices = (('', 'Select'), ('Good', 'Good'), ('Not Good', 'Not Good')) fuel_choices = (('', 'Select'), ('Full', 'Full'), ('3 Quarters', '3 Quarters'), ('Half Tank', 'Half Tank'), ('Almost Empty', 'Almost Empty')) cargo_choices = (('', 'Select'), ('Cargo Secured', 'Cargo Secured'), ('Cargo Not Secured', 'Cargo Not Secured'), ('No Cargo', 'No Cargo')) vehicle = models.ForeignKey(Trucks, on_delete=models.CASCADE, blank=True, null=True) driver = models.ForeignKey(User, on_delete=models.CASCADE) breaks = models.CharField(null=False, choices=choices, max_length=50, default='Select') wipers = models.CharField(null=False, choices=choices, max_length=50, default='Select') wiper_fluid = models.CharField(null=False, choices=choices, max_length=50, default='Select') cargo = models.CharField(null=False, choices=cargo_choices, max_length=50, default='Select') cargo_straps = models.CharField(null=False, choices=choices, max_length=50, default='Select') tires = models.CharField(null=False, choices=choices, max_length=50, default='Select') oil = models.CharField(null=False, choices=choices, max_length=50, default='Select') miles = models.IntegerField(null=False, default='0') gas = models.CharField(null=False, choices=fuel_choices, max_length=100, default='Select') seatbelt = models.CharField(null=False, choices=choices, max_length=100, default='Good') date_created = models.DateTimeField(auto_created=True) # Need video of vehicle video = models.FileField(upload_to='videos/') def __str__(self): return self.vehicle.nickname My View that handles the page render: @login_required() def report_detail(request, pk): checklist = CheckList.objects.get(pk=pk) context = {'checklist': checklist} return render(request, 'driver/report_detail.html', … -
I want make list with django
category1 = '' category1_tmp = ['a','b',c','d'] for n in category1_tmp: category1 &= n + '|' django error : unsupported operand type(s) for &=: 'str' and 'str' what i want : a|b|c|d how can I solve? -
how to add class {% render_field formset.empty_form %}
I would like my form to have their respective classes to give it a better view, at least to standardize the design {% render_field formset.empty_form %} Anyone have any ideas. The question is that I cannot standardize everything to the same class since there is a special class for the check -
How to write queryset to get data from different connected models in Django?
My models structure: PRODUCT_TYPE = ( ('s', 'simple'), ('v', 'varaible') ) class Products(models.Model): name = models.CharField(max_length=250,null=True, blank=True,) slug = models.SlugField(max_length=200, unique=True,null=True) product_type = models.CharField(choices=PRODUCT_TYPE, default='simple', max_length=50) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) is_published =models.BooleanField(default=False) class ProductAttribute(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE, related_name='attributes', default=None) attributes = models.ForeignKey(Attributes,on_delete=models.CASCADE, related_name='attributes', default=None) values = models.ForeignKey(AttributeTerms, on_delete=models.CASCADE, related_name='attributes', default=None) class ProductVariant(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE) variant = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE, null = True, default=None) stock = models.IntegerField(default=None) stock_threshold = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) sku = models.CharField(max_length= 250, default=None) sale_price = models.DecimalField(max_digits=10, decimal_places=2) sale_start_date=models.DateField(auto_now_add=False, auto_now=False) sale_end_date=models.DateField(auto_now_add=False, auto_now=False) What I want to achieve: If product_type is varaibale and if product has more than one variations, get the minimum and maximum price and show in range( as shown on attached image0 If product has sale_price, get the lowest sale_price and get the regular price of same variant having lowest sale_price. if product_type is simple, if sale_price is not none show regular price and sale_price else show regular price if product has sale_price and if sale start date is less than today, and if sale end date is greater than or equal to today, get sale_end_date And show in template in the format as shown in image. Any help will be … -
Django referencing column incompatible with referenced column
I have Displays and Ads table. The Ads have a reference to Displays. What could be the issue there if it's a standard model.? def generate_uuid(): return uuid.uuid4().hex class DisplaysDJ(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) from display.models import DisplaysDJ as Displays class AdsDj(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) display = models.ForeignKey(Displays, on_delete=models.CASCADE, blank=False, null=True) _mysql.connection.query(self, query) django.db.utils.OperationalError: (3780, "Referencing column 'display_id' and referenced column 'id' in foreign key constraint 'orders_adsdj_display_id_4024e66a_fk_displays_id' are incompatible.") -
A dynamic site that does not use JavaScript
I started using the python django framework. Can I open a dynamic site without using JavaScript? I find python easy to use and for some reason I don't like JavaScript. -
Pass ForeignKey to page and retrieve data
I have a page that basically displays user-entered data based on a project. The initial page contains just a handful of fields one being the project_name, which I have set as unique project_name = models.CharField(max_length=50, blank=False, unique=True) From this page, I want to open up another page based on the project_name which enables additional details to be added and stored in a different model. Models.py class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) ckeditor_classic = models.TextField(blank=True) def __str__(self): return str(self.project_name) class Fundamentals(models.Model): project_name = models.ForeignKey(Project, to_field='project_name', on_delete=models.CASCADE) project_website = models.URLField(max_length=100, blank=True) project_roadmap = models.CharField(max_length=25) def __str__(self): return str(self.project_name) What I am struggling to do is load the second page but displaying the project_name and be able to associate the next set of data to the project I think i need to do this via the views and urls but I can't get it to work. View.py @login_required def AddFundamentals(request,project_id): project = Project.objects.get(pk=project_id) form = AddFundamentalsForm(request.POST or None, instance=project) if form.is_valid(): form.save() return redirect('dahsboard.html') return render(request, 'pages/critical_fundementals.html', {'project': project, "form": form}) The error returned is AddFundamentals() missing 1 required positional argument: 'project_id' but I am passing this in via the URL path('fundanmentals/<project_id>', view=AddFundamentals, name="add_fundamentals"), Do … -
static fills in django
I get this error when I run collectstatic File "C:\django\venv\lib\site-packages\django\contrib\staticfiles\storage.py", line 38, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. enter image description here I learned the code from an educational video Does anyone know the reason ??? Thank you for answering -
What are the best practices for storing duplicated data in Django models such as first name, last name, and full name
I have built a project with a React frontend and a Django Rest Framework (DRF) API for my backend. Things are going well but I am quite curious about best practices for data saved against your models. As an example, I have a user model with first_name and last_name fields. There is a one-to-one relationship between my user and the two user domains (let's say Buyer and Seller as an example). In addition, we have a foreign key relationship for Seller on something like a Product. On my UI, I have tables that display the data and in general, the majority of tables display the user's full name (first_name + last_name). Generally, all table fields I will want to filter by and order by. I decided that I wanted the data returned from the REST API to represent the table data so I am now returning full_name by augmenting the serializer of Buyer and Seller to have full name using a SerializerMethodField like so: full_name = serializers.SerializerMethodField() ... def get_full_name(self, obj) -> str: return obj.user.get_full_name() However, I will also need to do this in all places where I want to show the Buyer/Seller where they are referenced by a Foreign …