Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11 TinyMCE attrs, how correct change attrs cols and rows?
how fix cols and rows in HTMLField from TinyMCE package ? class ProjectCat(models.Model): title = models.CharField(max_length=30, unique=True, verbose_name='название') slug = models.SlugField(unique=True) desc = HTMLField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}), verbose_name='описание') -
Django can't find a specific static file
I'm getting a 404 when trying to load 'irpf.jpg' which is in the same folder as 'jumbotron.jpg'. Other files are served normally as well, just the 'irpf' can't be found at all. Tried to run collectstatic but it says that no changes where detected. Any ideas? Thanks, The first one loads, the second don't static files structure <div class="col"> <img src="{% static 'appStaticSite/jumbotron.jpg' %}" alt="Imposto de Renda"> <img src="{% static 'appStaticSite/irpf.jpg' %}" alt="Imposto de Renda"> </div> </div> -
How to filter joined models in Django?
I have the following models: class Street(models.Model): name = models.CharField(max_length=40) class House(models.Model): street = models.ForeignKey(Street, models.PROTECT) number = models.CharField(max_length=10) class Meta: unique_together = ('street', 'number') class Room(models.Model): house = models.ForeignKey(House, models.PROTECT) number = models.CharField(max_length=10) class Meta: unique_together = ('house', 'number') I already know the ID of a Street and would like to get all the rooms of all the houses in that street. In SQL that is easy: SELECT * FROM room JOIN house ON house.id = room.house_id WHERE house.street_id = xyz; Now how do I do this in Django? I tried Room.objects.select_related('house').filter(street=xyz) But I get an exception saying I can't access this field: django.core.exceptions.FieldError: Cannot resolve keyword 'street' into field. Choices are: house, house_id, id, number Because of the amounts of data I am facing, I would really like to be able to join and filter using a single query! When giving up one or the other, I would have to resort to either making multiple queries or filtering in Python, both of which are inherently inefficient. An alternative would be raw queries, I guess... -
How to save url of the image in database with Django
i am new in Django, how to save url of the image in db using django. Thank you very much, sorry my english, i am learning too. views.py from django.shortcuts import render from django.views.decorators.http import require_POST from .models import Cad_component from django import forms from django.views.decorators.http import require_http_methods class register_data(forms.ModelForm): class Meta: model = Cad_component fields = ('title','slug','description','start_date','imagviewe') def home(request): imagesData = Cad_component.objects.all() template_name = 'index.html' context = { 'imagesData': imagesData } return render(request, template_name, context) def register(request): if request.method == "POST": form = register_data(request.POST) print (form) if form.is_valid(): datas = form.save(commit=True) #datas.image.save(request.read['title'],request.read['image']) datas.save() else: form = register_data() return render(request, 'register.html', {'form': form}) models.py from django.db import models import datetime class ComponentManager(models.Manager): def search(self, query): return self.get_queryset().filter( models.Q(name__icontains=query) | \ models.Q(description__icontains=query) ) class Cad_component(models.Model): title = models.CharField('Title', max_length=100) slug = models.SlugField('Link') description = models.TextField('Description', blank=True) start_date = models.DateField('Data: ', null=True, blank=True) image = models.ImageField(upload_to='img', verbose_name='Imagem', null=True, blank=True) created_at = models.DateTimeField('Criado em ', auto_now_add=True) updated_at = models.DateTimeField('Atualizado em', auto_now=True) objects = ComponentManager() def __str__(self): return self.title -
How can i see what is in the cart ? Django
I can't display the cart items. In the previous project i used django 1.8 and that code and all worked . But now i use django 2.0 and i don't know is that i made a mistake somewhere or it is something new in django. Cart.py in cart app from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {"quantity": 0, "price": str(product.price)} if update_quantity: self.cart[product_id]["quantity"] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]["product"] = product for item in self.cart.values(): item["price"] = Decimal(item["price"]) item["total_price"] = item["price"] * item["quantity"] yield item def __len__(self): return sum(item["quantity"] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item["price"]) * item["quantity"] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shop.models import Product from .cart … -
Checkbox linked to a ManyToManyField - Django
I'm working on a blog project with Django. This blog has Users and Articles among others. For a customisation of type 'this-user-likes-this-article' a ManyToManyField seems a good choice, i.e. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) # additional user_favorites = models.ManyToManyField(Article) Now I'd like to implement a form (or a checkbox) that saves or deletes this kind of pairship (add/remove an Article from user_favorites), much in the way that a user likes an answer in StackExchange (and many other similar sites). Django forms are somewhat oriented to save an instance of a particular model, so which would be the smartest way to approach this form? Is there some open code that already handles this scenario? -
Using Django admin site in other applications [duplicate]
This question already has an answer here: Django admin search/filter functionality as a page table 2 answers My goal is to develop a web-application that would retrieve data from a database and display them in a table. I'm new to the web-development, this task is not my main goal, therefore, I'd like to spend minimum efforts for it. I've chosen Django for this task. I've got familiar with its admin site from the official tutorial, and can conclude that it has all required functionality (retrieving, sorting, filtering, search). In parallel, I've installed django-tables2. It requires much more efforts, for example, writing CSS templates, while admin has all included. Is it possible to use that admin site like ordinary web app just to display data, without adding or deletion? -
Can't generate djangojs.po file - Django JavaScript translation
Following Django docs I'm trying to generate djangojs.po files to tranlate strings in JavaScript. url.py: from django.views.i18n import JavaScriptCatalog urlpatterns = [ # ... url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), # ... ] Template file contains: <script src="{% url 'javascript-catalog' %}"></script> <script> // ... document.write('Some string to translate') // ... </script> My file system for the project: base_dir | |_ app_dir | |_ locale | |_ pt_BR | |_ LC_MESSAGES | |_ django.mo |_ django.po Running command to generate catalogs (django.po and djangojs.po): $ python manage.py makemessages -d djangojs -l pt_BR I'd expected that djangojs.po would be generated in LC_MESSAGES subdir this file is not generated in any place, so i can't translate any string that I map in gettext() function in JavaScript code. At least in the docs the only things that we have to do is the ones that I list above. So, why djangojs.po is not being generated? PS.: djangojs.po is in python lib outside my project. If I use gettext() with some string already translated there the translation works. -
How can I use a list to create a table in html?
I am writing a django app with bootstrap and I have a table with a head in one of my pages like the one below: <table class="table table-striped table-sm table-bordered table-fixed table"> <thead class="thead-inverse table_head"> <tr class="table_head_row"> <th class="table_head_item">header 1</th> <th class="table_head_item">header 2</th> <th class="table_head_item">header 3</th> <th class="table_head_item">header 4</th> <th class="table_head_item">header 5</th> <th class="table_head_item">header 6</th> <th class="table_head_item">header 7</th> <th class="table_head_item">header 8</th> <th class="table_head_item">header 9</th> <th class="table_head_item">header 10</th> </tr> </thead> </table> I was wondering if instead of writing the same line a number of times, just use a list and a for loop. I could pass the list with the headers from the pages view, like so: <table class="table table-striped table-sm table-bordered table-fixed table"> <thead class="thead-inverse table_head"> <tr class="table_head_row"> {% for header in table_headers %} <th class="table_head_item">header</th> {% endfor %} </tr> </thead> </table> Can I do something like this just in html ? -
Django: Adding attachment to generic.DetailView
I have a existing Django App with a detailview for UserProfiles. Now our client wants to have the ability to 'download' the information of the page to a PDF. I have added a button in the HTML to trigger the 'generate-attachement' method <div class="input-group"> <button name='zip' value="True" type="submit">Get report</button> </div> I have also added a 'generate_pdf' method to the view, which is triggered by the button above. class ProfileView(ProfileMixin, generic.DetailView): template_name = 'user/profile/detail.html' def get_object(self, queryset=None): return self.context.profile_user def generate_pdf(self): from reportlab.pdfgen import canvas response = HttpResponse(content_type='application/pdf') response['pdf'] = 'attachment; filename="summary.pdf"' p = canvas.Canvas(response) p.drawString(100, 100, "Hello world.") p.showPage() p.save() print(p) return response def get_context_data(self, **kwargs): data = super(ProfileView, self).get_context_data(**kwargs) #Check if 'get attachement' button has been pressed if self.request.GET.get('zip', None): self.generate_pdf() #Code to load relevant data form a large number of models #append it to the 'data' variable . #(e.g data['group_year] = ...etc return data However, when I run this code / press the button the method / print commands are all triggered, but no attachment is returned to the browser <reportlab.pdfgen.canvas.Canvas instance at 0x112165638> [08/Feb/2018 12:30:08] "GET /user/profile/459/?zip=True HTTP/1.1" 200 41749 Yet I got most of the code from the official Django Documentation, so its not entirely clear … -
Is Django-haystack 2.6.1 compatible with Django 2.0?
My question is simple (as per title). Is the current Django-haystack compatible with the newest Django 2.0? The requirements in the docs and at PYPI suggest that it is: https://django-haystack.readthedocs.io/en/master/#requirements https://pypi.python.org/pypi/django-haystack/2.6.1 But the following user faces issues as well as I do when trying to use it with Django 2.0: Django 2.0 haystack whoosh update index, rebuild index throw error The same setup works with Django 1.11. Thanks! -
Not able to update database in Django, empty entry created for first time
I'm trying to update particular fields in database but an empty entry is created with the fields to be updated when I try to update and after that I get an error saying Duplicate entry for primary key. I'm using rno as the primary key. Here is the view.py code: class InterestsViewSet(viewsets.ModelViewSet): serializer_class = serializers.InterestsSerializer authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): return models.UserProfile.objects.filter(rno=self.request.user).values() def perform_update(self, serializer, *args, **kwargs): instance = self.get_queryset() instance.workshop = validated_data.get("workshop") instance.sports = validated_data.get("sports") instance.creative = validated_data.get("creative") instance.cultural = validated_data.get("cultural") instance.placement = validated_data.get("placement") instance.dance = validated_data.get("dance") instance.drama = validated_data.get("drama") instance.save() serializer = self.get_serializer(instance) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) Here is the serializers.py file: class InterestsSerializer(serializers.ModelSerializer): """A serializer for interests.""" class Meta: model = models.UserProfile fields = ('workshop', 'sports', 'creative', 'cultural', 'placement', 'dance', 'drama',) The models.py file: class UserProfile(AbstractBaseUser, PermissionsMixin): """A user profile in our system.""" rno = models.CharField(max_length=10, blank=False, primary_key=True, null=False) name = models.CharField(max_length=45, blank=True, null=True) workshop = models.BooleanField(default=True) sports = models.BooleanField(default=True) creative = models.BooleanField(default=True) cultural = models.BooleanField(default=True) placement = models.BooleanField(default=True) dance = models.BooleanField(default=True) drama = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) Any help on what I'm doing wrong would be really helpful. Thanks! -
runt time pdf attachment in django 1.9
how to send attachment pdf in the mail plaintext = get_template('email/email.txt') htmly = get_template('email/invoice.html') text_content = plaintext.render(kwargs) html_content = htmly.render(kwargs) html = get_template('email/invoicepdf.html') html_content_pdf=html.render(kwargs) email = EmailMultiAlternatives(sub, text_content, to=[useremail]) email.attach("Report.pdf", generatePdf(html=html_content_pdf), "application/pdf") email.attach_alternative(html_content, "text/html") email.send() mail is sent but the body does not show on mail (attachment show) -
django: load and initialize site-wide js only once
In my django project at each page I use big external library which initialization takes few seconds (to be more precised: http server and web browser do great job to decide whether or not file should be re-send but my problem is strictly related with code initialization). Is there any way to load (initialize) js script once and use it at all pages with django application? The only idea which I have is to use only ajax (without normal httpRequest) but this is very inconvenient. Do you have any better idea? -
How can I filtering objects of a model that their foriegn keys are not null in django?
I have these two models: class Questions(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) and in views.py I want to return just 5 last questions that have choice. In other words questions without any choice don't return. my view: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] What change should I apply in return statement? Sorry for my bad English. Thank you -
Users access in odoo,Sales Module
I created a new user 'demouser'. I have sales module in odoo 10, I want to restrict demouser from creating a new quotation in sales. How can i do that.? -
Django make migrations error
I am currently trying to make migrations for an app that I created in Django. My files are organised as follows: wisdompets/db.sqlite3 wisdompets/manage.py wisdompets/adoptions/__init__.py wisdompets/adoptions/admin.py wisdompets/adoptions/apps.py wisdompets/adoptions/models.py wisdompets/adoptions/tests.py wisdompets/adoptions/views.py wisdompets/adoptions/migrations/__init__.py wisdompets/wisdompets/__init__.py wisdompets/wisdompets/settings.py wisdompets/wisdompets/urls.py wisdompets/wisdompets/wsgi.py wisdompets/wisdompets/__pycache__/__init__.cpython-36.pyc wisdompets/wisdompets/__pycache__/settings.cpython-36.pyc wisdompets/wisdompets/__pycache__/urls.cpython-36.pyc wisdompets/wisdompets/__pycache__/wsgi.cpython-36.pyc Initially I tried to make migrations by typing in the following into the terminal: ('adoptions' is the app name) python3 manage.py makemigrations adoptions But it's saying that the app could not be found. So I went to settings.py and added the app under Installed_APPS by typing in the following: 'adoptions.apps.AdoptionsConfig'. Now when I go back to the terminal and type in the same commands as before, this is what came up: Anyone has idea how to fix this problem? Thanks in advance! -
Check in a View if is an upate or a create operation?
I have some operations that I do in form_valid (method on GCBV) that are repeated in multiple views. Also the operations for views that inherits from CreateView or UpdateView are very similar. So I want to create a class where I write a generic 'form_valid', and all other View inherit from that class, something like: AssocUpdateView(BaseClass, UpdateView) AssocCreateView(BaseClass, CreateView) So for create and update there is a small variation, so I need to know when I'm creating and when I'm updating in form_valid. It is possible ? -
Unable to mock a function in Python (Django)
I'm trying to mock a function used within the function I'm testing, but for some reason I'm not seeing the original function always runs, not the one I created as a mock. The code I'm testing has this type of setup: def function_being_tested(foo): ... function_i_want_to_mock(bar) ... def function_i_want_to_mock(bar) print("Inside original function") ... I've installed Mock and I've tried using unittest.mock patch Currently the test file uses this setup: import mock from django.test import TestCase def mock_function_i_want_to_mock(bar): print(bar) return True class SupportFunctionsTestCases(TestCase): @mock.patch("path.to.function.function_i_want_to_mock", mock_function_i_want_to_mock) def test_function_being_tested(self): # setup result = function_being_tested(test_foo) self.assertEqual(result, expected_result) What then happens is when I run the test, I always get: "Inside original function", not the parameter printed so it's always running the original function. I've used this exact setup before and it has worked so I'm not sure what's causing this. Probably some wrong setup... If anyone has a different way of doing this or spots some error, it would be appreciated. -
django Cannot find static/css files error 404
This problem seems to be widely known, however, most are old Q&A's and they do not solve my problem. I am using Django 2.0.2 and when my simple web page is not rendering my bootstrap.css file because it simply cannot find it. I am following this tutorial: https://simpleisbetterthancomplex.com/series/2017/09/11/a-complete-beginners-guide-to-django-part-2.html#static-files-setup This is my file structure: myproject/ |-- myproject/ | |-- boards/ | |-- myproject/ | |-- templates/ | |-- static/ | | +-- css/ | | +-- bootstrap.min.css <-- here | +-- manage.py This is my static variables defined in the settings.py file. STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] This is my home.html file as is with the bottom half cut out for brevity. {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Boards</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body> <h1>Boards</h1> I have debugging set to true, and when I run my server and load it up, I am presented with the following: [08/Feb/2018 19:26:02] "GET /static/css/bootstrap.css HTTP/1.1" 404 1675 I am also not able to visit this URL as it states a 404 error too: http://127.0.0.1:8000/static/css/bootstrap.min.css. I'm not sure as to why Django cannot find the .css file when I have it clearly stated in the … -
Parse html to text and text to html in DRF
I need to parse the html code to markdown and again i need to parse the markdown text to html for rendering, for this thing i need to use two different package. Currently i'm going to use html-to-text - Html to Markdown text and mistune - Markdown text to Html. The thing is that everything i need to do in the API part. So no connection with front-end. I need a better solution to do this. -
Load different HTML page based on URL in Django class based view
Currently my urls.py has this code login_view = LoginView.as_view() url(r'^login$', login_view, name='login'), I have written a corresponding LoginView in my views.py class LoginView(FormView): template_name = 'auth/login.html' form_class = forms.LoginForm Now my requirement is I want to create a login page for different set of users who would come from a different url. For ex myproject.com/customers. I can do it with a new View class. But I want to make it generic and want to handle it in the same LoginView() class. Is it possible to catch the url parameter and check that inside LoginView and load a different login.html page for them. Or is there any other way using which we can handle this situation -
How to handle API Framework casing that is different than Javascript Casing?
I use django rest framework that uses snake_case for attributes which send data to Angular client which should work on camleCase since they are javascript properties. What is the cleaner way to handle this incoherence ? -
username field in django sign up form
I use from django.contrib.auth.forms import UserCreationForm in forms.py for creating sign up form. first I register with a username, for example ali and again when I try to register with Ali it allows me to create user. how can I prevent registering with two same username like Ali and ali ? -
My product index is not updating as i am using haystack solr django oscar
As I am using Django oscar haystack and solr setup it is working fine, but when I do any change in product data it is not updating the index, when I do sorting and anything it is working like previous index result. I added in settings HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' but it is not working, as I used the default app that is provided by Django oscar. so what tweaks needed to resolve this problem .