Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models not showing in template
I am finding it quite difficult to display django models in template. The Model does not show at all in the template. Any help will indeed be appreciated. models.py from django.db import models from django.urls import reverse from datetime import datetime class Blog(models.Model): name= models.CharField(max_length = 200) company= models.CharField(max_length = 200) post = models.CharField(max_length = 200) author= models.ForeignKey('auth.User', on_delete = models.PROTECT) mantra= models.CharField(max_length = 200, help_text='make it short and precise') photo= models.ImageField(upload_to='photos/jobs/%Y/%m/%d/', blank=False, null=False) publish = models.BooleanField(default =True) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') views.py from django.shortcuts import render from django.views.generic import TemplateView,ListView from django.views.generic.edit import CreateView from .models import Blog class Home(ListView): model = Blog context_object_name = 'test' template_name='test.html' fields = ['name', 'company', 'post', 'author', 'mantra', 'continent', 'photo'] urls.py from django.urls import path from .views import Home urlpatterns=[ path('', Home.as_view(), name='index'), ] Template <p>{{test.name}}</p> <p>{{test.author}}</p> <p>{{test.post}}</p> -
Trim text in a cell of bootstrap table
How can I trim text in a cell of bootstrap table? Example: In bootstrap table below I have big names in 'stock name' column, this messes formatting of my entire table for example (check columns like invested amount, gains etc). Can I give fixed length to content in stock name column ? By default it can show "Ajanta Ph...", OnHover of a cell it can show full name. I am injecting this page from Django template. <tr id="port_row_{{row.stock}}_{{index}}"> {% if row.stock == 'TOTAL'%} <td> {{row.stock}}</td> {% else %} <td> <a target="_blank" style="color:blue;" href="https://www.google.com/finance?q=NSE:{{ row.stock }}">{{row.stock}}</a></td> {% endif %} <td>{{row.name}}</td> <td>{{row.monday_open_price|intcomma}}</td> <td>{{row.previous_close|intcomma}}</td> <td> {% if row.price >= row.previous_close %} <div style="color:green"> {{row.price|intcomma}} </div> {% else %} <div style="color:red"> {{row.price|intcomma}} </div> {% endif %} </td> <td> &#x20b9; {{row.investment_amount|intcomma}}</td> <td> {% if row.weekly_gain >= 0 %} <div style="color:green"> {{row.weekly_gain|intcomma}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.weekly_gain|intcomma}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> <td> {% if row.daily_gain >= 0 %} <div style="color:green"> {{row.daily_gain|intcomma}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.daily_gain|intcomma}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> <td> &#x20b9; {{row.current_market_value|intcomma}}</td> </tr> -
Django Initial Page Load Slow After Python 2 to 3 Upgrade
I run Django 1.11.20. I have just (finally) made the jump from Python 2.7 to 3.7. I've noticed that since upgrading to Python 3, the very first page load after clearing the cache is very slow. So far I only have my Python 3 environment on my development machine, so I'm experiencing this when using ./manage.py runserver and the FileBasedCache backend. I don't know if I will experience the same thing on a production stack (nginx, uwsgi, redis, etc). I'm using Django Debug Toolbar, which gives me some hints as to what the problem isn't, but I'm not sure where I should look to see what the problem is. The times given by the debug toolbar run loading a simple page with an empty cache in the Python 2.7 environment on my development machine are: CPU: 4877.89ms SQL 462.41ms Cache: 1154.54ms The times given by the debug toolbar run loading the same page with an empty cache in the Python 3.7 environment on my development machine are: CPU: 91661.71ms SQL 350.44ms Cache: 609.65ms (I'm using the file based caching on this development machine, so when I say "with an empty cache" I just mean that I rm -r cache before … -
Use php to call django view - best way
i have a PHP script from a payment provider that can receive payment notifications (Instant Payment Notification - IPN). The problem is that my web application used django. Now i try to find a solution to handle the received data with django and store them to the database. My first idea was to send the received data within the php script via post to a django view (via normal url) with a function like cURL. But is that the best way? Or can i call a django function/view directly from php? My django web application run under apache2 with mod_wsgi -
In Django, how do I query that all of the related objects have the same value for a certain field?
Let's say I have the following models in Django: class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, related_name='children', null=True) foo = models.CharField(max_length=5, blank=True, null=True) How would I query the Parent model to find all Parent records where ALL of it's children have a value of 'ABC' for foo? If I run: Parent.objects.filter(children__foo='ABC'), it returns Parent objects where at least one of it's children has a value of 'ABC' for foo, which is not what I want. Any help is appreciated, thank you. -
Django schedule framework doesn't work like it's supposed to
I'm trying to get to work the schedule framework for django but it doesn't look right and it's functually broken as well, although only in the front-end. A pop-up to show an event doesn't work either f.e.. This is how it is supposed to look like vs this is how it actually looks like Does anybody have an Idea what the Problem might be? Any help would be much appreciated. -
How to calculate all the consummation of a client?
I'm working on a project of managing payments of a restaurant, but I'm new in django and I need help to calculate the total consummation of a client. I tried to sum to sum a consommation, but can't sum all consommations for a client class Consommation(models.Model): .... vipcustomer = models.ForeignKey(VipCustomer, models.CASCADE, null=True, blank=True, verbose_name='Client prestigieux', related_name='vip_consommations') def total_consommation(self): get_price = Consommation.get_price return get_price(self.entree) + get_price(self.food) + get_price(self.dessert) + get_price( self.boisson) + get_price(self.autres) Thanks in advance. -
Dajngo gets error when overriding save method
I overriding model's save() method to do some work with directory. My overrided save() method looks like this: def save(self, *args, **kwargs): book_dir = os.path.join(MEDIA_ROOT, self.title) # check that at least one file is loading if all([self.pdf, self.fb2, self.epub]): raise ValidationError("At least 1 file should be uploaded!") # create book's directory if it not exists if os.path.exists(book_dir): raise ValidationError("This book is already exists!") else: os.mkdir(book_dir) # assign uploading files storage for x in [self.image, self.pdf, self.fb2, self.epub]: x.storage = book_dir super().save(*args, **kwargs) # Call the "real" save() method. Everything goes well until last line. Django gives me AttributeError: 'str' object has no attribute 'save' error. -
Why my overwriting on labels and widgets from UserCreationForm on Django doesn't work?
Although I found how to work around the problem (cf. at the bottom of the page), I do not understand why my overload of UserCreationForm doesn't work without erase parent attributs. Yet, I did a lot of research. In particular on this doc forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.utils.translation import gettext, gettext_lazy as _ from . import models class SignUpForm(UserCreationForm): """ Form for sign up in training app """ email_confirmation = forms.EmailField() # password1 = forms.CharField(label='Mot de passe') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) print(self._meta.labels) print(self._meta.fields) # self._meta.labels = { # 'username': 'Nom d`\'utilisateur', # 'password1': 'Mot de passe', # 'password2': 'Confirmation du mot de passe', # 'email': 'Adresse e-mail', # 'email_confirmation': 'Confirmation de l\'adresse e-mail', # } class Meta(UserCreationForm.Meta): model = User fields = ( "username", "password1", "password2", "email", "email_confirmation", ) labels = { 'username': _('Nom d\'utilisateur'), 'password1': _('Mot de passe'), 'password2': _('Confirmation du mot de passe'), 'email': _('Adresse e-mail'), 'email_confirmation': _('Confirmation de l\'adresse e-mail'), } # UserCreationForm.Meta.labels = { # 'username': _('Nom d\'utilisateur'), # 'password1': _('Mot de passe'), # 'password2': _('Confirmation du mot de passe'), # 'email': _('Adresse e-mail'), # 'email_confirmation': _('Confirmation de l\'adresse e-mail'), # } widgets … -
Class object value not displaying properly
I have implemented a counter in my Django program. It is not displaying as intended. From Views class PostDetail(DetailView): model = Post def get_context_data(self, **kwargs): data = super(PostDetail, self).get_context_data(**kwargs) self.object.view_count = F('view_count') + 1 self.object.save() return data I know this works because if I comment out the method From HTML Page <small class="text-muted">{{ object.view_count }}</small> How ever when I try to use the method it prints, F(view_count) + Value(1) Instead of a number as intended. I'm not sure what else to try as I am new to Django. I attempted to research how to fix it but couldn't find anything. -
A better syntax for switch-like conditions in Django Template
Does anyone know a less bulky way of performing a switch-like evaluation in Django Template than the one below? <div class="alert {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}alert-danger {% elif message.level == DEFAULT_MESSAGE_LEVELS.WARNING %}alert-warning {% elif message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}alert-success {% elif message.level == DEFAULT_MESSAGE_LEVELS.INFO %}alert-info {% elif message.level == DEFAULT_MESSAGE_LEVELS.DEBUG %}alert-dark {% else %}alert-light{% endif %} alert-dismissible fade show" role="alert"> {{ message }} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> -
JavaScript & HTML changes not appearing through Django server
I recently began a new job working on a Django server, and for some reason, the server stubbornly keeps refusing to propagate my updates. This seems to be getting worse; sometimes I can make a change. I've done a bunch of research and can't seem to get any closer to the problem. It is NOT due to my cache. I've been consistently clearing my cache, closing my browser, and even occasionally restarting the computer. It's NOT due to server cache, either. I've been stopping and starting the service with each test. It's not due to static files being updated. I've even gone and changed all the static files manually, and I've repeatedly run manage.py collectstatic both with and without the -c flag. I tried appending a number to the JS url (adding "?rand=23423423" to the end of the script src links), as that was recommended to fix the JS problem, and that's when I found that the HTML wasn't updating either. Changes made to .py files and CSVs always consistently work the first try. Only JS and HTML files have not been propagating. I'm working with Python 3.7, Django 2.1.5, Google Chrome 77.0.3865.90 and macOS (which I'd never worked with … -
Using field as row in django tables
I'm using the django_tables2 library and I don't see anywhere in the documentation to use the fields as rows instead of columns. class PizzaTable(tables.Table): class Meta: model = PizzaInstance fields = ("pizza", "type", "size", "price") attrs = {"class": "mytable"} Can I use pizza and type as rows in django_tables2 library? -
How to integrate Blockchain using Django
The Blockchain code is written in python and to use it in Django framework what imports we need and in which section ? -
Any way to update a ManyToMany field via a queryset?
Suppose I have an object: survey = Survey.objects.all().first() and I want to create a relationship between it and a group of objects: respondents = Respondent.objects.all() for r in respondents: r.eligible_for.add(survey) where eligible_for is an M2M field in the Respondent model. Is there any way to do it in one pass, or do I need to loop over the queryset? -
My sign up form is not working with django python
I have a problem with my application the sign up is not creating profiles on the backend. I have tried to use the django forms but I didnt like how they render so I wanted to use custom form but once I click button submit, nothing happens and I check on backend there's no profile. My forms.py file looks like this from django.forms import ModelForm from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Gig class GigForm(ModelForm): class Meta: model = Gig fields = ['title','category','description', 'price', 'photo', 'status'] class SignUpForm(forms.ModelForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password' ) Models.py File like this class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.CharField(max_length=500) about = models.CharField(max_length=500) location = models.CharField(max_length=30, blank=True) def __str__(self): return self.user.username - Views.py ```python def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() user.refresh_from_db() username = form.cleaned_data.get('username') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home.html') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) signup.html looks like this <div class="container1"> <img src="{% … -
Django: Overwriting a form. how to shortening the mapping of the fields?
i am testing forms and model nesting in django. Due to a ManyToMany Relation in my form i have to use a custom save function. So far it works. But i asked myself if there is a way to shorten the code? So here is my my... forms.py GuestForm(forms.ModelForm): dish = forms.ModelChoiceField(queryset=None) # --- Input for meal.table table_input = forms.IntegerField(widget=forms.NumberInput) class Meta: model = Guest fields = [ 'name', 'dish', 'table_input', 'city', 'department' ] # --- Dish names from dish.model def __init__(self, *args, **kwargs): super(GuestForm, self).__init__(*args, **kwargs) self.fields['dish'].queryset = Dish.objects.all() def save(self): # --- save the new Meal.object data = self.cleaned_data mealData = Meal(table=data['table_input'], dish=data['dish']) mealData.save() # --- save the new Guest.object guestData = Guest(name=data['name'], city=data['city'], department=data['department']) guestData.save() # --- add a m2m relation between Guest.object and Meal.object guestData.meals.add(mealData) guestData.save() return guestData Question My Question is especially related to the mapping of all fields after i saved mealData.save(). # --- save the new Guest.object guestData = Guest(name=data['name'], city=data['city'], department=data['department']) guestData.save() Because in bigger Projects it could mean a lot of work, to map every field afterwards, just because i needed tableand dishto save in a extra model. Or in other Words is there some Kind of Selection Method? Something like … -
Cross checking and validating two input fields in django
I am new to python and Django, i wanted to know how below thing can be possible? input field 1 - Enter name - abc@yoyo.com input field 2 - Enter Url - www.yoyo.com Submit button so I want to validate the email domain and the URL name is same. Suppose if abc@yoyo.com is not similar to the URL field (www.yo.com) so show an error. else if it's same then proceed. How can this be implemented in Django? -
How to get the amount for one specific client (vipcustomer)'s consommation in my detail view?
I want to get what each customer has as consommation in money, in my detail view, have problems in finding the way to render it, I'm new in django. this is the model for consommation class Consommation(models.Model): entree = models.ForeignKey(Entree, models.CASCADE, verbose_name="L'entree", null=True, blank=True) food = models.ForeignKey(Meals, models.CASCADE, verbose_name='Plat de resistance', null=True, blank=True) dessert = models.ForeignKey(Dessert, models.CASCADE, verbose_name='Dessert', null=True, blank=True) boisson = models.ForeignKey(Boisson, models.CASCADE, verbose_name='Boisson', null=True, blank=True) autres = models.ForeignKey(Autres, models.CASCADE, verbose_name='Snacks', null=True, blank=True) consomme_le = models.DateTimeField(default=timezone.now, editable=False) vipcustomer = models.ForeignKey(VipCustomer, models.CASCADE, null=True, blank=True, verbose_name='Client prestigieux', related_name='vip_consommations') @staticmethod def get_price(item, _default=0): if item: return item.price return _default def total_consommation(self): get_price = Consommation.get_price return get_price(self.entree) + get_price(self.food) + get_price(self.dessert) + get_price( self.boisson) + get_price(self.autres) the client: class VipCustomer(models.Model): ... I have used the related_name to get all the consommations for a specific vipcustomer, but in addition of that I want to calculate the total of those consommations for that vipcustomer. Thanks in advance. -
Display a Foreign Key Dropdown in Django Form as Text
Is there a way to show a foreign key field in a Django form as an read only text box? forms.py class NewModelForm(forms.ModelForm): class Meta: model = Model fields = ['fk_field', 'other_field'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['fk_field'].widget.attrs['readonly'] = True #the dropdown is still active when this is set #self.fields['fk_field'] = forms.CharField(widget=forms.TextInput()) ##when I turn this on, I get an error that I am assigning to the wrong instance. -
Permissões exceto de um grupo
Na query abaixo, obtenho uma lista de todas permissões. routines = ( Permission.objects.select_related("content_type") .values("id", "name", "content_type__app_label", "content_type__model", ) .order_by("content_type__app_label") ) Retorno da query: accounts | accountsroutine | Can add accounts routine accounts | accountsroutine | Can change accounts routine accounts | accountsroutine | Can delete accounts routine accounts | accountsroutine | Can view accounts routine Preciso alterar esta query para excluir dela as permissões já concedidas a um determinado grupo. Como fazer? -
Django template language
"dishList" is a list of "dish" object and "dish" object includes an "id" field. For example: dishList = [dish1, dish2, dish3, ...] dish1.id = 1 "dishCount" is a dictionary type in python, which include a number for each dish. For example: dishCount = { dish1.id: 0, dish2.id: 0, ...} My problem is that in this for loop: {% for d in dishList %} How can I assess the number of dish "d"? I want to use {{ dishCount.(d.id) }} but it is not working. Could not parse the remainder: '(d.id)' from 'dishCount.(d.id)' -
ValueError at /
The view demo.views.index didn't return an HttpResponse object. It returned None instead. @csrf_exempt def index(request): if request.method == 'POST': session_id = request.POST.get('sessionId') service_code = request.POST.get('serviceCode') phone_number = request.POST.get('phoneNumber') text = request.POST.get('text') response = "" if text == "": response = "CON What would you want to check \n" # response .= "1. My Account \n" response += "1. My Phone Number" elif text == "1": response = "END My Phone number is {0}".format(phone_number) return HttpResponse(response) -
Export pdf file
Please help me i just want to export pdf file i am stuck with qs variable i dont know how to type i searched but could not find complete answer. views.py response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="hello.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) qs = Item.objects.all() # SOLVE IT PLEASE p.drawString(100, 100, qs) p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
The current path, about, didn't match any of these
I'm learning Django and just started looking at it installing Django 1.11.17 on my local. But I got the below error while browsing the url. Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: ^admin/ The current path, about, didn't match any of these. I have created a Django project named website and an app named blog. I have made the views file and urls.py as below urls.py file in website package from django.conf.urls import url from blog.views import Aboutus urlpatterns = [ url(r'^about', Aboutus), ] root_urlconf of setting.py file in website ROOT_URLCONF = 'website.urls' views.py of blog from django.http import HttpResponse def Aboutus(request): retrun HttpResponse('Woww') I have spent so much time on this and browsed the answers related to this but I didn't get the solution. I can't find out what I'm missing here so please draw my attention to the gap.