Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate due date in django
I am creating a "library" website using django. Once a user has issued a book, I want to calculate a due date for it, 3 months after the issue/present date. How do I do it? -
Django how to see urls.py and settings.py changes without apache restart
I am setting up a django project on an apache server. I have access to the .htaccess and index.fcgi files, but no sudo access. When I make changes to urls.py or settings.py, the changes don´t come through. Is there a way to see changes come through without restarting apache? For example by adding a configuration to the .htaccess file? Here https://stackoverflow.com/a/6282363/5881884 is recommended doing touch on the .wsgi file, but I don´t have any file ending with .wsgi and neither is there a file including the string django.core.handlers.wsgi.WSGIHandler() .htaccess file: AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule /static/ /home/myusername/public_html/static RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule ^(.*)$ index.fcgi/$1 [L] RewriteCond %{HTTPS} !=on RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] -
Migration not working Django, Heroku
I have run locally make migrations and I got my migrations files in my folder. Then I pushed it live to heroku. But heroku didn't apply the changes to my database which is causing now an error. One column does not exist because of the missing migration. Locally everything works fine. I checked via heroku bash if the migration files exist and they do. Then I tried to run manage.py migrate. The output was: No migrations to apply. Also having release: python manage.py migrate in my procfile didn't help either. Any ideas what I can try to do else or why heroku is not migrating? -
how to find result with any word in list in django
I would like to find a list of results that are contained that match any word in a list. For example if company have different inputs it could still find them: company_name = 'awesome blossom' I would like to search for companies with 'awesome' and 'blossom' in the name. I tried something like this: companies = Company.objects.filter(company_name__icontains__in=company_name.split(' ') but this didn't work. How can I accomplish this? -
How to handle a form not tied to a specific URL with a view in Django?
I am creating a job board site and I have the following urls.py (not that important just included them to make the question clearer) : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name = "index"), url(r'^job_info/(?P<job_id>[0-9]+)/$', views.job_info , name = "job_info"), url(r'^employer_signup', views.employer_signup, name="employer_signup"), url(r'^employer_home', views.employer_home, name = "employer_home"), url(r'^login/$', login, {'template_name':'core/employer_login.html'}, name = 'employer_login'), ] I have a base.html that is included in all of the HTML files. This includes a Navbar with an inline search bar: <form class="form-inline my-2 my-lg-0 navbar-toggler-right" method = "post" > {% csrf_token %} <input class="form-control mr-sm-2" type="text" placeholder="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> Is there a way to handle this form with a View? As it is not directly tied to any specific URL? -
Bootstrap Snippet does not look like it has to in Django
Heyho, i'm new to Django and i have a problem including a template to my view. I want to use the following snippet from Bootstrap "https://bootsnipp.com/snippets/Nj4gp", but it just look like on the picture below. I took the same Code and just changed the Content of the table. Can somebody tell me what could be wrong, i checked, that bootstrap is in the right static folder. I do not understand why some parts work and others not.enter image description here Thanks in advance! Magda -
DetailView Shows Same Page Doesnt Return Detail page
models.py from django.db import models class india(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "Indians" class Australia(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "Australians" class South_Africa(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "South_Africans" class England(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "England's" views.py from django.shortcuts import render from .models import india,Australia,South_Africa,England def index(request): return render(request, "index.html") def india_v(request): rec_posts1 = india.objects.order_by('-Date_of_Publishing')[0:1] rec_posts2 = india.objects.order_by('-Date_of_Publishing')[1:2] rec_posts3 = india.objects.order_by('-Date_of_Publishing')[2:3] post = india.objects.all() context = {'rec_posts1':rec_posts1,'rec_posts2':rec_posts2,'rec_posts3':rec_posts3,'post':post} … -
One form for all classes in a model
I have a parts app where my model looks like this class Part(models.Model): name = models.CharField(max_length=550) def __str__(self): return self.name class Image(models.Model): image = models.FileField() part = models.ManyToManyField(Part, related_name='image_part') class IDNum(models.Model): IDNum = models.CharField(max_length=50) part = models.ForeignKey('Part', related_name='ID') def __str__(self): return self.IdNum class Stock(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2) unit = models.ForeignKey('Unit') part = models.ForeignKey('Part', related_name='stock') stockarea = models.ForeignKey('StockArea') class Warehouse(models.Model): name = models.CharField(max_length=550) address = models.TextField() def __str__(self): return self.name class StockArea(models.Model): area = models.CharField(max_length=550) warehouse = models.ForeignKey('Warehouse') def __str__(self): return '%s %s' % (self.warehouse, self.area) class Unit(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=550) abbreviation = models.CharField(max_length=10) def __str__(self): return self.abbreviation In the admin page I have a form for each class. I really want to add a Part and choose Images, set a IDNum, Choose Warehouse to get list of StockArea's for that Warehouse and set Stock Quantity and choose Abbreviation in one form. Is it possible to create a custom form for the admin pages, so that I can manage this for all classes in a model. They are all related somehow. I would like some tips on how, if it's possible =) -
Django using .get fails on model which uses content types
My .get method is failing. From the django documentation on a model implementing content types / generic foreign key you cannot use: TaggedItem.objects.filter(content_object=guido) # This will also fail >>> TaggedItem.objects.get(content_object=guido) So, do I pass in the content_type and object_id instead? I am using get_object_or_404(TaggedItem, content_type__pk=ct_pk, object_id=pk) and this raises a 404 despite these values beign correct in the database. -
Django - how to sum two Fields of a model? [duplicate]
This question already has an answer here: Django Aggregation: Summation of Multiplication of two fields 4 answers Here's a quick example class Invoice(models.Model): (...) net_amount = models.DecimalField(decimal_places = 2, max_digits=8) tax = models.DecimalField(decimal_places = 2, max_digits=8) @property def gross_amount(self): return self.net_amount + self.tax Then I want to query for chosen Invoices in my ListView using a form and GET: class ListInvoicesView(ListView, FormMixin): (...) def get_queryset(self): (...) return self.model.objects.filter(gross_amount__lte = self.kwargs.get('max_gross_amount')) (I skip some code for the sake of readability) This yields FieldError: Cannot resolve keyword 'gross_amount' into field. What is the proper way to sum two fields of a model? -
Backend endpoints to frontend
Here's the situation: We have a large django application, not on REST structure, our front-end was build with React. What we want to do is find an easy way to tell our front-end which are the URL's that our backend has. For example: Our backend has a "active plan" endpoint which is "plans/active", what we are doing in present days is build a file with django templates that builds an JS object with that endpoints, something like: const urls = {plans: {active: {% url "active_plan" %}}}; The problem here is that it's growing like hell and slowly becoming unorganized and with repeated urls. We had 2 ideas: First one was to parse these urls on python build to generate a file with similar structure as I said before, reflecting exactly what we desire Second one was to have something like a store to make an initial request that is gonna return some area (or all) urls and store these in an object. First one problem is that with an international application, we're gonna have all languages urls in one file, it doesnt not seen nice. Second problem is that we think it can become a big payload if not broken … -
TypeError : encode() missing 1 required positional argument: 'iterations'
i dont know what is triggering this error. i dont know why i keep getting this error . i already change a few parts of code and still i get this error . i have been trying to fix it for 2 days . Traceback: File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register 13. user = form.save() File "C:\Users\Adila\Documents\tryFOUR\src\custom_user\forms.py" in save 50. user.set_password(self.cleaned_data["password2"]) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\base_user.py" in set_password 105. self.password = make_password(raw_password) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in make_password 84. return hasher.encode(password, salt) Exception Type: TypeError at /accounts/register/ Exception Value: encode() missing 1 required positional argument: 'iterations' hashers.py : from django.contrib.auth.hashers import PBKDF2PasswordHasher from django.utils.crypto import (get_random_string, pbkdf2) from honeywordHasher.models import Sweetwords class MyHoneywordHasher(PBKDF2PasswordHasher): algorithm = "honeyword_base9_tweak3_pbkdf2_sha256" iterations = PBKDF2PasswordHasher.iterations*3 def hash(self, password, salt, iterations): hash = pbkdf2(password, salt, iterations, digest=self.digest) return base64.b64encode(hash).decode('ascii').strip() def salt(self): salt = get_random_string() while Sweetwords.objects.filter(salt=salt).exists(): salt = get_random_string() return salt def verify(self, password, encoded): algorithm, iterations, salt, dummy=encoded.split('$',3) hashes = pickle.loads(Sweetwords.objects.get(salt=salt).sweetwords) hash = self.hash(password, salt, int(iterations)) if hash in hashes: return honeychecker.check_index(salt, hashes.index(hash)) return False def encode(self, password, salt, iterations): sweetwords = ['hilman95'] sweetwords.extend(honey_gen.gen(password, base64, ["passfiles.txt"])) … -
How to create a download button/option for image/filefield in Django
Working fine. But whenever i am hitting the file download link download option appears but after i download the file it's no longer the same file that i have uploaded. rather it becomes 9 bytes small file and can't be opened. views.py def download_file(request, path): response = HttpResponse('image/png') response['Content- Type']='image/png' response['Content-Disposition'] = "attachment; filename="+path response['X-Sendfile']= smart_str(os.path.join(settings.MEDIA_ROOT, path)) return response urls.py url(r'^get\/(?P<path>.*)$', download_file), -
Redirect after POST django rest framework
I am submitting a POST request via django form to my Django Rest Framework api. Here is a snippet of my form: <form action="{% url 'entry-list' %}" method="POST" class="form" role="form"> {% csrf_token %} {{form.as_p}} <div class = "form-group"> <button type="submit" class="save btn btn-default btn-block">Save</button> </div> views.py: class entry_ViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class= EntrySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,) def perform_create(self, serializer): serializer.partial = True serializer.save(created_by=self.request.user) I am making a successful POST (and item is created in database), however once I save I go to the url /api/entry/ which shows my api w/Markdown. I'd like to have it go back to a specific url. Is there a way to customize where the POST redirect to if successful? -
Django : several models returns in queryset
Yeah I know, it's not possible. Or maybe I didn't see. But, I'm gonna explain why I need this. Let's do some dummy classes: class A(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() lvl_struct = GenericForeignKey('content_type', 'object_id') Let's say A can be attached to a struct (logical struct, like department in jobs). An A instance can be attached to only one struct, but there're 4 disctinct type of struct, and that's where I discovered generic foreign key (instead of a polymorphism on A). But now, my problem is, in my form, I want to attach the actual struct when I create a A instance : class CreateAForm(forms.ModelForm) lvl_struct = forms.ModelChoiceField( queryset=None, #here is my problem required=True ) So here I would like to have a unique select with all possibilities (all instances of first struct type, all instances of second struct type and so on). So is there any way to do this, or will I have to do like four select with some js to check at least one and only one select has a value? Or of course a third solution which I didn't see. Tell me. Thank you in advance for your time. -
How to introduce a model class method in Django admin
I have a model that has class methods. In testing the class methods work and alter the model instances according to my needs. The issue is using this class method in the admin. When an application cannot pay a late payment fee is applied creating another transaction altering the balance. The method in models is decorated with a @classmethod decorator. I need to get it so when status is altered, or when a tickbox is checked in the admin for an application it fires the class method. I have Googled overriding models in admin but cannot find anything. Many thanks for reading this. -
Replace string with other string python django
Hi guys i want to convert link into proper format for example i have text like This is google link https://www.google.com This is gmail link https://www.gmail.com And what i want is This is google link <a href="https://www.google.com">https://www.google.com</a> This is gmail link <a href="https://www.gmail.com">https://www.gmail.com</a> and here is code that i have written body_without_quotes = request.POST.get('stripped-text', '') data1 = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', body_without_quotes) for da in data1: link = "<a href="+da+">"+da+"</a>" body_without_quote = body_without_quotes.replace(da, link) print body_without_quotes but it does not print required output can anyone tell me what i am doing wrong here. Thanks -
Django: How to return with context from UpdateView (CBV)?
The following view works as expected class BrandEditView(PermissionRequiredMixin ,generic.UpdateView): permission_required = 'change_brand' template_name = 'brand_update_form.pug' model = Brand fields = ['name'] def get_object(self, queryset=None): print(self.request.user) self.object = Brand.objects.get(id=self.kwargs['pk']) obj = Brand.objects.get(id=self.kwargs['pk']) return obj After form submission, how do I return to the same view (with the same object), but with a message like "brand edited successfully"/"you can't do that"? I've found a way to redirect to the same view, but not with context. -
Performance, load and stress testing in Django
I am studying the different types of testing for a Django application. I know how to do functional and unit testing in Django and how to apply different methodologies, but now I am facing a new challenge, I need to know how to do: Performance testing Load testing Stress testing I know the difference between them but I dont know which is the best methodology to follow,which are the best packages for do it or simply where I can get some documentation about it. So my question is, how can I start to do these types of tests in a Django app or where can I get some good documentation about it? Thanks -
Django models.DecimalField issues with type and value conversion
Let's say you have a model like this: class Example(models.Model): amount = models.DecimalField(max_digits=8, decimal_places=2) I can do the following with no issue: x = Example() x.amount = 1.23456 x.save() print(x.amount, type(x.amount)) # outputs '1.23456 <type 'float'>' If I load back the object I find that x.amount is now equal to Decimal('1.23'). So, my issue is, at any given moment with any given instance of Example the amount attribute may contain a Decimal, a float, an integer, or something else that can be coerced into a Decimal. Also, the value may not yet be rounded to 2 decimal places so the value may change after saving and loading back from the database. As well, a statement like x.amount + Decimal('1') may work or may throw an exception about combining float with Decimal. Has anyone developed a replacement for models.DecimalField that mitigates these issues by immediately performing conversions and rounding when assigning a value instead of how it currently functions? Or, alternatively, a model that throws an error if an improper type is assigned or one that would be rounded on save? (I suspect I could write my own, but I was hoping I could find someone else's work that's already been … -
Django how to merge multiple query results
I have an ArrayField with choices and i'm trying to filter the choices: When i use Location.objects.filter(city__id='683506').values_list('options', flat=True) and it returns me <QuerySet [['0'], ['0', '1', '2', '3'], ['0', '1', '2'], ['0', '1'], ['0', '1', '2', '3']]> How can i merge the query or make them into a list and merge them? This is what i wish to get ['0', '1', '2', '3'] -
DjangoRestFramework serializer filter and limit related
Thats my models: class Org: name = CharField() owner = ForeignKey(User) class Cafe: name = CharField() org = ForeignKey(Org) class Product: name = CharField() class Assortment: cafe = ForeignKey(Cafe) product = ForeignKey(Product) price = IntegerField So the deal is - i need to search products with very specific way. It should looks like this: /assortment/search/?searh=cola 'cafe':{ 'id:1, 'name': 'Foo', 'assortment': [ { 'product': { 'id': 1, 'name': 'Cola' }, 'price': 100 }, { 'product': { 'id': 2, 'name': 'Coca-cola' }, 'price': 200, } ], 'search_count': 5, }, 'cafe': { 'id':2, 'name': 'Bar', 'assortment': [ { 'product': { 'id': 3, 'name': 'Sprite-cola', }, 'price': 150, }, ] 'search_count': 1, } So the problem is - when i search like Cafe.objects.filter(assortment__product__name='cola') It works, it shows all Cafes where product with name 'cola' exists, but problem is DJF serializer class CafeSerialzier: assortments = AssortmentSerializer(source='assortment_set') search_count = IntegerField(source='assortment_set.count') assortments and search_count shows all assortment and count of it, and does not consider search arguments, which is expected. So the question is - how to pass search parameters into source='assortment_set' (Also i need to limit results to 3) and how to count all search results. I've tried SerializerMethodField for assrotments, it solves a part of … -
django-simple-history, displaying changed fields in admin
When I inherit from admin.ModelAdmin, in history on admin page I can see what fields has been changed. However, now I need to use django-simple-history to track all my model changes. Now, for admin, I inherit for simple_history.SimpleHistoryAdmin. Whilst I can see all of the model changes and revert them, I cannot see, which fields were changed. Is it possible to add that handy functionality to SimpleHistoryAdmin? -
Type-error - django python
from django.conf.urls import * from django.contrib import admin from payments import views admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'ecommerce_project.views.home', name='home'), # url(r'^ecommerce_project/', include('ecommerce_project.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^$', 'main.views.index', name='home'), url(r'^pages/', include('django.contrib.flatpages.urls')), url(r'^contact/', 'contact.views.contact', name='contact'), url(r'^sign_in$', views.sign_in, name='sign_in'), url(r'^sign_out$', views.sign_out, name='sign_out'), url(r'^register$', views.register, name='register'), url(r'^edit$', views.edit, name='edit')] Issue in this code - type error - view must be callable I do not understand what is wrong with my urls.py file, here is a copy of it: Type error -
inline form with django crispy form
I'm sorry but I just don't get it, the docs here are pretty awesome, and I'm using practically the same example, I just have two fields, that I want do display inline, but it's just does not work, My form: from django import forms from crispy_forms.helper import FormHelper from crispy_forms import layout, bootstrap from crispy_forms.bootstrap import InlineField, FormActions, StrictButton from crispy_forms.layout import Layout from ..models import EmployeeModel class EmployeeCreateForm(forms.ModelForm): """ TODO: Extend CompanyModel into Form :returns: TODO """ def __init__(self, *args, **kwargs): super(EmployeeCreateForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.method = "POST" self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap3/layout/inline_field.html' self.helper.form_action = "company:create-employee" self.helper.layout = Layout( 'first_name', 'last_name', StrictButton('Add', css_class='btn-default'), ) class Meta: model = EmployeeModel fields = ["first_name", "last_name"] and my template: {% extends "base.html" %} {% load i18n static %} {% load crispy_forms_tags %} {% block content %} <nav class="navbar fixed-top navbar-light bg-faded"> <ul class="nav justify-content-center"> <li class="nav-item"> <a class="nav-link" href="{% url 'why' %}">WHY SCREEN?</a> </li> <li class="nav-item"> <a class="nav-link" href="#">BLOG</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'faq' %}">FAQ</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'about' %}">ABOUT</a> </li> </ul> </nav> <div class="container"> <div class="row"> <p style="padding:60px;"></p> </div> </div> <div class="container"> <div class="row"> <div class="col-sm-4 col-sm-offset-2"> <form …