Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin/site_base.html overwrites my admin/site_base.html
My admin/base_site.html doesn't load or gets overridden by django's admin/base_site.html. Please let me know what I'm missing out (I started recently) I have my template at BASE_DIR/templates/admin/base_site.html In settings TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(BASE_DIR, "templates"), ], "APP_DIRS": True, "OPTIONS": { 'debug': True, "context_processors": [ "django.contrib.auth.context_processors.auth", "django.template.context_processors.debug", "django.template.context_processors.i18n", "django.template.context_processors.media", "django.template.context_processors.static", "django.template.context_processors.tz", "django.template.context_processors.request", "django.contrib.messages.context_processors.messages", "account.context_processors.account", "pinax_theme_bootstrap.context_processors.theme", ], }, }, ] -
Django - Proper Way To Use LoginView
I've read that function-based login is deprecated as of 1.11, but also that LoginView is not available as of Django version 1.9. What's the current way to set up a login URL if we aren't supposed to do this: from django.contrib.auth.views import login and we can't do this? from django.contrib.auth.views import LoginView (the latter yields a No name 'LoginView' in module 'django.contrib.auth.views' message) -
Append a specific line
def get_submit(title=None, button=None): if title is None: title = LABEL_CREATE return Div( Div( HTML('<a href="/accounts/signin/" class="btn btn-primary">%s</a>'% LABEL_SIGNIN), Submit('submit', title, css_class='white-text'), css_class="right-align"), css_class="card-action") You could see in the line HTML('<a href="/accounts/signin/" class="btn btn-primary">%s</a>'% LABEL_SIGNIN),. This line is optional in fact. I would like to modify this code in such a way if the button is not None, then it will append that line in the Div method. My problem is not the if statement, my problem is to append this line if the condition is respected. How could I do that? -
How to integrate angular 4 with Django
I'm trying to integrate Django and Angular 4 in the same app (running as two servers as well). Well, reading the setup guide I noticed about the references to the node_modules directory (and some "hardcode" references). Well, I wanna know if is possible to merge those technologies, I mean, to use the Django context and the http.get of angular to bind the results. Or, those npm_modules should are included in my static directory? But, where I should generate the angular project? -
Django Rest Framwork, many to many groups
I'm new to using DRF. I have a 2 layered many-to-many relationship I would but I would like to be able to serve up. # modles.py class Person(models.Model): name = models.CharField(max_length=32) class Group (models.Model): name = models.CharField(max_length=32) people = models.ManyToManyField(Person,related_name='groups',blank=True) class Event(models.Model): name = models.CharField(max_length=32) groups = models.ManyToManyField(Group ,related_name='events',blank=True) In my serializer I would like to be able to show in Person, which event they are attending. class PersonSerializer(serializers.ModelSerializer): class Meta: model = person fields = ('name', 'events') However, I'm getting an error when I look up events. Is this lookup even possible? -
WSGI error with two SSL virtual hosts and apache
I have two Django projects running on the same server, accessed by two different domains, both of them using HTTPS provided by Let's Encrypt. Both of them are working and I can access them from https://foo.com or https://bar.com. If I go to foo.com it redirects to https://foo.com; but for bar.com, it redirects to https://foo.com too. I have two .conf files that look like: <VirtualHost *:80> ServerName foo.com ServerAlias www.foo.com </VirtualHost> <VirtualHost *:443> ServerName foo.com ServerAlias www.foo.com Alias /static /var/www/html/foo <Directory /var/www/foo/static> Require all granted </Directory> <Directory /path/to/foo> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess foo.com python-home=/path/to/venv/foo python-path=/path/to/ WSGIProcessGroup foo.com WSGIScriptAlias / /path/to/foo/wsgi.py RewriteEngine On RewriteCond %{HTTPS} off RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] SSLCertificateFile /etc/letsencrypt/live/foo.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/foo.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> And the other one is pretty much the same but for "bar" where ever is a "foo". Both have their own virtualenvs and settings. My /etc/apache2/sites-enabled have only these two files: foo.com.conf and bar.com.conf. For the SSL I used: sudo letsencrypt --apache -d foo.com -d www.foo.com and sudo letsencrypt --apache -d bar.com -d www.bar.com At running the second one, it shows this error: Name duplicates previous WSGI daemon definition. Any idea on what's wrong? -
Django Rendering Same Page Fresh
After form.save() I want to render same page with a message. form.save() form = myform(request.POST) #for empty form return render(request, 'same_page.html', {'form': form, 'message': message}) But form comes filled again. How to view it fresh? -
return 500 internal server error in django
I Do a form request in django with ajax but the response is always 500 and i don´t have any ideia what is wrong. My ajax post using ember e jquery: saveContactAndDownload() { this.set('showErrors', true); var self = this; if(!this.isEmpty('name') && !this.isEmpty('email') && !this.get('invalidEmail')) { let store = this._targetObject.store; let contact = store.createRecord('contact-download', { name: this.get('name'), email: this.get('email'), }); My django view: @throttle(zone='institucional-contact') @csrf_exempt @require_POST def contactdownload_contact_api(request): import ipdb; ipdb.set_trace(); post = json.loads(request.body) form = ContactDownloadAPIForm(post.get('contactDownload')) if form.is_valid(): contact = form.save() response = {'contactDownload': {'id': contact.id}} return HttpResponse(content=json.dumps(response), status=200) else: errors = form.errors msg = '<br />'.join([errors.get(error)[0] for error in errors]) return HttpResponse(content=msg, status=400) My url.py: urlpatterns = patterns( '', url(r'^', include(DashboardResource().urls)), url(r'^', include(LoginResource().urls)), url(r'^', include(AgendaResource().urls)), url(r'^', include(ChatResource().urls)), url(r'^', include(MunicipioResource().urls)), url(r'^', include(UFResource().urls)), url(r'^', include(BranchResource().urls)), url(r'^file/upload/$', csrf_exempt(UploadResource.as_view())), url(r'^', include(FileTypeResource().urls)), url(r'^', include(DeedResource().urls)), url(r'^', include(api.urls)), url(r'^{}/contact/$'.format(api.api_name), simple_contact_api, name='simple_contact_api'), url(r'^{}/branch-contact/$'.format(api.api_name), branch_contact_api, name='brsanch_contact_api'), url(r'^{}/candidate-contact/$'.format(api.api_name), candidate_contact_api, name='candidate_contact_api'), url(r'^{}/contact-download/$'.format(api.api_name), contactdownload_contact_api, name='contactdownload_contact_api'), url(r'^{}/magazine-contact/$'.format(api.api_name), magazine_contact_api, name='magazine_contact_api'), url(r'^{}/partnership/$'.format(api.api_name), partnsership_contact_api, name='partnsership_contact_api'), url(r'^v1/search/$', search_autocomplete, name='search_autocomplete'), url(r'^v1/destiny-guide/$', destiny_guide, name='destiny-guide'), ) And i have no ideia what do , my dubugging ipdb the request is made , but the response is always that: Ember Data Request POST http://dev.worldstudy.com.br:8000/api/v1/contact-download/ returned a 500 Payload (text/html) [Omitted Lengthy HTML] Error -
Search django-taggit tags
I need help adding in the django-taggit tags to my search function. I'm currently using the search function that I found on here (Search page on the django). Is there any way to incorporate taggit into this? Or am I better off using a package like Haystack? This is for a simple internal web app for my company, ~ 3-4 light users. -
How to use the date picker used in django 1.11 admin site in custom form?
I want to use the date picker in my ModelForm that is used in django admin site but I don't know how to use because i am new in Django so help me to solve this and thanks in advance. -
Django: Associate objects before committing
So I'm loading a djang-registration Form, which I'm subclassing like so in order to create two related objects, a GeneralUser, and their Business. The below code fails with the warning: save() prohibited to prevent data loss due to unsaved related object 'owner'. And I have also got warnings in the vein of "NoneType Object has no attribute owner"'NoneType' object has no attribute 'is_active'" when trying to create a Business like so :business = Business(name=self.cleaned_data['business_name'], owner=user) I'm simply looking for a way to not commit to db either the user or the business, unless I'm doing it simultaneously. Please note I do not have a view for this form to check all sorts of things as form.isvalid() because django-registration is taking care of all those views. class GeneralUserForm(UserCreationForm): business_name = forms.CharField(required=True) class Meta: model = GeneralUser fields = ['username', 'email', 'password1', 'password2', 'business_name'] def save(self, commit=True): user = super(GeneralUserForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) business = Business.objects.create(name=self.cleaned_data['business_name'], owner=user) if commit: user.is_active = True # TODO: remove before deployment. user.save() business.save() return user How would I go about associating GeneralUser with Business, and only then committing to the DB? -
Django in multiple servers
I am trying to set up a django server, and I would like to have the admin pages in admin.example.com/app_name, the api endpoints in api.example.com/app_name and the normal pages in www.example.com/app_name. I tried to do it via nginx, but internal links are messed up, and I have redirects. Is what I am trying even possible in django? -
Trying to integrate Talend and Python( Django)
Am planning to integrate Talend tool with Python( mainly django) as part of front end. Do any one have idea about it? -
I have following messages
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/info Using the URLconf defined in mysites.urls, Django tried these URL patterns, in this order: ^ ^$ [name='index'] ^info/ ^admin/ The current path, info, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Email conformation system-how to set submited emails to recipient_list in signal
I successfully,manually sent an email to specific email address and activated the user but I cannot figure out how to: 1 Set submitted emails into recipient_list in my post_save_activation_receiver signal,since email field itself is defined in other model(if it is possible)? 2 Make this emails that I sent more secure, because gmail is treating them like potential fishing content. models.py from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.contrib import messages from django.core.mail import send_mail from django.conf import settings from django.core.validators import RegexValidator from django.db import models from django.db.models.signals import post_save # Create your models here. from .utils import code_generator USERNAME_REGEX = '^[a-zA-Z0-9.+-]*$' class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( username = username, email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( username, email, password=password, ) user.is_admin = True user.is_staff = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): username = models.CharField( max_length=255, validators=[ RegexValidator( regex = USERNAME_REGEX, … -
self.cleaned_data.get not working with integer field
I have a pretty basic definition within my forms.py to pull data from my submitted form. Something I have done with other apps, but for some reason, it is not working at the moment. I feel like I'm overlooking something. Whenever I print(image_height) I get None. models.py height_field = models.IntegerField(default=1200) forms.py class PostForm(ModelForm): class Meta: model = Post fields = ['user', 'title', 'content', 'post_image', 'height_field', 'width_field', 'draft', 'publish'] def clean_post_image(self): post_image = self.cleaned_data["post_image"] image_height = self.cleaned_data.get("height_field") print(image_height) return post_image -
expend search and return all objects Djangorestframework
Currently in my ModelViewSet I'm returning all contacts for today, additionally I'm checking if the query_params on the request for searching/filtering is available and not empty, In that case I'm not adding "today" to the queryset so that will perform search on the entire queryset. Problem is that I need to extend search so the user can see other users contacts, but only when he search for them, default view should not be changing if you are not searching, so how can I extend my current filter and return all objects in search. My current view: from rest_framework import viewsets, permissions, filters from cms.restapi.pagination import StandardResultsOffsetPagination from cms_sales.models import LeadContact from cms_sales.restapi.permissions.lead_contact_permissions import LeadContactPermissions from cms_sales.restapi.serializers.lead_contact_serializer import LeadContactSerializer class LeadContactViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user if user.has_perm('cms_sales.can_view_full_lead_contact_list'): queryset = LeadContact.objects.all() elif user.has_perm('cms_sales.can_view_lead_contact'): queryset = LeadContact.objects.filter(account_handler=user) filter_date = self.request.query_params.get('filter_date', None) search_params = self.request.query_params.get('search', None) if filter_date is not None and (search_params is None or len(search_params) == 0): queryset = queryset.filter(next_action_date=filter_date) return queryset serializer_class = LeadContactSerializer filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) filter_fields = ('account_handler',) ordering_fields = ( 'first_name', 'last_name', 'account_handler__first_name', 'account_handler__last_name', 'sub_organization_name', 'organization_name', 'next_action_date', 'serial_number', 'status_text') search_fields = ( 'first_name', 'last_name', 'account_handler__first_name', 'account_handler__last_name', 'sub_organization_name', 'organization_name', 'next_action_date', 'serial_number', 'status_text') pagination_class … -
Counting rows from each day from last 60 days
I would like to count rows from each day from last 60 days and return this as list. models.py class Error(models.Model): name = models.CharField(max_length=250) adding_time = models.DateTimeField(auto_now=True) In database I have: name | adding_time ------------------------------------ error_1 | 2017-04-10 10:47:33.204518 error_2 | 2017-04-10 11:01:12.339936 error_3 | 2017-04-21 08:40:56.862731 error_4 | 2017-04-21 08:45:50.235212 What I would like to achieve is list of dates and counted rows in that day: [{'count': 2, 'adding_date': '2017-04-10'}, {'count': 2, 'adding_date': '2017-04-21'}] So far, I have done someting like this: last_30_days_errors = Error.filter(adding_time__lte=datetime.datetime.today(),adding_time__gt=datetime.datetime.today()-datetime.timedelta(days=60)) errors_dates = last_30_days_errors.extra({'adding_date': 'date(adding_time)'}).values('adding_date') It is returning: >>> [{'count': 1, 'adding_date': '2017-04-10'}, {'count': 1, 'adding_date': '2017-04-10'}, {'count': 1, 'adding_date': '2017-04-21'}, {'count': 1, 'adding_date': '2017-04-21'}] I can parse it, but is there any method to do it by a query? Thank you. -
Create Django project with Visual Studio Community 2017 (Mac)
I downloaded the new Visual Studio 2017 for Mac (community) version in order to write my Django project inside. Up to now, I didn't find any solution in order to add Python and/or Django extensions. For example, I have a directory on my Desktop with my Django project, but it's not possible to load this directory as a new project. There is an existing solution ? Thank you -
Download Images from CSV column to Django ImageField
I am building a rest api in drf, which will serve images, the data is imported from a csv file and it is not so reliable and subject to change, the last column contains the image urls and i need to cache the images locally. Since I am using ImageField model in django, i need to save these images to the database, as well as the respective title and description. I am stuck on this part -- download image, populate filename and img_raw_data variables response.content returns a binary blob of the image and the ImageField expects a valid image, I am just hitting a roadblock here. This is my sample csv data title description image Item 1 Description 1 http://www.imgur.com/784/77987987.jpg Item 2 Description 2 http://www.image.com/images/797-oijio.jpg Item 3 Description 3 https://www.google.com/logo.jpg this is my image model, class Image(BaseModel): title = models.CharField(max_length=200, unique=True) description = models.CharField(max_length=400, null=True, blank=True) image = models.ImageField(null=True, blank=True) class Meta: db_table = 'images' def __str__(self): return self.title This is my code, currently I am stuck on download image, populate filename and img_raw_data variables import csv import validators from django.core.management.base import BaseCommand import requests from images.models import Image def get_image_content(url): resp = requests.get(url) if resp.status_code == 200: return resp.content … -
Implementing automated tool through django based website
I would like to implement an automated python tool in website with django framework. I know the directory structure. But in our automation tool there are so many methods. And when we will write views.py other web related functions will come into. So what will be the best practice to keep those functions to great better readability? Inside views.py of my app Keeping tool related functions in another .py module and importing them in views.py accordingly. If any other way please suggest. -
correct way to use auth.permission as a foreign key
class Designation(models.Model): name = models.CharField(max_length=100) blog = models.ForeignKey('Blog') permission = models.ManyToManyField(Permission) class Blog(model): name class BlogContributors(model): user = model.ForeingKey(User) designation = models.ManyToManyField(Designation) Each blog have there own designation e.g. blog 1 have writer, seo , billing manager blog 2 have comment moderator, writer, e.t.c permission on blog 1 writer may vary with blog 2 writer and each user can have more than one designation for a blog. What is the best way to achieve it ? -
How to prevent race condition in Django on INSERT with limiting SUM?
Consider two models: Project: id: An AutoField primary key budget: A PositiveIntegerField some unrelated fields Expense id: An AutoField primary key amount: A PositiveIntegerField project: A ForeignKey to Project some unrelated fields For each project, I wish to ensure that the sum of their expenses is less than or equal to the budget at all times. In SQL terms: SELECT SUM(amount) FROM expense WHERE project_id = ?; should always be less than or equal SELECT budget FROM project WHERE id = ?; Is there any way to do this in Django, keeping in mind that multiple people may be accessing the web server and creating Expenses at the same time? I am using postgresql as my database backend. I have tried using select_for_update but that doesn't prevent INSERTs from taking place and it doesn't seem to work on aggregations anyway. I was considering saveing the Expense to the database first, then query the total cost and remove the Expense if it's over-budget but then I would need that code to be outside of a transaction so that other threads can see it and then if the server stops mid-processing, the data could be left in an invalid state. -
Crispy form render
I have a manytomany object in a model form which I want to be rendered as select fields under each other, but whatever I try, i keep getting them next to each other with crispy django forms class ContactForm(forms.ModelForm): choice = forms.ModelMultipleChoiceField(label=_('Request'), widget=forms.CheckboxSelectMultiple(),required=False, queryset=ContactFormChoices.objects.all()) name = forms.CharField(label=_('Name')) email = forms.EmailField(required=False, label=_('E-mail')) phone_number = forms.CharField(required=False, label=_('Phone number')) message = forms.CharField( widget=forms.Textarea , label=_('Message')) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Field('name', css_class='input-xlarge'), Field('email', css_class='input-xlarge'), Field('phone_number', css_class='input-xlarge'), Field('message', rows="3", css_class='input-xlarge'), #'choice', Field('choice'), FormActions( Submit('submit', _('Submit'), css_class="btn-primary") ) ) class Meta: model = ContactData fields = ['name','message','email','phone_number','choice'] and the model: class ContactFormChoices(models.Model): ''' The contact form options to show ''' text = models.CharField(max_length=256) active = models.BooleanField(default=True) def __unicode__(self): return self.text class ContactData(models.Model): ''' The contact data (when customer fills in the contact form, this is mailed and saved here ''' name = models.CharField(max_length=256,help_text=_("Name")) phone_number= models.CharField(max_length=256,null=True,blank=True,default=None) email = models.EmailField(max_length=256,null=True,blank=True,default=None) choice = models.ManyToManyField(ContactFormChoices,blank=True,default=None) message = models.TextField() def __unicode__(self): return self.name it looks like this: Anybody any suggestion? -
How to get the date format of the current language in the template?
I've found tons of links but they all ask for date formatting. I dont want date formatting, I want the format of the current language. And not the settings.LANGUAGE_CODE, but the one of the current request (I dont get why a lot of answers are based on the settings.LANGUAGE_CODE because if the user wants to change the language, using settings.LANGUAGE_CODE wont change the formatting...). The only solution I've found so far is to make my own custom tag for my template, like this: @register.filter(name='locale_date_format') def locale_date_format(arg1): """ Returns the date format of the current locale Use: {{ request|locale_date_format }} Args: arg1: request """ # a will contain something like '%m/d%/%y' -> convert it for dateselector a = formats.get_format('DATE_INPUT_FORMATS', lang=arg1.LANGUAGE_CODE)[1] for old, new in [('%y', 'YYYY'), ('%Y', 'YYYY'), ('%d', 'DD'), ('%m', 'MM'), ]: a = a.replace(old, new) return a And then to call it like that: {% load static i18n compress templates_extras %} <html> <head> <script> var globDateFormat = '{{ request|locale_date_format }}'; </script> </head> </html> And then I use it in the jQuery datetimepicker. IMHO it's like taking a sledgehammer to crack a nut. Is there any other way I didn't find?