Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Execute only if finance.pay_amount is empy
Here is the model FinancialProfile @python_2_unicode_compatible class FinancialProfile(models.Model): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='financialprofile') income_source = models.CharField(_('Income source'), max_length=20, choices=settings.LOANWOLF_INCOME_SOURCE_CHOICES, default='employed') had_bankruptcy = models.BooleanField(_('Had bankruptcy'), default=False) bankruptcy_date = models.DateField(_('Bankruptcy date'), blank=True, null=True) had_consumer_proposal = models.BooleanField(_('Had consumer proposal'), default=False) consumer_proposal_date = models.DateField(_('Consumer proposal date'), blank=True, null=True) bank = models.CharField(_('Bank'), max_length=10, choices=settings.LOANWOLF_BANK_CHOICES) bank_transit = models.CharField(_('Bank transit'), max_length=5, blank=True, null=True) bank_account = models.CharField(_('Bank account'), max_length=10, blank=True, null=True) bank_other = models.CharField(_('Other Bank'), max_length=10, blank=True, null=True) pay_frequency = models.CharField(_('Pay frequency'), max_length=50, choices=settings.LOANWOLF_PAY_FREQUENCY_CHOICES, default='2weeks') pay_amount = models.DecimalField(_('Monthly pay amount'), decimal_places=2, max_digits=11, blank=True, null=True) and another model from requirements.py, class ValidationRequirements(BaseRequirement): label = _('Validation') states = ['validation', 'evaluation', 'signature', 'deposit'] invalidates = ['evaluation', 'signature'] def is_income_valid(self): is_valid = True finances = self.user.customerprofile.financialprofile if not finances.pay_amount: is_valid = False self.conditions.append( {'is_valid': is_valid, 'label': '%s' % _('Monthly pay amount is not defined')}) else: self.conditions.append( {'is_valid': is_valid, 'label': '%s' % _('Monthly pay amount is defined')}) return is_valid Actually, finances.pay_amount is equal to Decimal('0.00'). I would like to tell the method is_income_valid, if finances.pay_amount is empty then apply the content inside the if condition. Actually, it is zero, and I don't know why it is apply. How could I modify this function in such a way it will do what I … -
Django how to allow usage of empty ranges in IntegerRangeField
I`m using IntegerRangeField (specific field for PostgreSQL) to represent year periods when a bancnote was issued. Works fine when adding object to db and filtering with non-empty ranges such as 1990-2000, however there are few bancnotes, which were issued during only one year, so the period is for example 2005-2005. When setting range like this, this value becomes as 'None-None' after object adding to db. Seems like IntegerRangeField doesn`t accept empty ranges. I was trying to set range like '2005-(no value here)' with blank=True, null=True, this is fine for me, but in this case filters not working for this object. To be more clear look at the example below: 2003-2008: displayed and filtered correctly 2003-2003: displayed as 'None-None', filtered wrongly 2003-(no value)/(no value)-2003: dislayed as '2003-None'/'None-2003'(satisfactorily for me), filters doesn`t work this Also was thinking about using DateRangeField, but it provides day and month at the same time as input, what makes a mess. Are there any other possible and correct ways to do this? Hope I was clear with my situation, looking forward for any advice. Please feel free to ask, I will provide any information. Thanks in advance! Here is my models.py from django.contrib.postgres.fields import IntegerRangeField from django.core.validators … -
Django datepicker not working?
I am trying to implement a datepicker in a user profile page, but it is not presenting the datepicker when I click on the textfield. Any thoughts? class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('birth_date', ) widgets = { 'birth_date': forms.DateInput(attrs={'class': 'form-control'}), } -
Is there a gunicorn configuration parameter governing request size?
I'm looking to see if there's a gunicorn setting which governs request size. I'm running an nginx webserver which takes particularly large (potentially hundreds of megs) files and then passes them on to Django via Gunicorn. I've updated my nginx settings so that it can handle these large requests, however it seems that these large requests aren't being properly passed to gunicorn (if I upload a small file, it works, if I upload a large file, it fails silently) I do see some request size options for gunicorn, but I'm not sure which one is THE one and I don't want to be just throwing around updated configs willy nilly. -
How to prevent caching of a Sum?
I'm trying to pass a Sum to my ListView. But if I add more to the DB the Sum does not change until I restart Apache. The new objects are appearing in the List. What am I missing? It seems to get cached for some reason. class ReceiptListView(ListView): model = Receipt total_amount = Receipt.objects.all().aggregate(Sum('amount')) extra_context = {"total_amount":total_amount["amount__sum"],} def get_context_data(self, **kwargs): context = super(ReceiptListView, self).get_context_data(**kwargs) context.update(self.extra_context) return context -
How to do AJAX in Django CMS Admin
I have 2 models in Django CMS - a Map (which has name and an image attributes), and a Location, which one of it's attributes is a Map. I want, when the user changes the Map, to perform an AJAX request to get the map details for that item so that I can add the Map image to the page to do some further jQuery processing with it. But I'm new to Django and I can't seem to figure it out. Anything I find seems unrelated - in that it talks about using AJAX on front end forms. I have my jQuery file ready to go but I don't know what to put for the URL of the AJAX call and how/where to set up the endpoint in Django. -
how to determine which link in django template is causing NoReverseMatch error
I have hundreds of reverse links in my template that looking like this: {% 'tracking:area' pk='1' %} On one of them there is an invalid reference and I get the error: Reverse for 'area' with arguments '()' and keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: [u'tracking/area/(?P\d+)/$'] How can I figure out which one is causing the problem from the hundreds in the template? -
Django Models: Creating Subtypes
I am new to Django and am working through some models on a project right now. Is there a decent way to set the following up? Using a model that ties to the auth_user model (UserAccount), I prompt users to select the type of account they have (Ex: Vendor or Buyer). This part works fine... but I want to build the site experience based off of their account type. How would I create VendorProfile or BuyerProfile models (with differing data) based upon that option? I might be over analyzing this, but basically I do not want any profiles to be linked to both types of data. Is that something I should just control with views, or is there a good way to lock my models and prevent duplicate information? Let me know if you think this is too broad, but I'm still on the conceptual level. So: auth_user model UserAccount model: user: one to one (User) account_type: 'V' or 'B' VendorProfile(?) user: one to one (UserAccount where type='v')? company name: vendor code: BuyerProfile(?) user: one to one (UserAccount where type='b')? favorite color: pet's name: -
Unable to install virtualenvwrapper on mac
I am trying to run Django on python 3.6.1 according to this website. So i first installed virtualenv using pip install virtualenvwrapper But this gives me an error: copying build/lib/clonevirtualenv.py -> /Library/Python/2.7/site-packages error: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/clonevirtualenv.py' I tried skipping this step and tried the command source .bashrc which again gave me an error saying "file not found": -bash: /usr/local/bin/virtualenvwrapper.sh: No such file or directory (I checked my home directory but it was there). How can I fix this? -
develop django python app for multiple clients simultaneously
I'm developing a web crawler in python using Django framework. i want it to work like a web-app. Means if I open in two different browser tabs, they should work individually, each having its own data (crawled + queued links). Both of them should start crawling from separate URL and continue their work. currently i have designed very simple version of it. it is working in one tab, does not work in another browser tab. I have even tried opening a new window of chrome but same results. I'm not sure what feature or library i should use for that purpose. can somebody help me? -
How to apply an upgrade python package whithout stop Django server?
I have a Django Server that uses a X package, these package i upgrade daily. I don’t want to Stop my Django instance every day when the package was updated. I have a Cron daily to Upgrade the Package (Pip package -U), but the Django doesn’t use the latest version upgrated. Thanks -
Django: Trunc datetime results in none
I have the following model: class Statistic(models.Model): meter = models.ForeignKey(Meter, on_delete=models.CASCADE, db_index=True) timestamp_start = models.DateTimeField(db_index=True) timestamp_end = models.DateTimeField(db_index=True) usage_start = models.DecimalField(max_digits=10, decimal_places=3) usage_end = models.DecimalField(max_digits=10, decimal_places=3) return_start = models.DecimalField(max_digits=10, decimal_places=3) return_end = models.DecimalField(max_digits=10, decimal_places=3) I have some data in there all filled in with timestamps. But when I run the following query: statistics = Statistic.objects .annotate(timestamp=Trunc('timestamp_start','day', output_field=DateTimeField())) .values('timestamp') .annotate(usage_start = Min('usage_start')) timestamp results in None QuerySet [{'usage_start': Decimal('136.972'), 'timestamp': None}] When I attach the debugger and check the first records of my statistics table like this Statistics.objects.all()[0].timestamp_start it returns: datetime.datetime(2016, 12, 22, 6, 0) Am I missing something here? Python 3, Django, Sql lite database -
Django Auth Additional Validation
I need compare a boolean variable when i do login (variable name: aproved) If variable is true: login success; else login error; I have variable stored in database. My form: class LoginForm(AuthenticationForm): username (...) password (...) Urls: url(r'^login/$', auth_views.login, {'authentication_form': LoginForm}, name='login'), Views: def login(request): return render(request, 'registration/login.html') How to change default login to allow this? -
URLS Django not working
I am trying to create a user form and then post the input to the database model.However I keep getting this error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hiresite/Recruiter Using the URLconf defined in recruitment.urls, Django tried these URL patterns, in this order: ^hiresite ^$ [name='index'] ^hiresite ^Recruiter$ [name='Recruiter'] ^admin/ The current URL, hiresite/Recruiter, didn't match any of these. I am a bit confused because I can see the url Recruiter above and yet I get the error message.Your help would be much appreciated . 1.Here is my Urls.py for the app from django .conf.urls import url from. import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^Recruiter$', views.Recruiter, name='Recruiter') ] 2.Here is my Urls.py for the Project from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^hiresite', include('hiresite.urls')), url(r'^admin/', admin.site.urls), ] 3.Here is the view for the Url Recruiter def Recruiter(request): if request.method == 'POST': form = register_job(request.POST) if form.is_valid(): title = request.POST.get('title', ' ') description = request.POST.get('description', ' ') salary = request.POST.get('salary', ' ') reference = request.POST.get('reference', ' ') user_obj = jobsearch(title=title, description=description, salary=salary, reference=reference) user_obj.save() return render(request, 'hiresite/Recruiter.html', {'user_obj ': user_obj, 'is_registered': True}) else: form = register_job() return render(request, 'hiresite/Recruiter.html', {'form': … -
Inter app model import in Django
I'm struggling with inter app model importing in Django I've had a look at others who have asked the same sort of question and the answers have not satisfied my problem my file structure is: welted_website -cart --views -shop --models I'm trying to import Product from my shop.models into cart.views but to no avail! I've tried from ..shop.models import Product from welted_website.shop.models import Product The second of which gave me the following: ValueError: Attempted relative import beyond toplevel package My apps contain __init__.py files by default -
Python package for handling email providers to authenticate and get contacts
Is there any python packages for handling email providers to authenticate and get contacts from various providers like google, yahoo, rediffmail, zoho etc. Django-allauth only provides authentication and that too not with any email providers except google. Am I missing out Something. My aim is to allow users to connect their different mailing accounts in order to allow them to invite friends and email connections. -
django rest framework nested relationship serializers is not passing related data to the create() method
I have a model related to another model with a m2m+through table. I am having trouble accessing the data of the related models via either the serializer.create() method or the viewset.perform_create() method Jump to line #45 for the first problem Jump to line #10 for the 2nd problem (my attempt at solving the 1st problem) https://gist.github.com/guyjacks/cecd1dfad1323a4be8a27099ea3e90c0 -
Django- How to make a dynamic template with ManyToManyField in model
I'm new to Django. I'm trying to figure out how to get the tags property of MyModel (manytomany) onto the template (mytemplate.html) for each object in MyModel. Note: there are 4 possible tags in the Tags admin. Some of the objects from MyModel have 2 tags, some have 1. How do I get each object's unique selection of tags onto my template? Here are my files: models.py class Tag(models.Model): CATEGORY_CHOICES = ( ('dataset', 'dataset'), ('brand', 'brand'), ) tag = models.CharField(max_length=100) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) class MyModel(models.Model): id = models.CharField(max_length=30, primary_key=True) publish_date = models.DateField() tags = models.ManyToManyField(Tag) views.py from .models import MyModel, Tag def index(request): tags = Tag.objects.all() infos = MyModel.objects.all().order_by('publish_date').reverse() return render(request, 'mytemplate.html', {'infos': infos, 'tags':tags}) mytemplate.html Right now this just creates 4 p elements- one for all 4 possible 'tags' {% for info in infos %} <small>{{info.publish_date}}</small> {% for tag in tags %} <p>{{tag.tag}}</p> {% endfor %} {% endfor %} -
Django faster loading of form
I have a model named Title, which contains some ForeignKey fields: class Title(models.Model): name = models.CharField(max_length=120) department = models.ForeignKey('Department') rank = models.ForeignKey('Title_rank') I have a form that has parameter choices set to all of the Title entries: class Emp_titleForm(forms.Form): title = forms.MultipleChoiceField( choices=( (x.id, x.name) for x in Titles.objects.all() ), widget=forms.SelectMultiple(), required=True, ) The page loads fine but is slow (~6-10sec) from (I assume) there being many objects in the Title class (currently ~5,000). Is there anyway to adjust my form or model to speed up page load? Unfortunately, filtering to reduce choices is not an option. -
In Django Rest Framework, adding obtain_jwt_token to my URLs causes all of my other endpoints to disappear from the docs
I'm using Django Rest Framework, and for authentication, I'm using Rest Framework JWT Auth. It says in their docs that url(r'^api-token-auth/', obtain_jwt_token) should be added to an application's URLconf in order to add an endpoint for obtaining an authentication token. I'm also using Django Rest Framework's automatically-generated docs, which can be read at localhost:8000/docs. All of my API endpoints are listed on that page. However, when I add the login URL to my URLconf as described above, all of my documentation disappears, and in its place, there is a single endpoint listed: the api-token-auth endpoint. What could be causing all my documentation to disappear? How can I get the login endpoint to coexist with all the others? -
Django + IIS + Wfastcgi read error
I was setting up all paths in my web.config file and configuring everything in IIS (on Windows Server 2012 R2). When I was done I started the server and accessed the website. But while doing so I got this following error message: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\inetpub\wwwroot\djangoapp\wfastcgi.py", line 711, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\inetpub\wwwroot\djangoapp\wfastcgi.py", line 568, in read_wsgi_handler return env, get_wsgi_handler(handler_name) File "C:\inetpub\wwwroot\djangoapp\wfastcgi.py", line 551, in get_wsgi_handler raise ValueError('"%s" could not be imported' % handler_name) ValueError: "django.core.wsgi.get_wsgi_application()" could not be imported StdOut: StdErr: Web.config (file): <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python34\python.exe|C:\inetpub\wwwroot\djangoapp\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="C:\Python34\python.exe" /> <add key="WSGI_RESTART_FILE_REGEX" value=".*((\.py)|(\.config))$" /> <add key="DJANGO_SETTINGS_MODULE" value="djangoapp.settings" /> </appSettings> </configuration> I don't understand why this error occurs. Does anyone has a clue how to solve this or help. Thanks for reading. -
Import my django model to excel
I have 7 models in my app.I want to export all the models in one single excel sheet.What should I do? I tried, but i can export only one model at a time not all. -
Django POST dict empty, use simple html form
I am use Django 1.8 and Python 3.5.2, and try recive POST data from simple html form <form action="/shop/order" method="POST"> {% csrf_token %} <input type="hidden" name="product-code" value="{{ product.product_code }}"> <input type="text" name="email"> <input type="submit"> </form> It view where I try get need for me data, but QueryDict empty for POST, when I change POST to GET in form and view all work. def order_product(request): test = request.POST.get('product-code', '') mail = request.POST.get('email', '') # logger.info(test) return render(request, 'shop/test.html', dict(test=test, email=mail)) And I'am not understand why is that. Similarly I try parse(decode binary to utf-8 etc) body and I recive empty string. urls.py url(r'^order/?$', views.order_product), -
Django Rest Framework Multiple Serializers for One Model
I'm trying to create two endpoints -- one to write and one to list(read only), but I'm getting an error message "type object 'Model1' has no attribute 'objects'". class Model1(models.Model): test = models.CharField(max_length=10, unique=True) test_name = models.CharField(max_length=250) desc = models.TextField() country_name = models.ForeignKey(Model2, related_name="country") class Model2(models.Model): country = models.CharField(max_length=10, unique=True) class WriteSerializer(serializers.ModelSerializer): class Meta: model = Model1 fields = ('test', 'test_name', 'desc', 'country') class ReadOnlySerializer(serializers.ModelSerializer): country_name = serializers.RelatedField(source='country', read_only=True) class Meta: model = Model1 fields = ('test', 'test_name', 'desc', 'country_name') -
How to test a Django view which has transaction.atomic(using=myDb)?
I am trying to test a django view that includes a transaction; in particular, I specify which db I want to use by transaction.atomic(using=myDb). However, when I run my test I get django.db.utils.ConnectionDoesNotExist: The connection myDb doesn't exist. Is there any way to test the view given that I'm not hitting myDb in the test? Thanks for your help!