Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Filtering against the URL with Format suffixes
I would like to use format suffixes within a filtered endpoint, like so: http://localhost:8000/retailers/1/ads.json Format suffixes - http://www.django-rest-framework.org/api-guide/format-suffixes/ Filtering against the URL - http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-url I'm using Routers and ModelViewSets urls.py looks like this: # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'retailers', views.RetailerViewSet) router.register(r'templates', views.TemplateViewSet) router.register(r'sizes', views.SizeViewSet) router.register(r'products', views.ProductViewSet) router.register(r'ads', views.AdViewSet) router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^retailers/(?P<retailer>.+)/ads/$', views.AdViewSet.as_view( { 'get': 'list', 'post': 'create' } )), url(r'^retailers/(?P<retailer>.+)/templates/$', views.TemplateViewSet.as_view({'get': 'list'})), url(r'^retailers/(?P<product>.+)/products/$', views.ProductViewSet.as_view({'get': 'list'})), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Example ModelViewSet: class AdViewSet(viewsets.ModelViewSet): queryset = Ad.objects.all() serializer_class = AdSerializer def get_queryset(self): if 'retailer' in self.kwargs: retailer = self.kwargs['retailer'] return self.queryset.filter(retailerId=retailer) return self.queryset Any ideas? -
NameError: name '' is not defined
I want to have a view in which I could add new contacts in the model "contacts" that I created. Here are some lines of code that are concerned views.py: def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): sujet = form.cleaned_data['sujet'] message = form.cleaned_data['message'] envoyeur = form.cleaned_data['envoyeur'] renvoi = form.cleaned_data['renvoi'] envoi = True return render(request, 'blog/contact.html', locals()) def nouveau_contact(request): sauvegarde = False form = NouveauContactForm(request.POST or None, request.FILES) if form.is_valid(): contact = Contact() contact.nom = form.cleaned_data["nom"] contact.adresse = form.cleaned_data["adresse"] contact.photo = form.cleaned_data["photo"] contact.save() sauvegarde = True return render(request, 'blog/newcontact.html', { 'form': form, 'sauvegarde': sauvegarde }) forms.py: class ContactForm(forms.Form): sujet = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) envoyeur = forms.EmailField(label="Votre adresse mail") class NouveauContactForm(forms.Form): nom = forms.CharField() adresse = forms.CharField(widget=forms.Textarea) photo = forms.ImageField() forms.py: class Contact(models.Model): nom = models.CharField(max_length=255) adresse = models.TextField() photo = models.ImageField(upload_to="photos/") def __str__(self): return self.nom The error message tells me that "" NewContactForm "" is not defined this is the ERROR_MESSAGE -
Angular RouteProvider always hits '/' first
I have an Angular/Django application where on the front end, I have several url routes using Angular's routeProvider to navigate the user to different controllers/templates. I thought this might be like Django's url configuration where it serializes down the list looking for a match, but in this case it seems like no matter what route I go to, it always has to hit '/' first, which goes to my home controller, and redirects the user to the sign in page if they're not logged in. This is actually good since a user shouldn't have the ability to get into the site without logging in, besides one exception. There is a reset password route that a user goes to through a link they receive in an email as soon as they tell us they forgot their password. Whenever they get the link and try and change their password, it hits that home controller and redirects them, even though the reset password route is above the home route. First few routes of angular app configuration app.config(function ($routeProvider) { $routeProvider.when('/reset_password/:user/:reset_code', { templateUrl: 'views/reset-password.html', reloadOnSearch: false, controller: 'resetPassword' }); $routeProvider.when('/', { templateUrl: 'views/home.html', reloadOnSearch: false, controller: 'home' }); $routeProvider.when('/_=_', { // needed for facebook … -
Display a pdf in object/embed django
Hi the problem i have is that i have a carpet that contains pdf files. I need to show this pdf files in a django template and i dont know what im doing wrong. templates and pdf containers are at the same level <body> <object data="ea_Junio_2017.pdf" type="application/pdf" title="SamplePdf" width="500" height="720"> <embed src="ea_Junio_2017.pdf" > </object> <body> The problem is that the program can't get the file and drops me this error "GET /pdf/ea_Junio_2017.pdf HTTP/1.1" 404 2778" There is something that im doing wrong? -
Unicode exception in Django template
I have Django application that has unicode characters read from DB and they to be displayed as it is on the template. here is what i tried in views and my template: # -*- coding: utf-8 -*- from .models import keywords as m def newdata(request): keywords = m.objects.all() template = loader.get_template('keywords.html') context = Context({ 'keywords': keywords, }) #return HttpResponse(template.render(context)) #return HttpResponse(meanings) return render(request, 'keywords.html',context) I am trying to use the keywords from the database in a select list in my template using a js function like below <html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </html> <select id="keyword1" name="keyword1" onChange="add_to_text1();"> <option value="" selected="selected">---SELECT---</option> {% for post in keywords %} <!-- here keyword has unicode strings --> <option value="{{post.id}}">{{post.keyword}}</option> {% endfor %} </select> <input type="hidden" name="key1" value='' id='key1'/> function add_to_text1() { var e = document.getElementById("keyword1"); var str = e.options[e.selectedIndex].text; var selected_keyword_id=e.options[e.selectedIndex].value; document.getElementById("key1").value = selected_keyword_id; "{% for each in keywords %}" var x="{{ each }}"; var other_form=x.split(" - ")[0]; var el=other_form+"({{ each.id }})" var opt = document.createElement('option'); opt.value = "{{each.id}}"; opt.innerHTML = el; select.appendChild(opt); "{% endfor %}" } This is the error i get when i try to open the tempalte page Exception Value: 'ascii' codec can't encode character u'\xe9' in position 4: ordinal … -
Django admin style from a custom folder
I am running Django 1.7.11 on my production server, and i cant make the admin theme to work. The default would be good for me as well. The theme is not stored on the server, so i uploaded admin directory from my computer to the production servers template folder So basically i copied: /usr/local/lib/python2.7/dist-packages/django/contrib/admin To my production servers appname/templates/admin After as i read in some topics here i changed my settings.py with the following: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And also added: STATIC_ROOT = '' STATIC_URL = '/templates/' It works perfectly on my computer, and as i see it reads the info from the templates directory, however on the production server i still dont see the CSS. How can i make it work? -
Django OneToMany Field with predefined Models
I'd like to make a OneToMany-relationship between one of my models and the Permission model of django.contrib.auth.models. My plan is to create at least one new permission when my model is created and delete this/these permissions when the model is deleted. When it comes to Many-to-one relations the documentation recommends using a ForeignKey (https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_one/). But if I get this right, I would need (theoretically) to add a ForeignKey to the Permission model. Am I on the wrong way? What would be the best practice to implement this? -
Should I always use virtualenvs in Django?
I'm a beginner,and I'm learning Django for web developpement. So I want to know for my little test, should in always have a virtualenv or can I continue to learn without installing it? I've asked because in youtube Django videos, some instructors are installing it, and others aren't. -
NoReverseMatch at /music/ 'music' is not a registered namespace
Error during template rendering In template C:\Users\Pranay\Desktop\website\music\templates\music\index.html, error at line 5 'music' is not a registered namespace this is the template code with the error: {% if all_albums %} <h3>here are all my albums</h3> <ul> {% for album in all_albums %} <li><a href="{% url 'music:detail' album.id %}">{{ album.album_title }}</a></li> {% endfor %} </ul> {% else %} <h3>you dont have any albums</h3> {% endif %} -
Simple workflow management in python which must be easily customizable
Me as super admin, then admin users and list of clients & contacts. work flow is the main point being able to create steps, assign them, track them, notifications based upon timed events etc. standard workflow engine things, work with several APIs (twilio, smtp, paypal, etc) so basically looking for workflow system, an existing open-source product which we can customize and make changes I see existing tools(airbnb airflow python system and django-viewflow not sure it serve the purpose) and think they can be modified and other times the modification seems so tough that just doing custom is better. Python Django preferred, but not necessary. Any advice on what should I use? Thanks in Advance. -
Django Haystack. And, or in search queryset
Using: Haystack and Sorl. I need to make a search queryset to search products by filter. Firstly, I need to filter only products based on my site (Django site framework). So I do: sqs = sqs.filter(site=site.pk) It returns such search query: site:(6) OK. Then I need to filter by attributes: sqs = sqs.filter(attribute_codes='power', attribute_values__range=(20, 30)) sqs = sqs.filter(attribute_codes='power', attribute_values__range=(40, 50)) And it generates such query: (site:(6) AND attribute_codes:(power) AND attribute_values:(["20" TO "30"]) AND attribute_values:(["40" TO "50"])) But, I need to make a query like this: (site=6) AND ((attributes1) OR (attributes2)) So I tried to change filtering by attributes to filter_or: sqs = sqs.filter_or(attribute_codes='power', attribute_values__range=(20, 30)) sqs = sqs.filter_or(attribute_codes='power', attribute_values__range=(40, 50)) And the result is: (site:(6) OR (attribute_codes:(power) AND attribute_values:(["20" TO "30"])) OR (attribute_codes:(power) AND attribute_values:(["40" TO "50"]))) But I need else: (site=6) AND ((attributes1) OR (attributes2)) So, how to do this? Help me, please -
"no such table" with multiple database on Django 1.11.1
im facing a problem with multiple database with Django 1.11.1. I allwas recive: OperationalError at /admin/news/article/ no such table: news_article when i klick "Artikel" on the Admin-page. My project contains two database, one for recipies, one for a RSS newsfeed. I defined them like this in the settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, '..', 'cookbook.db'), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, 'news_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, '..', 'news.db'), }, } I also added a router in routers.py: class CookbookRouter(object): """ A router to control all database operations on models in the cookbook site. """ def db_for_read(self, model, **hints): if model._meta.app_label == 'news': return 'news_db' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'news': return 'news_db' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'news' or \ obj2._meta.app_label == 'news': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'news': return db == 'news_db' return None And i set it up like this in settings.py: DATABASE_ROUTERS = ['cookbook.routers.CookbookRouter'] My news.model.py looks like this: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from basemodels import DateTimeInfo # Create your models here. class … -
Can any one please help looping in django templates?
{% for dispN0, tableDataSet0 in tabulatedTable.items %} {% for dispN in orderChanels %} {% for antenaName, antenaLevel in tableDataSet0.{{dispN}}.items %} <td>{{antenaName}}</td> {% endfor %} {% endfor %} {% endfor %} here {{dispN}} is integers numbers will come..like 36,42..etc if i give tableDataSet0.36.items its working fine. but i need multiples in the place 36 can any one help on this. -
How to get the values from a ManyToMany field in a custom user?
app.models.py: BANKS = { '1': 'bank1', '76': 'bank2', '': 'bank3', '724': 'bank4', } class Bank(db_models.Model): BANK_CHOICES = tuple((int(code), BANKS[code]) for code in BANKS if code != '') code = db_models.IntegerField( 'Bank Code', choices=BANK_CHOICES, blank=True, ) class User(AbstractUser): objects = UserManager() banks = models.ManyToManyField(Bank) I can create and add banks to the user in the browser but can't get the banks of the user to show in the settings page. So I've tried to get these values in the django shell and what I get is an empty QuerySet. In this example I've created the user 'testuser' and added the bank 76 via browser. I can get what users have a specific bank but can't get all banks from a user: >>> import django >>> from app import models >>> models.User.objects.get(banks=76) <User: testuser> >>> user = models.User.objects.get(username='testuser') >>> user.banks.all() <QuerySet []> -
Setting up django parallel test in setting.py
Hello I know that it's possible to run tests in django in parallel via --parallel flag eg. python manage.py test --parallel 10. It really speeds up testing in project I'm working for, what is really nice. But Developers in company shares different hardware setups. So ideally I would like to put parallel argument in ./app_name/settings.py so every developer would use at least 4 threads in testing or number of cores provided by multiprocessing lib. I know that I can make another script let's say run_test.py in which I make use of --parallel, but I would love to make parallel testing 'invisible'. To sum up - my question is: Can I put number of parallel test runs in settings of django app? And if answer is yes. There is second question - Would command line argument (X) manage.py --parallel X override settings from './app_name/settings' Any help is much appreciated. -
get output from python script to django
I'm looking for get the outputs from a python script to my django web server. I will use pySmartDL in my script, so i need it to run even when django close itself and django needs to get data from a running script when it start-up. pySmartDL exemple script : import time from pySmartDL import SmartDL url_100mb_file = ['http://ipv4.download.thinkbroadband.com/100MB.zip'] obj = SmartDL(url_100mb_file, progress_bar=False) obj.start(blocking=False) while not obj.isFinished(): print("Speed: %s" % obj.get_speed(human=True)) print("Already downloaded: %s" % obj.get_dl_size(human=True)) print("Eta: %s" % obj.get_eta(human=True)) print("Progress: %d%%" % (obj.get_progress()*100)) print("Progress bar: %s" % obj.get_progress_bar()) print("Status: %s" % obj.get_status()) print("\n"*2+"="*50+"\n"*2) time.sleep(0.2) if obj.isSuccessful(): print("downloaded file to '%s'" % obj.get_dest()) print("download task took %ss" % obj.get_dl_time(human=True)) print("File hashes:") print(" * MD5: %s" % obj.get_data_hash('md5')) print(" * SHA1: %s" % obj.get_data_hash('sha1')) print(" * SHA256: %s" % obj.get_data_hash('sha256')) else: print("There were some errors:") for e in obj.get_errors(): print(str(e)) # Do something with obj.get_dest() As you can see here the script will print output several times while a file is downloading with this : time.sleep(0.2) So i need to get the output dynamically. I found some answer with websocket (with redis and django-channels or django-redis) and nodeJS but i can't find code example for sending the script output to redis … -
Create test-only models within an app part of a larger project
I am looking for a way to create temporary models to test a simple django app part of a larger django project. If it was not of the models I need to test the app, I would just create a "tests" directory within that app, however it does not work since it requires the migrations. I'd like to avoid to: create a sibling test app with the tests in it create another application in another repository and install through pip pollute the database with the test models create the tables manually using SQL I use both sqlite3 and MySQL. Django 1.9.5 What I tried: Create tables manually Django Fake Models does not seem to work -
Validating the type of django queryset related objects parameters
Does django provide a way to validate the model type in django queryset when for example filtering by related objects? Let's say we have the following models: class Person(models.Model): name = models.CharField(max_length=5) class Author(models.Model): name = models.CharField(max_length=25) class Book(models.Model): name = models.CharField(max_length=5) author = models.ForeignKey(Author) And p = Person.objects.all().first() query = Book.objects.filter(author=p) filters all books which auhtor_id is equal to given person_id (p_id), although Book refers to Author, not to Person. Of course this is the responsibility of a programmer to avoid such errors but it's sitll possible. -
Search iwa directory to add users to django admin page
I am trying to use django to create an application that will used across a corporate network. Right now to add a user I have to have them ping the site then go to their user account and click add. What I would like is the ability to click 'search for user' in my admin page and then be able to search for a user in my iwa directory. -
radio buttons display form
I have in my form 3 radio buttons, when i click on each one a form appears and a parameter of my backtesting change. The problem is that when i click on save buttons nothing is saved. Before I added the check of radio buttons the save buttons was working. The click on radio buttons change the strategy of parameters. The error is with the save function when i check the radio buttons but i don't know how to resolve it. Models.py class Parameters(models.Model): MARKET= ((1,'Nasdaq'),(2, 'Nyse'),(3,'Amex'),) SECTOR_CHOICES = ((1,'Utilities'),(2, 'Basic Materials'),(3,'Healthcare'), (4,'Services'),(5,'Financial'),) user = models.ForeignKey(User) title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters') type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest") strategy = models.CharField('Strategy', choices=STRATEGY_CHOICES, max_length=20,default="Long") #input characteristics price_1_min = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)]) price_1_max = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)]) stocks_num_2_min = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)]) stocks_num_2_max = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),]) holding_period = models.IntegerField('3. Holding Period', default=1, validators=[MinValueValidator(1),]) volume = models.IntegerField('4. Volume', default=0, validators=[MinValueValidator(0),]) market = models.CharField('Market', max_length=30, null=True) sector= models.CharField('Sector', max_length=30, null=True) The html where the parameters are saved in a table: {% extends 'base.html' %} {% block … -
Running Python App on a Clean Server
I have a developed Python on Django app pushed to my Github. I am now working on a clean computer. I am trying to find a way to run the app on the new computer after cloning my old code into a repo. Any suggestions? -
django get_available_name() got an unexpected keyword argument 'max_length'
I want to override files with the my django Model. So if I upload 'one' and later upload 'two', 'two' should override 'one' (on the file system). But I get an error. This is my model: class StudentAssignment(models.Model): file0 = models.FileField(upload_to=use_solution_path, storage=OverwriteStorage(), validators=[validate_file_extension]) This is the storage. import os from django.conf import settings from django.core.files.storage import FileSystemStorage class OverwriteStorage(FileSystemStorage): def get_available_name(self, name): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ # If the filename already exists, remove it as if it was a true file system if self.exists(name): os.remove(os.path.join(settings.MEDIA_ROOT, name)) return name The Error: [...] File "/home/mb/.local/lib/python3.5/site-packages/django/db/models/fields/files.py", line 95, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) File "/home/mb/.local/lib/python3.5/site-packages/django/core/files/storage.py", line 53, in save name = self.get_available_name(name, max_length=max_length) TypeError: get_available_name() got an unexpected keyword argument 'max_length' I am new to django and have no idea how to go on. Can someone help? Thanks :) -
How to deploy a Django/WSGI as an azure webapp with a different Python runtime?
I'm trying to deploy a Django webapp on a Microsoft Azure webapp instance (it is a managed Windows VM). The documentation here, https://docs.microsoft.com/en-us/azure/app-service-web/web-sites-python-configure describes how to deploy an application with either Python 2.7 or Python 3.4. I'm trying to deploy an app built with Python 3.6 (not a runtime supported by Azure out-of-box). I installed the runtime using the 'Site Extensions' feature of Azure. Here's the link to the extension (I think), https://www.siteextensions.net/packages/python361x86/ I primarily work on Linux systems using Apache. The difficulty I'm facing here is how to configure IIS on the Azure instance to use Python 3.6 to run my django webapp (it works on my development system using the runserver command). Sadly, I cannot request to use a Linux VM on azure (business constraint). One problem I'm having is how to write the web.config file on the project. The reference Python3.4 one uses a virtualenv which, oddly enough, is explicitly disabled on Python with site extensions ( ref: https://github.com/Azure/azure-python-siteextensions/issues/6 ). Another issue I'm having is that I'd like to use waitress WSGI instead of FastCGI (ref: http://docs.pylonsproject.org/projects/waitress/en/latest/ ). Can someone point me to a web.config + python wsgi script combination which runs on azure using Python 3.6 … -
Django - How to filter a ManyToMany model object?
I have the following models which are linked via a foreign key and ManyToMany relationship. from django.db import models from django.contrib.auth.models import User class AssetMetadata(models.Model): id = models.DecimalField(6).auto_creation_counter material_id = models.CharField(max_length=256, blank=True) series_title = models.CharField(max_length=256, blank=True) season_title = models.CharField(max_length=256, blank=True) season_number = models.IntegerField(default=0) episode_title = models.CharField(max_length=256, blank=True) episode_number = models.IntegerField(default=0) synopsis = models.TextField(max_length=1024, blank=True) ratings = models.CharField(max_length=256, blank=True) def __str__(self): return self.material_id class Batch(models.Model): material_id = models.ManyToManyField(AssetMetadata) user = models.ForeignKey(User, unique=True) def __str__(self): return 'Batch_' + str(self.pk) + '_' + self.user.username I can see that this has worked and the models have been created and the relationships work as you would expect. As you can see from the console output: >>> from asset_db.models import Batch >>> Batch.objects.values() <QuerySet [{'user_id': 1, 'id': 1}, {'user_id': 3, 'id': 2}]> When i migrated the models it created the following tables (added so you can see the relationships). asset_db_batch: id | user_id ____________ 1 | 1 2 | 3 asset_db_batch_material_id: id | batch_id | assetmetadata_id ______|_____________|________________ 1 | 1 | 1 2 | 1 | 2 3 | 1 | 6 4 | 1 | 8 5 | 1 | 4 6 | 2 | 8 7 | 2 | 2 8 | 2 | … -
DRF: Serializer validation while submitting a POST request to detail route
DRF newbie here. I have the following model: class User(models.Model): first_name = models.CharField(max_length=30, null=True, blank=True) last_name = models.CharField(max_length=30, null=True, blank=True) email = models.EmailField(max_length=254, null=False, blank=False, unique=True) password = models.CharField(max_length=128, null=False, blank=False) I've managed to implement POST /users/ successfully. I'm able to validate password and email fields in the request body against pre-defined constraints.(e.g. password cannot be entirely numeric) For this purpose, I override field validators such as validate_password and validate_email. Now I'm trying to implement an endpoint POST /users/pk/password/ through which users will be able to update their password resource. To achieve this I've used detail_route. Below you can find the corresponding implementation: # Custom method to update the password resource of a given user. @detail_route(methods=['post']) def password(self, request, pk=None): try: user = User.objects.get(pk=pk) except User.DoesNotExist: # returns error else: password = request.data.get('password',None) new_password = request.data.get('new_password',None) if password and new_password: if check_password(password,user.password): # Use Django built-in to hash password. password_hash = make_password(new_password) user.password = password_hash user.save() serializer_data = UserSerializer(user).data return Response(serializer_data) else: # return error reponse else: # return error response By using this approach, I'm able to update the password field of a user but validate_password is not effective anymore when POST /users/pk/password/ is called so that users can …