Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSON data not coming through from Django REST API
I have a Django REST API with an Angular Front-end. I am getting no errors on the front-end, but no json data is logging to the console. I have a service like so: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl = 'http://127.0.0.1:8000/weatherstats/weatherdata'; getWeatherData() { return this.http.get(this._WeatherStatsUrl) .map((res:Response) => res.json()); } getWeatherDataRecords() { this.getWeatherData().subscribe(weatherdata => { console.log(weatherdata) }) } } feeding a component like so: import { Component, OnInit } from '@angular/core'; import { WeatherstatsService } from '../weatherstats.service'; @Component({ selector: 'weather-stats', templateUrl: './weather-stats.component.html', styleUrls: ['./weather-stats.component.css'] }) export class WeatherStatsComponent implements OnInit { data: any; constructor(private weatherstatsservice: WeatherstatsService) { } ngOnInit() { console.log(this.weatherstatsservice.getWeatherData().subscribe(data => this.data = data)); } } I am new to both Django and Angular, when I test the API in the browser I get the data I want. What could be happening that means I can't see my json data? (With apologies to people who tried to help on similar issue just now - My brain is exploding with all this new stuff!) -
Django staticfiles images not showing
I worked out how to link my CSS files to my HTML with Django but I can't figure out how to get my images to show in my base.html file. These are my files, and this is how I added images, maybe I'm doing something wrong? pic with all the files and directories first, I made a static directory and then I made two sub-directories, CSS and Images. I put my css files in the css directory and then I put my images where my images directory is. Then I used this piece of code to try to add uptown.jpg as my background in css. header { background-image:linear-gradient(rgba(0, 0, 0, 0.5),rgba(0, 0, 0, 0.5)), url({% static 'static/images/uptown.jpg' %}); height: 65vh; background-size: cover; background-position: center; } But the image never appeared, on my website. I also tried to link it just how I would normally do it in a css file without Django tags but still didn't work. I have everything set up in my settings.py in terms of the staticfiles_dir and all. so I'm not sure what the problem is, so please help. best, thanks! -
python spyne with django to make a rpc api service:Requested resource not found
I recently learned how to use python spyne to build a rpc webservice. I used the examples in the package as a start. But I stuck on always getting a "resource not found " response and can't figure why. Here are the codes simplified from the spyne/example/django the view.py class HelloWorldService(Service): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield 'Hello, %s' % name app = Application([HelloWorldService], 'spyne.examples.django.core', in_protocol=HttpRpc(validator='soft'), out_protocol=Soap11()) hello_world_service = DjangoApplication(app) the urls.py urlpatterns = [ url(r'^hello_world/', hello_world_service) ] I use the url http://localhost:8000/hello_world?name=World&times=4&quot to see the rpc result.But I always got a response which said: ``` <?xml version='1.0' encoding='UTF-8'?> <soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/"> <soap11env:Body> <soap11env:Fault> <faultcode>soap11env:Client.ResourceNotFound</faultcode> <faultstring>Requested resource u'{spyne.examples.django.core}' not found</faultstring> <faultactor></faultactor> </soap11env:Fault> </soap11env:Body> </soap11env:Envelope> ``` environment python: 2.7.12 Django:1.11.7 spyne: 2.13.1 -
about: Django, python's super() on multiple inheritance accessing from parent 1 to parent 2 method when parent 2 isnt on parent's 1 MRO?
Problem regarding using of super() to support cooperative multiple inheritance in a dynamic execution environment. I have attached the jpgs to specify. jpg scanned pages, doubt on django unleashed super method jpg super() MRO chain, doubt on django unleashed super method part 2 main doubt: -- how does super() get to call the version of the method (get_context_data()) found in ListView if the Mixin has no relation whatsoever with ListView itself on its Method Resolution Order? I also have this other question. -- How so it says GCBV (ListView) will have created the Page instance at this point if the mixin is passed as first argument and GCBV listview comes after? references used: code, first snippet https://dju.link/be588e9505/organizer/utils code, second snippet https://dju.link/81321265be/organizer/views.py super() http://www.artima.com/weblogs/viewpost.jsp?thread=236275 https://docs.python.org/3/library/functions.html#super -
Django configuring different databases
I have 2 databases of interest, the basic one and the development one: mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | projectsdb | | projectsdb_dev | +--------------------+ 3 rows in set (0.00 sec) In my django file mysite/mysite/settings.py, my databases are declared this way: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectsdb', 'USER': 'projectsdb', 'PASSWORD': 'notsecure', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } The allowed hosts is: ALLOWED_HOSTS = ['xxx.xx.xxx.xx'] # I replaced it for the example I start the server on the port 8006 which I use for developing: $ python ./manage.py runserver xxx.xx.xxx.xx:8006 And here I modify the production database. I can switch to the dev database replacing the default database name: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectsdb_dev', 'USER': 'projectsdb', 'PASSWORD': 'notsecure', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } And it works fine, the server is interacting with the projectsdb_dev database. However I would like to keep both databases available in the settings file and I saw tutorials setting it up this way: DATABASES = { 'default': {}, 'prod': { … -
400 Bad Request getting data from DJango API with Angular 4
I have a Django RESTAPI with a urls.py like this: from django.contrib import admin from django.conf.urls import url, include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^weatherstats/', include('weatherstats.urls')), ] The API has an app with urls.py like this: from django.conf.urls import url from django.contrib import admin from rest_framework.urlpatterns import format_suffix_patterns from weatherstats import views urlpatterns = [ url(r'^$', views.WeatherData.download_weather_stats_uk), url(r'^england$', views.WeatherData.download_weather_stats_england), url(r'^wales$', views.WeatherData.download_weather_stats_wales), url(r'^scotland$', views.WeatherData.download_weather_stats_scotland), url(r'^weatherdata/', views.WeatherData.as_view()) ] urlpatterns = format_suffix_patterns(urlpatterns) And a serializers.py like this to convert output to json: from rest_framework import serializers from .models import WeatherStatistics class WeatherStatisticsSerializer(serializers.ModelSerializer): class Meta: model = WeatherStatistics fields = '__all__' My Angular4 front-end has a service like this: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl = 'http://127.0.0.1:8000/weatherstats/weatherdata'; getWeatherData() { return this.http.get(this._WeatherStatsUrl) .map((res:Response) => res.json()); } getWeatherDataRecords() { this.getWeatherData().subscribe(weatherdata => { console.log(weatherdata) }) } } which feeds a component like this: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl … -
Integrating pinax-badges in django with a points system
I am having trouble getting pinax-badges to work in my project. I followed the minimal usage example provided by creating a badges.py file in my app: #badges.py from pinax.badges.base import Badge, BadgeAwarded from pinax.badges.registry import badges class PointsBadge(Badge): slug = "points" levels = [ "Bronze", "Silver", "Gold", ] events = ["points_awarded",] multiple = False def award(self, **state): user = state["user"] points = user.get_profile().points if points > 10000: return BadgeAwarded(level=3) elif points > 7500: return BadgeAwarded(level=2) elif points > 5000: return BadgeAwarded(level=1) badges.register(PointsBadge) and a pretty bad points function that in my users model that calls a takes a parameter of amount and adds it to the points field in my user model. #User Model class User(AbstractUser): .... points = models.IntegerField(default=0) def award_points(self,amount): self.amount = amount self.points+=amount self.save() Now the function i am calling in a signal that checks when a user logs in and awards them some points.Like so #signal.py from django.contrib.auth.signals import user_logged_in,user_logged_out from django.dispatch import receiver from django.conf import settings from pinax.badges.registry import badges @receiver(user_logged_in) def award(sender,request ,user, **kwargs): user = request.user.award_points(5000) badges.possibly_award_badge("points_awarded", user=user) I registered the signal as well just to make sure. I am still not getting the desire result, which is, as soon as a … -
Should Whitenoise auto-compress static files? How?
I recently enabled Whitenoise for my Django project that will run on Heroku. I want Whitenoise to compress my static files automatically, as would seem to be possible from this part of the docs: http://whitenoise.evans.io/en/stable/django.html#add-compression-and-caching-support However, after adding the following to my settings: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I find that my files are not compressed! curl -H "Accept-Encoding: gzip" -I http://localhost:8080/static/app/js/auth.min.js HTTP/1.0 200 OK Date: Thu, 30 Nov 2017 17:14:27 GMT Server: WSGIServer/0.2 CPython/3.5.2 Last-Modified: Thu, 30 Nov 2017 01:45:33 GMT Content-Length: 103648 Content-Type: application/javascript; charset="utf-8" Cache-Control: max-age=0, public Access-Control-Allow-Origin: * However, if I manually gzip one of my files, everything works just peachy $ gzip ../app/static/app/js/auth.min.js $ curl -H "Accept-Encoding: gzip" -I http://localhost:8080/static/app/js/auth.min.js HTTP/1.0 200 OK Date: Thu, 30 Nov 2017 17:21:47 GMT Server: WSGIServer/0.2 CPython/3.5.2 Last-Modified: Thu, 30 Nov 2017 17:14:53 GMT Content-Type: application/javascript; charset="utf-8" Cache-Control: max-age=0, public Access-Control-Allow-Origin: * Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 21870 Do I just have to add some script to my build process to gzip everything, or does Whitenoise include this? If it does, does anyone have any idea what I might be missing or doing wrong? I would really like the ability (as advertised in the docs above) to keep everything cached forever -
Python-socketio with Django and https
I'm trying create a system of calls with WebRTC, so I developed a Python code using Django and socketio In localhost my app works fine, but in AWS EC2 doesn't. I see this error on my browser console: POST https://mydomain.com.br/socket.io/?EIO=3&transport=polling&t=M0DrIuC&sid=a3f1d452bbb044a3ac7809e0e2a4e7fd 400 () My socketio-cliente: socket = io.connect('https://' + document.domain + ':' + location.port + namespace, verify=false); My NGINX: upstream gunicorn_webapp { # for a TCP configuration server 127.0.0.1:9000 fail_timeout=0; } server { listen 80; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/mydomain.com.br/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mydomain.com.br/privkey.pem; # managed by Certbot client_max_body_size 4G; # set the correct host(s) for your site server_name mydomain.com.br; keepalive_timeout 5; # path for static files root /deploy/sites/webapp; location / { # checks for static file, if not found proxy to app try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #enable this if and only if you use HTTPS #proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; proxy_pass http://gunicorn_webapp; } } Where is my mistake? Thank you so much. -
How much should I learn Python to learn Django? [on hold]
I want to learn Django. For work professionally. How much python language need to know or learn to learn Django? -
Django REST API returning No 'Access-Control-Allow-Origin' header is present with Angular 4
I set up a Django REST API with the Django REST framework, and I'm trying to access it via an Angular 4 front-end. I keep getting an error saying "No 'Access-Control-Allow-Origin' header is present on the requested resource." I tried installing django-cors-headers, but it doesn't seem to do anything. I'm thinking I may have my REST API set up wrong. settings.py """ Django settings for weather project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'not_telling' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1:4200'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'weatherstats', ] MIDDLEWARE_CLASSES = [ 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'localhost:4200', ) ROOT_URLCONF = 'weather.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': … -
Create a Zip Archive from a cloned GitHub repo in Python
I'm working on a project using python(3.6) in which I need to create a zip archive which includes all files from a GitHub repo. The user will provide the git repo URL then I will need to clone this repo and create a zip archive which includes all files from GitHub repo. Here's what I have tried: ARCHIVE_NAME = func_obj.fname + '.zip' zip_archive = zipfile.ZipFile(ARCHIVE_NAME, "w") # Write files to the archive zip_archive.write(git.Repo.clone_from(func_obj.sc_github, to_path=os.path.join(ARCHIVE_NAME))) zip_archive.close() file_path = os.path.join(IGui.settings.BASE_DIR, ARCHIVE_NAME) Help me, please! Thanks in advance! -
Django: Using multiple slugs in a url
I want to keep my urls dynamic as well as clean. Therefore I'm using slugs. My problem right now is, that I get the following error: redefinition of group name 'slug' as group 2; was group 1 at position 42 I think I get that error, because I have to slugs in my chain. For reference I have a ListView into ListView into an UpdateView, alls importet from django.views.generic. The first list view gives me the first slug and the update view the second. Here is the url pattern (spread across the apps): First list view: urlpatterns = [ url(r'^$', RestaurantListView.as_view(), name='restaurant-list'), url(r'^(?P<slug>[\w-]+)/menus/', include('menu.urls', namespace='menu')), ] Second list view: urlpatterns = [ url(r'^$', MenuListView.as_view(), name='menu-list'), url(r'^(?P<slug>[\w-]+)/', MenuUpdateView.as_view(), name='menu-detail'), ] In the templates I get the objects via: <li><a href='{{obj.get_absolute_url}}'> {{obj}} </a></li> Which I have defined in the respective models: def get_absolute_url(self): return reverse('restaurants:menu:menu-detail', kwargs={'slug': self.slug}) and def get_absolute_url(self): return reverse('restaurants:menu:menu-list', kwargs={'slug': self.slug}) So the resulting pattern at the end is: restaurants/(?P<slug>[\w-]+)/menus/(?P<slug>[\w-]+)/ How can I fix it so that I don't get the error anymore? -
Django Model Form Set POSTs But Does Not Save
I have a Django site built on a model formset (forms.py). The model formset is picked up by my view (views.py). The view is rendered in my template (alerts.html). The user sees a list of alerts with entity and logic populated. They must enter a comment on one or more forms in the formset and then click the submit button to post the one or more forms to the DB. When the submit button is clicked currently, the page refreshes, but the data is not submitted to the DB. No error appears, and the data (i.e. text typed into the comment field) remains. How should I alter my project to allow the model formset to be saved appropriately? forms.py class AlertForm(ModelForm): class Meta: model = Alert fields = [ 'entity', 'logic', 'comment' ] AlertFormSet = modelformset_factory(Alert, extra=0, exclude=(), form=AlertForm) views.py def alerts(request): newAlerts = Alert.objects.filter(disposition='') formset = AlertFormSet(request.POST or None, queryset=newAlerts) context = {'formset':formset} if request.method == 'POST': formset = formset if formset.is_valid(): formset.save() else: formset = formset return render(request, 'alerts/alerts.html', context) alerts.html <form method='POST' action=''> {{ formset.management_form }} {% csrf_token %} <input name="submit" value="Submit" id="submit-id-submit" type="submit"> {% for form in formset %} {% for hidden_field in form.hidden_fields %} {{ … -
Django isnull query with mysql datefield not working
I have model class similar to this: class Manager(models.Model): employee = models.ForeignKey(Employee) manager_id = models.ForeignKey(db_index=True,max_length=20) start_date = models.DateField(blank=True, null=True) end_date= models.DateField(blank=True, null=True) The records are being stored in mysql db. When i use the query to fetch manager records whose end time is not yet set: Manager.objects.filter(end_time__isnull=True) it return zero records. However, Manager.objects.all()[0].end_time==None returns True in Django shell The entries in the database are also stored as '0000-00-00' How can i query to get Manager records whose end time is not yet set.? -
Show management commands in admin site
Maybe I am just naïve in my expectations, but I cannot find any simple configuration or app that would allow running a Django project's management commands from the admin interface. Surely allowing commands to be executed remotely without having to shell to the machine is a pretty common thing? Do you always have to implement it yourself? If so, how do you add to the existing admin site without replacing it entirely? -
Parse Django REST API response with Angular 4
I've built a Django REST API using the Django Restapiframework, and it uses a serializer to return a json response: from rest_framework import serializers from .models import WeatherStatistics class WeatherStatisticsSerializer(serializers.ModelSerializer): class Meta: model = WeatherStatistics fields = '__all__' In my Angular 4 front-end project I have a service: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl = 'http://127.0.0.1:8000/weatherstats/weatherdata'; getWeatherData() { return this.http.get(this._WeatherStatsUrl) .map((res:Response) => res.json); } getWeatherDataRecords() { this.getWeatherData().subscribe(weatherdata => { console.log(weatherdata) }) } } And I also have a component that uses that service: import { Component, OnInit } from '@angular/core'; import { WeatherstatsService } from '../weatherstats.service'; @Component({ selector: 'weather-stats', templateUrl: './weather-stats.component.html', styleUrls: ['./weather-stats.component.css'] }) export class WeatherStatsComponent implements OnInit { data: any; constructor(private weatherstatsservice: WeatherstatsService) { } ngOnInit() { this.data = this.weatherstatsservice.getWeatherData(); } } At the moment all I want it to do is log the json data from my api to the console oninit. So far tho, it does nothing. How do I get the json from Django into Angular? -
Django ListView with paginator: That page contains no results
I'm getting this error: That page contains no results I use CBV ListView with django-filter and simple pagination. I don't understand why I'm getting this error and, moreover, there is one item in QuerySet. I tried also append page=1 query param which raises the same error. This is my view: class UserFilterView(LoginRequiredMixin,ListView): template_name = 'frontend/userprofile_filter.html' model = UserProfile paginate_by = 5 # ordering = True # allow_empty = True def get(self,*args,**kwargs): self.filter = UserProfileFilter(self.request.GET, queryset=UserProfile.objects.all()) return super(UserFilterView,self).get(*args,**kwargs) def get_queryset(self): return self.filter.qs def get_context_data(self, **kwargs): context = super(UserFilterView,self).get_context_data(**kwargs) context['filter_form'] = self.filter.form return context I know that there is something wrong with paginator but I don't know what. Do you know? -
Using TaggableManager for m2m relationship in django
I am trying to use TaggableManager() to add tags in my form in django application but this does not seem to work. class UserBookmark(models.Model): user = models.ForeignKey(User) bookmark = models.URLField() tag = TaggableManager() def __str__(self): return '%i %s %s'%(self.id,self.user,self.bookmark) my html template: <div class="modal-body"> <form name = "form2" id = "form2" method = "post" action = "{% url 'savetag' %}" class = "form-inline"> {% csrf_token %} <div class = "form-group"> <input name = "tag" id = "tag" required> <input type="hidden" id = "field1" name="bookmark" value=""> <button type = "submit" class = "btn btn-danger">Save</button> </div> </form> </div> when i hit this query UserBookmark.objects.filter(tag__name__in = ['java']) i get empty set, while i do have records with this tag java. earlier my UserBookmark model was like this: class UserBookmark(models.Model): user = models.ForeignKey(User) bookmark = models.URLField() tag = models.CharField(max_length = 100) but this did not work because tag had a many to many relationship as a bookmark can have many tags, so CharField did not work. Can someone tell me what needs to be corrected here? -
Why we need <input> tag with object primary key and action_checkbox_name in django admin template?
Here is HTML page, which is Django admin template. It has a hidden input tag with value equals to subject primary key (pk). Why it is not working without that input? {% extends "admin/base_site.html" %} {% load i18n l10n %} {% block content %} <form action="" method="post">{% csrf_token %} <p>Choose tutor Subject:</p> <select title="selected_subject" name="selected_subject"> {% for sub in subjects %} <option type="hidden" name="subject" value="{{ sub }}">{{ sub.name }}</option> {% endfor %} </select> <p> {% for obj in queryset %} <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk }}" /> {% endfor %} </p> <p> <input type="hidden" name="action" value="{{ return_method }}" /> <input type="hidden" name="send" value="yes"/> <input type="submit" value="Select subject" /> </p> </form> {% endblock %} -
How to keep track of price changes and different prices for different customers in Django
In my Django project, I need to have products, prices and customers. One product can belong to many customers and have a different price for each of them. The price also needs to be updated over time. How can I keep track of price changes? Inside the view 'product history' I need to be able to see what was the original price and all the following changes to the price (with their related date of change). How should I model the entire customer - product relationship? Considering that the same product can belong to different customers and have a different price for each. models.py class Product(models.Model): sku = models.CharField(max_length=20) name = models.CharField(max_length=50) description = models.CharField(max_length=200) class Price(models.Model): product = (this links with a ManytoMany to Product) price = (most recent price) date = (date most recent price was entered on) class Customer(models.Model): product = (this links with a ForeignKey to Product) price = (this links with a ForeignKey to Price) How would you model it? Thank you in advance for your insights! -
Class-based Views in Django
I'd like to ask you if you can clear something up to me. I'm designing a web app powered by Django and I'm also learning about OOP as I go. From what understand main purpose of class-based views is to keep my code DRY. To avoid any repetitive or redundant code. I've tried to implement class-based views however at the end I always ended up tossing everything into function-based view 'coz all the views are fairly unique. When I looked over the views I asked myself: "Does your code repeat anywhere ?" Answer was no. The question is: Despite using classed-based views being considered to be the best coding practice it's not always possible. Am I right ? -
PrimaryKeyRelatedField does not include value in validated_data
I'm creating a serializer that is suppose to create an object on a POST request. However when run serializer.validated_data it does not include currency in the QueryDict. if i for instance change from PrimaryKeyRelatedField to IntegerField it includes it, but that is not optimal when it is suppose to point to a record in another table. Why is it that currency is not being included in validated_data when i use PrimaryKeyRelatedField? serializer class InvoiceSerializer(serializers.ModelSerializer): deposit_amount = serializers.FloatField() receive_amount = serializers.FloatField() currency = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Invoice fields = ('task', 'deposit_amount', 'receive_amount', 'currency') read_only_fields = ('created_at', 'updated_at', 'currency') def create(self, validated_data): return Invoice.objects.create(**validated_data) When i call request.data in my viewset it returns: {'currency': 2, 'task': 1, 'deposit_amount': 2.01, 'receive_amount': 118652.7} however when i return serializer.validated_data: OrderedDict([('task', 1), ('deposit_amount', 2.01), ('receive_amount', 118652.7)]) -
django modelform booleanfield not appearing as required
I'm trying to render a modelform which has a booleanfield from the model (with yes, no choices) that fails to appear as default (what I thought was the default). the model field is: BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) same_address = models.BooleanField(choices=BOOL_CHOICES) And used in the form via (and not altered in the form constructor or elsewhere): .... class Meta: model = Address fields = [ 'same_address', ] -
MultiValueDictKeyError Django 1.8
I am trying to import a file using forms.py. This code is the same code I used in another model and it worked, but this time it gives me this error: MultiValueDictKeyError at /importraw Exception Value: "u'rawname'" These are the snippets of code you need to know about: Views.py def importraw(request): form = UploadRaw(request.POST, request.FILES) if form.is_valid(): raw = Raw(title=request.POST['rawname'], file='raw_files/' + request.POST['file']) raw.save() handle_uploaded_raw(request.FILES["file"], request.POST["name"]) raw.save() return redirect('/importations') Urls.py: url(r'^importraw$', views.importraw), Models.py: class Raw(models.Model): title = models.CharField(max_length=200) file = models.FileField(upload_to='raw_files') uploaded_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.name Index.html <!--IMPORT--> <div class="col-md-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Importer un fichier brut</h3> </div> <div class="panel-body"> <form class="form-horizontal" action="/importraw", method="post"> {% csrf_token %} <fieldset> <div class="form-group"> <label for="name" class="col-lg-4 control-label">Structure</label> <div class="col-lg-6"> <select name="id" id="id" class="struct form-control"> {% for structure in structures %} <option value="{{ structure.name }}">{{ structure }}</option> {% endfor %} </select> </div> </div> <div class="form-group"> <label for="file" class="col-lg-4 control-label">Nom du fichier brut</label> <div class="col-lg-6"> <input type="text" name="rawname" id="rawname" class="form-control"> </div> </div> <div class="form-group"> <label for="file" class="col-lg-5 control-label">Fichier brut</label> <div class="col-lg-6"> <input type="file" name="file" id="file"> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2" align="center"> <button type="submit" value="Create" class="btn btn-primary">Importer</button> </div> </div> </fieldset> </form> </div> …