Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django conditional permission and initial attribute
I have problem about conditional permission and setting initial values. My models.py is : from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ import re from smart_selects.db_fields import ChainedForeignKey # Create your models here. class Product(models.Model) : name = models.CharField(max_length=20, verbose_name='Name', help_text='Product Name') u_name = models.CharField(max_length=20, editable=False) description = models.CharField(max_length=40, verbose_name='Description', help_text='Product Description') def clean(self) : self.u_name = re.sub(r'[^a-zA-Z0-9]','', self.name.lower()) existing = Product.objects.filter(u_name = self.u_name) if len(existing) > 0 : if self.pk == None : raise ValidationError('Duplicate Name : %s' %(existing[0].name)) else : if existing[0].id != self.id : raise ValidationError('Duplicate Name : %s' %(existing[0].name)) def __str__(self): # __unicode__ on Python 2 return self.name class Meta: verbose_name = 'Product' class Warehouse(models.Model): name = models.CharField(max_length=20, verbose_name='Name', help_text='Warehouse Name') u_name = models.CharField(max_length=20, editable=False) description = models.CharField(max_length=40, verbose_name='Description', help_text='Warehouse Description') def clean(self) : self.u_name = re.sub(r'[^a-zA-Z0-9]','', self.name.lower()) existing = Warehouse.objects.filter(u_name = self.u_name) if len(existing) > 0 : if self.pk == None : raise ValidationError('Duplicate Name : %s' %(existing[0].name)) else : if existing[0].id != self.id : raise ValidationError('Duplicate Name : %s' %(existing[0].name)) def __str__(self): # __unicode__ on Python 2 return self.name class Meta: … -
Send html input to views.py in Django
Hello I'm trying to send input text from index.html to my view function that is "result".When I click the 'Generate Summary' button its shows csrf verification failed.Csrf token missing.Urgent help required. views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader from .models import Input from django.views.decorators.csrf import csrf_protect def home(request): input=Input.objects.all() template=loader.get_template('home/index.html') context={ 'input':input, } return HttpResponse(template.render(context,request)) def result(request,input_text): Input.input_text = request.POST('input_text') return HttpResponse("<h1> text is"+Input.input_text) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Title</title> {% load staticfiles %} <link rel='stylesheet'href="{% static 'css/bootstrap.min.css' %}" type='text/css'/> </head> <body background="/static/home/img/bg.jpg"> <center><h1> <font color="white" >Summarizeit.com !</h1></center> <form name="myform" action="." method="post">{% csrf_token %} <div class="form-group"> <center><label for="abc">Input Text</label> <input type="text" name="input_text"class="form-group" id="abc"placeholder="Text input"> </div> <br><br><center><button type="submit" class="btn btn-default"> Generate Summary !</button> </form> home/urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.home, name='home'), ] finalproject/urls.py(Root Project) from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', include('home.urls')) ] models.py from django.db import models class Input(models.Model): input_text = models.CharField(max_length=250) def __str__(self): return self.input_text -
django rest framework 'tuple' object has no attribute 'key'
i used django framework and REST framework JWT Auth for token generation serializer.py from django.contrib.contenttypes.models import ContentType from django.contrib.auth import get_user_model from django.db.models import Q from django.contrib.auth.models import User from rest_framework import serializers from company.models import Employee from rest_framework.authtoken.models import Token from rest_framework.serializers import( ValidationError, ) class UserLoginSerializer(serializers.ModelSerializer): token = serializers.CharField(allow_blank = True , read_only = True) username = serializers.CharField(required = False , allow_blank=True) email = serializers.EmailField(label="Email Adress",required = False, allow_blank=True) class Meta: model = User fields = [ 'username', 'email', 'password', 'token', ] extra_kwargs ={"password": {"write_only":True } } def validate(self, data): user_obj = None email = data.get('email', None) username = data.get("username", None) password = data["password"] if not email and not username: raise ValidationError("A username or email is required to login") user=User.objects.filter( Q(email=email)| Q(username=username) ).distinct() user = user.exclude(email=None) if user.exists() and user.count() == 1 : user_obj = user.first() else: raise ValidationError("username/email not valid.") if user_obj: if not user_obj.check_password(password): raise ValidationError("Incorrect credentials please try again") token = Token.objects.get_or_create(user=user_obj) #print token.key data["token"] = token.key return data error give at data["token"] = token.key this line i.e. 'tuple' object has no attribute 'key' url.py url(r'^api/emp/$', x.EmployeeList.as_view(), name='api-Emp'), #url(r'^api/emp/(?P<pk>\d+)/$', x.EmployeeDetailAPIView.as_view(), name='api-Detail'), url(r'^api/emp/(?P<pk>[\w]+)/$', x.EmployeeDetailAPIView.as_view(), name='api-Detail'), #url(r'^(?P<pk>\d+)/$', x.EmployeeDetailAPIView.as_view(), name='api-Detail'), url(r'^api/emp/(?P<pk>[\w]+)/update/$', x.EmployeeUpdateAPIView.as_view(), name='emp-api-update'), url(r'^api/emp/(?P<pk>[\w]+)/delete/$', x.EmployeeDeleteAPIView.as_view(), name='emp-api-delete'), url(r'^create/emp/$', x.EmployeeCreateAPIView.as_view(), … -
Can/how do I access CSS data via selenium and python?
Using python (3.4), django (1.9) and selenium (3.0.2), I'm trying to figure out if/how I can access CSS code for my automated testing. Acute example of what I'm trying to do: I want to make sure that the appropriate background images are loading on the appropriate pages. In the past, these have broken when I've changed my project's static settings. I've coded the images into the CSS fairly simply like: background: url('image.jpg') Essentially, I'd like to do something like: css = self.browser.get_css_data('example.css') self.assertIn('image.jpg', css) I haven't done an exhaustive search, but I don't see anything in the selenium source code webdriver.py that does something like that. Any ideas of what I could do? More examples of my code: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from time import sleep class UnauthenticatedTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_home_page_loads_correctly(self): # The user loads the web page self.browser.get(self.live_server_url) self.assertIn('App Name', self.browser.title) -
How to create an object in one file and use everywhere in Django?
Let's take an example of this snippet import logging log = logging.getLogger('myapp') This has to be there in every file of my Django project in which I am using. There can be several other imports, that will be used in every file of the project. Is there any file or place in Django where I can declare these snippets once, and use the variable log and the others everywhere in the project without any imports or as minimum import as possible? -
Setting up Django development, test, and production environments
I am setting up a CentOS server with Apache and it got me wondering about how to setup development, testing, and production environments and how to setup the settings.py files. For the development environment, I was going to develop on the local computer, use the Postgres test database on the CentOS machine, and use runserver as the web server. When done coding, I was going to push to Git. For the testing environment, was going to pull, or clone, from Git to the CentOS server. I was going to have the test app running on 8080 and using the Postgres test database. For the production environment, would run on 80 and use the production Postgres database. Now these questions might seem to have pretty obvious answers, but feel the need to ask for clarity: 1) The production and testing directories will need to be completely separated from one another, correct? Obviously if they share the same directory and issues that come up during testing will be present in the production env which would be bad. 2) In Apache, it would need to be setup to serve the test environment on 8080 and point to the test directory for the test … -
How to add google login to your django 1.10 websites?
I know this question might be repetitive but i have tried my best to find the answer but all in all the answers the packages used are either deprecated or are not working properly. While answering please do list all the additional packages that need to be download assuming that I haven't installed any package. -
CSRF verification failed. Request aborted. Django
I am getting the CSRF failure in django and no articles are working. It says it's used for posts, like I remember, and it is included in the form, but not in a form tag settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] login.html {% extends 'base.html' %} {% block body_block %} <style> html{ } </style> <h1>Login</h1> <form id="login_form" method="post" action="{% url 'accounts:login' %}"> {% csrf_token %} <div class="input-group input-group-md"> <span class="input-group-addon">Username</span><input type="text"class="form-control" placeholder="Username" aria-describedby="basic-addon2" name="username" value="" size="50" /> </div> <br> <div class="input-group input-group-md"> <span class="input-group-addon">Password</span><input class="form-control" placeholder="Password" aria-describedby="basic-addon2" type="password" name="password" value="" size="50" /> </div> <br> <div class="input-group input-group-md"> <input class="btn btn-default navbar-btn" type="submit" value="Submit" /> </div> </form> <br /><br /> <a style="font-size:22px;" href="/accounts/register/">Need to make a new account?</a> {% endblock %} {% block buttons %}{% endblock %} views.py: def user_login(request): context = RequestContext(request) if request.method == 'POST': form = LoginForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return redirect('bookmarks:silo') else: return HttpResponse("Your Sitename account is disabled.") else: return render_to_response('accounts/login.html', locals(), context) else: template_name = 'accounts/login.html' return render_to_response('accounts/login.html', locals(), context) Why is this csrf token not working? Thank you -
Django model primary key as a pair
I am trying to make an app where users will login to their profile and can add songs to their favorite list. I am defining a M2M relationship for this. My question is how to say combination of (song, singer) is unique? I searched and found that it may be possible through unique_together. Is this the correct way of setting this? models.py: from django.contrib.auth.models import User class Singer(models.Model): name = models.CharField(max_length=500, unique=True) def __str__(self): return self.name class Song(models.Model): id = models.AutoField(primary_key=False) singer = models.ForeignKey(Singer, on_delete=models.CASCADE, related_name='song') name = models.CharField(max_length=500) Class Meta: unique_together = (singer, id) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) songs = models.ManyToManyField(Song, related_name='profile') def __str__(self): return self.user.username Please feel free to correct my models.py, if you think the relationship is not correct. Thanks, -
How can I close a django 1.8 database cursor and connection?
Here is what I have: from django.db import connection class Command(BaseCommand): option_list = BaseCommand.option_list def handle(self, *labels, **options): with connection.cursor() as cursor: # Drop database cursor.execute("drop database if exists test_db;") # Create database again cursor.execute("create database test_db;") Where in this block can I close the db cursor and connection and what do I call to close them? -
Django - displaying values from a dictionary nested in a list in an html template
I have the followed class-based views in my views.py file: class HomeView(TemplateView): template_name = 'annual_means/home.html' site_list = AnnualMean.objects.values("site").distinct() def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['sites'] = AnnualMean.objects.values("site").distinct() return context At the top of my html template, just for testing this out, I have {{sites}} and it is displaying: Below, I have the following html code: {% for value in sites %} <li>{{value}}</li> {% endfor %} And it lists all the key:value pairs as shown above, e.g. {'site': 'Belfast Centre'}, instead of just the values. I assume this is due to the dictionary in the QuerySet being nested within a list. Is there a way I can return just the a dictionary or otherwise get around this problem? -
Formatting job returned from input with Jquery
I am trying to format these dates that I am receiving. I am intilizing the inputs like so: $('#newEventStartDate').plusDatePicker(); $('#newEventEndDate').plusDatePicker(); After the user submits the form, I would like to collect the dates and submit them to my api with ajax. Django requires the date to be in YYYY-MM-DD format yet the date picker uses MM/DD/YYYY format. How can I convert the following date: var eventData = { startDate: $('#newEventStartDate').val(), //right now it gives MM/DD/YYYY endDate: $('#newEventEndDate').val(), } I tried this and it didn't work: var eventData = { startDate: $('#newEventStartDate').plusDatePicker({ dateFormat: 'YYYY-MM-DD' }).val(), endDate: $('#newEventEndDate').plusDatePicker({ dateFormat: 'YYYY-MM-DD' }).val(), } -
How to migrate django custom base64 field
I have a base64 field that is copied from the django snippet. https://djangosnippets.org/snippets/1669/ class Base64Field(models.TextField): """ https://djangosnippets.org/snippets/1669/ Example use: class Foo(models.Model): data = Base64Field() foo = Foo() foo.data = 'Hello world!' print foo.data # will 'Hello world!' print foo.data_base64 # will print 'SGVsbG8gd29ybGQh\n' """ def contribute_to_class(self, cls, name): if not self.db_column: self.db_column = name self.field_name =name+ '_base64' super(Base64Field, self).contribute_to_class(cls, self.field_name) setattr(cls, name, property(self.get_data, self.set_data)) def get_data(self, obj): return base64.decodestring(getattr(obj, self.field_name)) def set_data(self, obj, data): setattr(obj, self.field_name, base64.encodestring(data)) def deconstruct(self): ame, path, args, kwargs = super(Base64Field, self).deconstruct() from pprint import pprint pprint(vars(self)) return ame, path, args, kwargs I am facing issues while migrating this field e.g. class EmailStatus(models.Model): attachment = attachment = Base64Field(null=True,blank=True, db_column='attachment', name="attachment", verbose_name="attachment") The error I am getting while migrating is raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: EmailStatus has no field named u'attachment' Now I can see why that is happening. But cant figure out a way around it. I think I might need to change something in the deconstruct field. -
Django - passing data from a python script to a django view
I have a python script with my django models imported to it, it does a little data treatment to the objects and returns some values for example a dictionary called travel and two lists: city and route; My script runs in a view: class UpdateObject(UpdateView): [...] command = "python script.py" subprocess.call(command, shell=True) [...] I would like to pass the values that I got with the script to another view class DetailView(generic.DetailView): [...] How can I achieve that? -
Curl {"error": "invalid_client"} for Oauth access token
I've been try to get my Django App to make Open Street Map API calls. To do this I needed to register my app with OAuth, so I've been following this tutorial to help me do this. I've gotten to step four and using curl to get the access token. I've ran this command (and replaced the client keys): curl -d "grant_type=password&username=myUser&password=myPassword" -u "<clientId>:<clientSecret>" http://localhost:8000/o/token/ -v And this was the output I got: * STATE: INIT => CONNECT handle 0x80049cd0; line 1407 (connection #-5000) * Added connection 0. The cache now contains 1 members * Trying ::1... * TCP_NODELAY set * STATE: CONNECT => WAITCONNECT handle 0x80049cd0; line 1460 (connection #0) * Trying 127.0.0.1... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 8000 (#0) * STATE: WAITCONNECT => SENDPROTOCONNECT handle 0x80049cd0; line 1567 (connection #0) * Marked for [keep alive]: HTTP default * STATE: SENDPROTOCONNECT => DO handle 0x80049cd0; line 1585 (connection #0) * Server auth using Basic with user 'W48FhrdBtWpwdwcMfGOCaKtD2k7QRSKxi4nKkGIE' > POST /o/token/ HTTP/1.1 > Host: localhost:8000 > Authorization: Basic VzQ4RmhyZEJ0V3B3ZHdjTWZHT0NhS3REMms3UVJTS3hpNG5La0dJRTpHV1VTTG5Ub0NWcWNWWVNheE1ZUFBvVlRQMXVycjh5YXJseVp4ZHNG > User-Agent: curl/7.51.0 > Accept: */* > Content-Length: 52 > Content-Type: application/x-www-form-urlencoded > * upload completely sent off: 52 out of 52 bytes * STATE: DO => … -
Values larger than 1/3 of a buffer page cannot be indexed Django error
I am using Heroku for the deployment for my Django application and I am trying to put a very long data into the table with the following model (adding the data to content: models.py: class ContentModel(models.Model): ref_id = models.CharField(primary_key=True, max_length=120, unique=True) content = models.TextField() #<------- timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.content class Meta: unique_together = ("content", "ref_id") But I get the following error: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.OperationalError: index row size 3496 exceeds maximum 2712 for index "editor_contentmodel_content_2192f49c_uniq" HINT: Values larger than 1/3 of a buffer page cannot be indexed. Consider a function index of an MD5 hash of the value, or use full text indexing. I am not sure what indexing here means, if it is for searching I don't think I will be needing it, all I wanted to do is to retrieve the data from the table. It is also asking me to us MD5 hash, so should I be using hashlib before I add the content to the database? The problem is that I am adding a JSON to the content -
How to set initial values in django forms.ChoiceField?
I have simple django form: class AddSymbolForm(forms.Form): list_n = forms.ChoiceField(choices=[(1,1), (2,2), (3,3)]) How can I set initial value in views.py? I tried to something like this: add_symbol_form = AddSymbolForm(initial={list_n:3}) And this is not working. So is there any way I can set initial values for choice fields? P.S. It's interesing but this code set correct initial value class AddSymbolForm(forms.Form): list_n = forms.ChoiceField(choices=[(1,1), (2,2), (3,3)], initial=3) and this one is not working correctly: class AddSymbolForm(forms.Form): list_n = forms.ChoiceField(choices=[(1,1), (2,2), (3,3)]) list_n.initial = 3 -
unknown error -django 1.8 checkbox widget/boolean field
In modal there is a field anonymous = models.BooleanField(default=True) This a form: class QuestionForm(forms.ModelForm): question = forms.CharField(required=True, label='', max_length=5000, widget=forms.widgets.Textarea(attrs={'class': 'question_textarea','placeholder':'Write your question here'})) anonymous = forms.BooleanField(initial=True, widget=forms.widgets.CheckboxInput(attrs={'class': 'anonymous_checkbox'})) class Meta: model = Question fields = ('question','anonymous',) When anonymous field is selected in html(as default) the form works, but otherwise(if unselected) I get unknown error: {"error":{"type":"http","message":"unknown error"}} What am I doing wrong and how to fix? -
Django 1.10. Why does settings.LOGIN_URL default to /accounts/login/, while django.contrib.auth.urls uses ^login/$?
I'm migrating to Django 1.10 and trying to fix login issues. So, going by topics.auth.default Using the views I do the following: urlpatterns = [ .... url('^', include('django.contrib.auth.urls')), ] OK, and now I am getting a 404 about /accounts/login not existing. Now, as this is an existing app I am moving to Django 1.10, I first figured I had forgotten that url somewhere. But I couldn't find it. Then it turns out that, in Django: django.conf.global_settings: LOGIN_URL = '/accounts/login/' But, Using the views, says: This will include the following URL patterns: ^login/$ [name='login'] as expected from django.contrib.auth.urls urlpatterns = [ url(r'^login/$', views.login, name='login'), There is also some more guidance about watching what's in settings.LOGIN_URL. Basically, the way I set up the url, it's expecting a login @ /login/. But the settings default to /accounts/login/. For, now, I've modified my settings to LOGIN_URL = LOGIN_REDIRECT_URL = '/login/'. And I now have to deal with a template name error, which is expected, but at least I have gotten past the 404. Wouldn't it have made more sense to suggest setting up the top-level urls.py as : url('^accounts/', include('django.contrib.auth.urls')), Which would have lined up better with the settings default? And also with the … -
NoReverseMatch at /
I get this error on the homepage of my website: NoReverseMatch at / Reverse for 'admin' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []. Here is my urls.py: from django.conf.urls import url from django.contrib import admin from rest_framework.urlpatterns import format_suffix_patterns from rest_framework import routers from . import views router = routers.SimpleRouter() router.register(r'queue', views.QueueItemViewSet) router.register(r'label', views.EventLabelViewSet) urlpatterns = router.urls urlpatterns += [ url(r'^$', views.api_root), url(r'^fingerprint/submit/$', views.FingerprintSubmit.as_view(), name="fingerprint-submit"), url(r'^fingerprint/rebuild/$', views.RebuildFingerprints.as_view(), name="fingerprint-rebuild"), url(r'^admin/', admin.site.urls, name="admin"), ] urlpatterns = format_suffix_patterns(urlpatterns) And here is the offending views.py snippet: @api_view(['GET']) def api_root(request, format=None): """ Home page of the API """ return Response({ 'admin': reverse('admin', request=request, format=format)}) And finally, the traceback: Environment: Request Method: GET Request URL: http://128.31.25.88:8000/ Django Version: 1.10.5 Python Version: 3.4.3 Installed Applications: ['deltasherlock_server.apps.DeltasherlockServerConfig', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.4/dist-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py" in dispatch 477. response = self.handle_exception(exc) File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py" in handle_exception 437. self.raise_uncaught_exception(exc) … -
Django: what is the purpose of "$" symbol in urlpatterns?
I just lost about 1h trying to figure out why my Django routes/urls were not working for create, edit and delete. Just list was working. Here is the issue I had: urlpatterns = [ ... ### url(r'^solicitacao', views.solicitacao_list, name='solicitacao_list'), url(r'^solicitacao_new$', views.solicitacao_create, name='solicitacao_new'), url(r'^solicitacao_edit/(?P<pk>\d+)$', views.solicitacao_update, name='solicitacao_edit'), url(r'^solicitacao_delete/(?P<pk>\d+)$', views.solicitacao_delete, name='solicitacao_delete'), ] The first url was missing a $ symbol at the end, and there was no error or any message when I tried to access other urls than list Somehow my routes got screwed up. I ended up being redirected to the list url, even though the redirect did not appear on the console. Can anybody with more django experience explain me what the $ symbol means in the routes, and why did it affect the create/edit/delete urls? -
Save an 'owner' to my model on Django Rest Framework
First of all, sorry for my bad English, I'm still learning Can you help me to solve a problem? I need save an owner on my django DB with DRF, I use the model "User" from django and I create a Models, actor and serie, I need set an owner on each of this models but I don't know how to do it, my code is the next. Here is my models GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) class actor(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) age = models.IntegerField() owner = models.ForeignKey(User, editable=False) def __unicode__(self): return '%s %s' % (self.first_name, self.last_name) class serie(models.Model): name = models.CharField(max_length=100) actors = models.ManyToManyField(actor) pic = models.ImageField(upload_to='series/%Y-%m-%d') release = models.DateField() review = models.TextField() seasons = models.IntegerField() owner = models.ForeignKey(User, editable=False) def __unicode__(self): return '%s' % (self.name) and now my serializers.py class actorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = actor fields = ('url', 'first_name', 'last_name', 'gender', 'age', 'owner') class serieSerializer(serializers.HyperlinkedModelSerializer): actors = actorSerializer(many=True) class Meta: model = serie fields = ('url', 'name', 'actors', 'pic', 'release', 'review', 'seasons', 'owner') and my viewsets.py class actorViewSet(viewsets.ModelViewSet): queryset = actor.objects.all().order_by('id') serializer_class = actorSerializer permission_classes = (IsOwnerOrReadOnly, ) class serieViewSet(viewsets.ModelViewSet): queryset = serie.objects.all() serializer_class = … -
KeyError when trying to assign clean_data value in Django
I receive a KeyError when I try to assign a form.clean_data['value'] I'm trying to script an interest calculator in django web app, which takes the user input of initial capital years and rate and calculates the final capital, however it returns a key error the db is sqlite3 Any help is appreciated in the solution and design being a beginner and all.. here's the traceback Traceback: File "/Users/Andras/miniconda3/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/Andras/miniconda3/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/Andras/miniconda3/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Andras/myproject/myapp/views.py" in query 37. initial = form.cleaned_data['initial'] Exception Type: KeyError at /query/ Exception Value: 'initial' views.py from django.shortcuts import redirect from django.shortcuts import get_object_or_404, render from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from django.template.loader import get_template from django.template import Context from django.views.generic.base import TemplateView from myapp.models import Queries from django.core import serializers import os, re, math from django.template import Context from django.views.generic import View from django import forms from myapp.forms import QueriesForm import decimal from django.http import Http404 def get_final(initial, rate, years): initial = self.initial rate = self.rate years = self.years calcInterest = … -
Web Framework with a good Data Structure
I'm used to work with .NET, I'm looking for something like Django, and I was excited to learn it. But I realized that the data structure is a bit weird. The goal is to work with a lot of data and well organized. Where can have a List of a class and do "where", "order by", etc. Like this: public partial class Customer : System.Web.UI.Page { public class myCustomer { public String Name {get;set;} public int Age { get; set; } public String City { get; set; } public myCustomer() { } public myCustomer(string _name, int _age, string _city) { Name = _name; Age = _age; City = _city; } } List<myCustomer> customerList; protected void Page_Load(object sender, EventArgs e) { customerList = new List<myCustomer>(); myCustomer co1 = new myCustomer { Name = "Donna", Age = 40, City = "New York" }; myCustomer co2 = new myCustomer("Raj", 10, "New York"); myCustomer co3 = new myCustomer("Art", 16, "New York"); customerList.Add(co1); customerList.Add(co2); customerList.Add(co3); testDataGrid.DataSource = customerList; testDataGrid.DataBind(); } } I'm looking for some framework that can do it, but doesn't .net. Someone know? -
Display field other than __str__
I am trying to display the version field from the below model other than the default str which is field2_name: Note: This SO link Displaying a specific field in a django form might be more than I need but I am not 100% sure. I tried to implement this but was not successful. Also note that I tried the example at https://docs.djangoproject.com/en/1.10/ref/forms/fields/ but was not able to get it to work Model (Generic names): class CodeVersion(models.Model): field1= models.ForeignKey(SomeOtherModel, on_delete=models.CASCADE) field2_name = models.CharField(max_length=256) field3_description = models.CharField(max_length=1000, blank=True) version = models.PositiveIntegerField() def __str__(self): return self.field2_name Form: class VersionsForm(forms.Form): code_versions = forms.ModelChoiceField(queryset=CodeVersion.objects.none()) def __init__(self, SomeOtherModel_id): super(VersionsForm, self).__init__() self.fields['infocode_versions'].queryset = CodeVersion.objects.filter(SomeOtherModel_id=SomeOtherModel_id) This works - it returns field2_name as it is supposed to. How do I return version instead - what is the simplest way? Any help or guidance is appreciated.