Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to translate strings in javascript written in script tags of html in django?
Hi I am translating a website in hungarian, I have problems with alerts and confirm strings that i have in my templates . am using "gettext('')" but these strings are not appearing in po files .enter code here my urls.py urlpatterns = patterns('', url(r'^jsi18n/$', javascript_catalog, js_info_dict, name='javascript-catalog'),` I have created po file django.po by running makemessages it has all the strings marked as trans in templates and also strings from *.py files. then I have run following command django-admin.py makemessages -d djangojs -l hu_HU its creating djangojs.po. The strings appearing in this file are all from *.js files in my static folder. But how do i have my strings used in alerts and confirms that are written in my templates. here are snippets from my templates. enter code here if($('#id_action').val()=='DEL'){ if(confirm(gettext('Are you sure you want to delete selected author(s) ?'))){flag_action=true;} } In my template i also have something like this which is not appearing in po files either. <li><a onclick="if(confirm(gettext('Are you sure you want to delete the selected author?'))){filter_content({{auth.id}},'DEL');return false;}" href="javascript:void(0)">{% trans 'Delete' %}</a></li> The string in gettext is not appearing in any po. I have included the following in my templates Please help me out. -
what could cause html and script to behave different across iterations of a for loop?
I'm trying to build a side navigation bar where categories are listed and upon clicking a category a respective sub list of subcategories is shown right below the category. And if the category is clicked again, the sub list contracts. So I'm running a loop across category objects. Inside this outer loop, I'm including a an inner loop to list subcategories and a script that hides the submenu and slidetoggles it only when a category is clicked. I'm using django template tags to dynamically assign class names for my html elements and also to refer to them in the script. So after all for loop iterations, there is a list of subcategory and a dedicated script for each category and they have unique class names so no chance of an overlap. So the weird part is, this works perfectly for most categories, but some of the categories and their submenu remain open and when clicked on the category the page reloads. I don't get it, what could cause the exact same code (run in a for loop) to behave so differently? -
Django uploaded file permissions
How to add permissions to uploaded file? E.g class Car(models.Model): name = models.CharField(max_length=255) photo = models.ImageField(upload_to='cars') owner = models.ForeigKey(AuthUser) And each logged user can add te images. E.g. User1 added image a.jpg. And can access it by adresserver.com/cars/a.jpg but anyone can access it too. How add permissions to only owner can see the image? -
How to prevent Django Rest Framework from validating the token if 'AllowAny' permission class is used?
Let me show you my code first: In settings.py .... DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) .... My my_view.py: @api_view(['POST']) @permission_classes((AllowAny,)) def say_hello(request): return Response("hello") As you can see, I'm using Token Authentication to protect my other API's by default, but when I add a token header in say_hello, Django Rest Framework will also check if the token is valid or not, even when i add AllowAny permission class. My question is how to make Django Rest Framework ignore checking the token if the token header is present in the say_hello? and Is there any security considerations for making this? Thanks. -
Need additional field for models on indirect relation
I've created a high school race django app. I have three models, Race, split and Athlete. Of which Split flows through Split Filter to dictate a filtering script we run. I was just asked to add a new field of Frosh vs JV vs Varsity. This creates a huge problem for me, because we're not sure where to add it. There can be JV and Varsity runners in the same race. These runners are registered in our system, and change races week to week, so we can't add it on athlete. We are considering adding it on split, but there are multiple splits per person (laps) per race, and in some weird circumstances, some splits can belong to different races (ie. a kid is in two races at the same time). Athlete and race aren't directly related on a Foreign key, so it makes this very difficult to figure out where and how to add JV vs. Varsity. class Race(models.Model): name = models.CharField(max_length=50) splits = models.ManyToManyField(Split, through='SplitFilter') class SplitFilter(models.Model): race = models.ForeignKey(Race) split = models.ForeignKey(Split) filtered = models.BooleanField(default=False) class Split(models.Model): athlete = models.ForeignKey(Athlete) time = models.BigIntegerField() class Athlete(models.Model): user = models.OneToOneField(User) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=1, null=True, blank=True) β¦ -
Modyfing pdf and returning it as a django response
I need to modify the existing pdf and return it as a response in Django. So far, I have found this solution to modify the file: def some_view(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment;filename="somefilename.pdf"' packet = StringIO.StringIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) ##################### 1. First and last name first_last_name = "Barney Stinson" can.drawString(63, 686, first_last_name) #Saving can.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(file("fw9.pdf", "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) # finally, write "output" to a real file #outputStream = file("output.pdf", "wb") #output.write(outputStream) response.write(output) outputStream.close() return response It let's me download the pdf, but when I am trying to open it, I get the message, that the file is damaged or wasn't correctly decoded. Does anyone know what am I don't wrong? Thank you! -
Django 1.9.7 Admin pages - CSS loaded but not rendering
I'm trying to get started with Django but already have something trivial bugging me. The localhost:8000/admin page should give me page with rendered elements using the login.css and base.css styles. However, the styles are not applied. Because my .css files are actually loading, I'm not even sure it's related to Django. Any insight on what could be causing the issue greatly appreciated. Django 9.1.7 / Python 3.5.0 -
Strange mistake in .aggregate with Case
I have two models: UserProfile BalanceEntry | - user = models.ForeignKey(UserProfile) - models.CharField(max_length=32, db_index=True, choices=BALANCE_ENTRY_TYPES) - amount = models.FloatField() - added_dt = models.DateTimeField(auto_now_add=True) I want to get total user revenue for last N days, so I created this method: def get_revenue_with_delta(self, days_delta): now = timezone.datetime.now() earlier = now - timezone.timedelta(days=days_delta) return int(BalanceEntry.objects.filter(user=self).aggregate(sum=Sum( Case( When(Q(type=BALANCE_ENTRY_TYPE_REFILL) & Q(added_dt__gt=earlier), then='amount'), default=Value(0), output_field=models.FloatField() )))['sum']) I have seeded the DB with fake UserProfiles and BalanceEntries for them yesterday, so all of them have the same added_dt. Then I'm trying to test the method get_revenue_with_delta for these profiles with days_delta = 7 and days_delta = 30. And I'm getting different amounts! Where is the mistake? -
AngularJS Logging Out and Logging back in
I have an index file that has some directives- <div ng-if="$hide"> <ba-sidebar></ba-sidebar> <page-top></page-top> <div class="al-main"> <div class="al-content"> <content-top></content-top> <div ui-view></div> </div> </div> </div> <div ng-if="!$hide"> <login-view></login-view> </div> What this does is it shows the content if a user successfully logs in. The code for logging in is- $interval(function(){ var token = $cookies.get('token'); if(token === undefined){ $rootScope.$hide = false; } else{ $rootScope.$hide = true; } }, 300) The interval function keeps a check on cookies for token that is send from the backend(django) and switches the views. If there is a token, it shows the main content, if not, it loads up the log-in directive. To log out, what I do is delete these cookies and set them to null, which automatically changes the view back to log-in directive. Once logged out, page switches to log-in. The problem- When I try to log-in with a different user, at the backend, the user gets switched but as soon as the view changes to the main content, it loads up the data from the previous user until whole page is refreshed(manually). I do not seem to understand why as ng-if recreates the whole DOM, shouldn't it load up the new data? If not, β¦ -
Python - <Response [450]>
I got two apps python based. Both apps deployed on Heroku. First app using Django framework and the second app using Flask framework. The problem is, second app try send request to first app and I got this error message as response. 2016-09-23T20:59:10.141255+00:00 app[web.1]: <Response [450]> second app code r = requests.post("https://facebook-auto-reply.herokuapp.com/api/messages/1/?format=json", params=params, headers=headers, data=data) log(r) first app code class message_detail(APIView): """ Retrieve, update or delete a message instance. """ def get_object(self, pk): try: return Campaign.objects.get(pk=pk) except Campaign.DoesNotExist: raise Http404 def get(self, request, pk, format=None): user = self.get_object(pk) user = MessageSerializer(user) return Response(user.data) def put(self, request, pk, format=None): user = self.get_object(pk) serializer = MessageSerializer(user, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Please advice. Thank you. -
Django REST Framework: Setting up prefetching for nested serializers
My Django-powered app with a DRF API is working fine, but I've started to run into performance issues as the database gets populated with actual data. I've done some profiling with Django Debug Toolbar and found that many of my endpoints issue tens to hundreds of queries in the course of returning their data. I expected this, since I hadn't previously optimized anything with regard to database queries. Now that I'm setting up prefetching, however, I'm having trouble using making use of properly prefetched serializer data when that serializer is nested in a different serializer. I've been using this awesome post as a guide for how to think about the different ways to prefetch. Currently, my ReadingGroup serializer does prefetch properly when I hit the /api/readinggroups/ endpoint. My issue is the /api/userbookstats/ endpoint, which returns all UserBookStats objects. The related serializer, UserBookStatsSerializer, has a nested ReadingGroupSerializer. The models, serializers, and viewsets are as follows: models.py class ReadingGroup(models.model): owner = models.ForeignKeyField(settings.AUTH_USER_MODEL) users = models.ManyToManyField(settings.AUTH_USER_MODEL) book_type = models.ForeignKeyField(BookType) .... <other group related fields> def __str__(self): return '%s group: %s' % (self.name, self.book_type) class UserBookStats(models.Model): reading_group = models.ForeignKey(ReadingGroup) user = models.ForeignKey(settings.AUTH_USER_MODEL) alias = models.CharField() total_books_read = models.IntegerField(default=0) num_books_owned = models.IntegerField(default=0) fastest_read_time = models.IntegerField(default=0) β¦ -
heroku server 500 error after a fit push
I did a git push and then all of a sudden my app responds with a server error. I have been trying to get my my scheduler to work it works fine locally. It gave me a problem but I fixed it using a git pull request. it was working fine locally and then all of sudden server error 500. I did heroku logs and got this response (practice) apples-MBP:src ray$ heroku logs fatal error: unexpected signal during runtime execution [signal 0xb code=0x1 addr=0x240b7863f52e pc=0x4227b] runtime stack: runtime.throw(0x525680, 0x2a) /usr/local/go/src/runtime/panic.go:547 +0x90 runtime.sigpanic() /usr/local/go/src/runtime/sigpanic_unix.go:12 +0x5a runtime.unlock(0x6c9ca0) /usr/local/go/src/runtime/lock_sema.go:107 +0x14b runtime.(*mheap).alloc_m(0x6c9ca0, 0x1, 0x8, 0x7aee88) /usr/local/go/src/runtime/mheap.go:492 +0x314 runtime.(*mheap).alloc.func1() /usr/local/go/src/runtime/mheap.go:502 +0x41 runtime.systemstack(0xc820067e58) /usr/local/go/src/runtime/asm_amd64.s:307 +0xab runtime.(*mheap).alloc(0x6c9ca0, 0x1, 0x10000000008, 0x41f1f) /usr/local/go/src/runtime/mheap.go:503 +0x63 runtime.(*mcentral).grow(0x6cb2f0, 0x0) /usr/local/go/src/runtime/mcentral.go:209 +0x93 runtime.(*mcentral).cacheSpan(0x6cb2f0, 0x7aee88) /usr/local/go/src/runtime/mcentral.go:89 +0x47d runtime.(*mcache).refill(0x75e000, 0x8, 0x7aee88) /usr/local/go/src/runtime/mcache.go:119 +0xcc runtime.mallocgc.func2() /usr/local/go/src/runtime/malloc.go:642 +0x2b runtime.systemstack(0xc820001240) /usr/local/go/src/runtime/asm_amd64.s:291 +0x79 runtime.mstart() /usr/local/go/src/runtime/proc.go:1051 goroutine 1 [running]: runtime.systemstack_switch() /usr/local/go/src/runtime/asm_amd64.s:245 fp=0xc82018f5d8 sp=0xc82018f5d0 runtime.mallocgc(0x70, 0x36c4a0, 0x1, 0x79930) /usr/local/go/src/runtime/malloc.go:643 +0x869 fp=0xc82018f6b0 sp=0xc82018f5d8 runtime.newarray(0x36c4a0, 0x63, 0x2c) /usr/local/go/src/runtime/malloc.go:798 +0xc9 fp=0xc82018f6f0 sp=0xc82018f6b0 runtime.makeslice(0x35d8a0, 0x63, 0x63, 0x0, 0x0, 0x0) /usr/local/go/src/runtime/slice.go:32 +0x165 fp=0xc82018f740 sp=0xc82018f6f0 strings.Join(0xc8201f51a0, 0x2, 0x2, 0x49c0e8, 0x1, 0x0, 0x0) /usr/local/go/src/strings/strings.go:363 +0xee fp=0xc82018f838 sp=0xc82018f740 main.(*Command).buildFlagHelp(0xc8201a72c0, 0x0, 0x0) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/command.go:117 +0x31a fp=0xc82018fb20 sp=0xc82018f838 main.(*Command).buildFullHelp(0xc8201a72c0, 0x0, 0x0) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/command.go:125 +0x131 fp=0xc82018fc20 sp=0xc82018fb20 main.Commands.loadFullHelp(0xc8201b5800, 0xd7, 0x100) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/command.go:221 +0x6b fp=0xc82018fc88 sp=0xc82018fc20 β¦ -
Eclipse: unresolved import
Eclipse Neon (4.6.0). PyDev for Eclipse 5.1.2.201606231256 I have created a Django project: File / New / Project / PyDev Django project Selected "Add project directory to the PYTHONPATH". Now I have this folder structure. (django_comments) michael@ThinkPad:~/workspace/formsets$ tree . βββ formsets βββ db.sqlite3 βββ formsets β βββ __init__.py β βββ __pycache__ β β βββ __init__.cpython-35.pyc β β βββ settings.cpython-35.pyc β β βββ urls.cpython-35.pyc β β βββ wsgi.cpython-35.pyc β βββ settings.py β βββ urls.py β βββ wsgi.py βββ home_page β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β β βββ __pycache__ β β βββ __init__.cpython-35.pyc β βββ models.py β βββ __pycache__ β β βββ admin.cpython-35.pyc β β βββ __init__.cpython-35.pyc β β βββ models.cpython-35.pyc β β βββ views.cpython-35.pyc β βββ templates β β βββ home_page β β βββ home_page.html β βββ tests.py β βββ views.py βββ manage.py In prjoect properties in PyDev-PYTHONPATH at the tab Source Folders I have: /${PROJECT_DIR_NAME} In home_page/views.py I have created HomePageView. And in urls.py I would like to import it: from home_page.views import HomePageView The problem is: 1) HomePageView is underlined with red line. Error is Unresolved import: HomePageView. 2) Code completion is not working. By the way, if β¦ -
Change to Django model not detected by makemigrations
I have a Django model which is referenced in another model as a ForeignKey type. In order that this is displayed nicely in the admin interface I added a __unicode__ method, like this: class Foo(models.Model): label = models.CharField(max_length=2) description = models.TextField() def __unicode__(self): return self.label This change is immediately visible in the admin interface after saving my models.py file. But when I run makemigrations it returns No changes detected in app 'concert'. Running migrate does nothing, as it doesn't see any changes, and python manage.py check returns System check identified no issues (0 silenced). Should I expect this? I've made many changes to my models and so have run many migrations, but I've never encountered this before. Currently running Django 1.8.3 with Sqlite development db, under Python 2.7 on Windows. -
What benefit to society are movies about slavery like Amistad and Django Unchained?
Sonya AbarcarThere is considerable benefit. They are very informative. They educate. Entertainment is provided as well. I would have never known about Amistad if it werenβt for this movie. Period. Many people would probably agree with that sentiment. Movies are often stories that need to be told and the former is definitely a story that needed to be told.Sure, they are painful but they donβt worsen race relations. Racism worsens race relations. Not movies, books, or songs. People do that.See Questions On Quora -
Define a Django model that is shared among many apps
How to define a generic Django model (that would perfectly fit in utility/common module), that is going to be used by many apps? I would prefer to define it outside an app, because semantically it does not belong to any of them. Is it possible? How to deal with the migration of it outside the app? -
Setting a cookie in Django Rest Framework API
I am trying to set a cookie on my website when a GET request is made to an API end-point. In my urls.py, I have this: url(r'^api/cookies/$', views.cookies, name='cookies'), which points to this view: @api_view(['GET']) def cookies(request): if request.method == 'GET': response = HttpResponse('Setting a cookie') response.set_cookie('cookie', 'MY COOKIE VALUE') if 'cookie' in request.COOKIES: value = request.COOKIES['cookie'] return Response('WORKS') else: return Response('DOES NOT WORK') In other words, when this view is loaded through a GET method, I am setting a cookie. If the cookie is set properly, I return 'WORKS', otherwise, I return 'DOES NOT WORK'. Now, I am sending a GET request to this URL, and I get 'DOES NOT WORK', which means the cookie is not set properly. What am I doing wrong? How can I fix this? Note: I am using Django Rest Framework for my views. -
Getting 403 (Forbidden) when trying to send POST to set_language view in Django
I'm new to Django and am trying to create a small website where I click on a flag and the language changes. I'm using django i18n for that: urls.py from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns urlpatterns = [url(r'^i18n/', include('django.conf.urls.i18n'))] urlpatterns += i18n_patterns( url(r'^$', views.home, name='home'), ) The problem is, when I run the following code: templetatags.py @register.simple_tag def test(): r = requests.post('http://localhost:8000/i18n/setlang/', data = {'lang':'en', 'next' : '/'}) print r.status_code home.html <div id='country_flags'> <a hreflang="en" href="{% test %}"><img id='en' src='{% static "mysyte/images/gb.png" %}'></a> </div> the result of r.status_code is 403. What am I doing wrong? -
How would I create a form for a foreign key field that has a drop down menu with an 'add item' option in django?
I'll start with my model fields: class Store(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Product(models.Model): type = models.CharField(max_length=250) def __str__(self): return self.type class Receipt(models.Model): store = models.ForeignKey(Store) date = models.DateField() line_items = models.ManyToManyField(Product, through='ReceiptProduct') def __str__(self): return self.store.name + ': ' + str(self.date) class ReceiptProduct(models.Model): receipt = models.ForeignKey(Receipt) product = models.ForeignKey(Product) price = models.FloatField() description = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.product.type What I would like to do is create a form for the ReceiptProduct model. class AddItemForm(ModelForm): class Meta: model = ReceiptProduct fields = ['product', 'price', 'description'] Done. And the view? def add_receipt_product(request, receipt_id): current_receipt = Receipt.objects.get(id=receipt_id) if request.method != 'POST': # No data submitted; create a blank form. form = AddItemForm(initial={'receipt': current_receipt}) else: # POST data submitted; process data. form = AddItemForm(data=request.POST) if form.is_valid(): new_product = form.save(commit=False) new_product.receipt = current_receipt new_product.save() return HttpResponseRedirect(reverse('purchase_log:receipt_details', args=[receipt_id])) context = {'current_receipt': current_receipt, 'form': form} return render(request, 'purchase_log/add_receipt_product_form.html', context) Okay, so what I would like to do is, under the 'product' field (which is a drop down menu populated by the Product model), have an option called, maybe, 'custom product' or something, that the user can select to add an item to the Product model and will then appear in β¦ -
Micro-components architecture with python / Django / Drf
I have several applications in my Django project: -ticker -payments -crypto -referrals -core I am using Docker wrapped by Wercker (quite limiting I would say, but saves time). My question is, how to deploy each application as a standalone container as a start, and a standalone VPS Node in the private network later. My logic tells me that a separate Django project will be required for this purpose. -
Deploy django app on ubuntu apache2
I want to run my Django app created in virtualenv on ubuntu with python3. Folder structure in virtualenv folder: -bin -include -lib -myapp -share pip-selfcheck.json The myapp folder contains my application with apache folder configured as specified in this tutorial: https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/ I have all apps installed I need in my virtualenv, after 'sudo service apache2 restart' I see only Apache2 Ubuntu Default Page. File /etc/apache2/sites-enabled/000-default.conf is like in the tutorial: <VirtualHost *:80> WSGIScriptAlias / /home/myuser/mysite/apache/wsgi.py <Directory "/home/myuser/mysite/apache/"> Require all granted </Directory> </VirtualHost> Of course with correct paths pointing to my project location in 'venv' folder. No idea where to move on, what to check, thanks for suggestions. -
How to query for SQLite database column names in Python/Django?
I can get all the values from the database for a particular Django model in Python using something like a = Attorney.objects.all().values_list() print(a) What command would I use to make a similar query but for all the column names in the database? Also, how would I append all the values returned by Attorney.objects.all().values_list() to a list that I could then iterate over? -
Can not save custom model based choices
Error: Exception Value: Cannot assign "'AF'": "UserProfile.country" must be a "Countries" instance. Error happens at the line if user_profile_form.is_valid(): # admindivisions.models class Countries(models.Model): osm_id = models.IntegerField(db_index=True, null=True) status = models.IntegerField() population = models.IntegerField(null=True) iso3166_1 = models.CharField(max_length=2, blank=True) iso3166_1_a2 = models.CharField(max_length=2, blank=True) iso3166_1_a3 = models.CharField(max_length=3, blank=True) class Meta: db_table = 'admindivisions_countries' verbose_name = 'Country' verbose_name_plural = 'Countries' class CountriesTranslations(models.Model): common_name = models.CharField(max_length=81, blank=True, db_index=True) formal_name = models.CharField(max_length=100, blank=True) country = models.ForeignKey(Countries, on_delete=models.CASCADE, verbose_name='Details of Country') lang_group = models.ForeignKey(LanguagesGroups, on_delete=models.CASCADE, verbose_name='Language of Country', null=True) class Meta: db_table = 'admindivisions_countries_translations' verbose_name = 'Country Translation' verbose_name_plural = 'Countries Translations' # profiles.forms class UserProfileForm(forms.ModelForm): # PREPARE CHOICES country_choices = () lang_group = Languages.objects.get(iso_code='en').group for country in Countries.objects.filter(status=1): eng_name = country.countriestranslations_set.filter(lang_group=lang_group).first() if eng_name: country_choices += ((country, eng_name.common_name),) country_choices = sorted(country_choices, key=lambda tup: tup[1]) country = forms.ChoiceField(choices=country_choices, required=False) class Meta: model = UserProfile() fields = ('email', 'email_privacy', 'profile_url', 'first_name', 'last_name', 'country',) # profiles.views def profile_settings(request): if request.method == 'POST': user_profile_form = UserProfileForm(request.POST, instance=request.user) if user_profile_form.is_valid(): user_profile_form.save() messages.success(request, _('Your profile was successfully updated!')) return redirect('settings') else: messages.error(request, _('Please correct the error below.')) else: user_profile_form = UserProfileForm(instance=request.user) return render(request, 'profiles/profiles_settings.html', { 'user_profile_form': user_profile_form, }) As I understand, country from ((country, eng_name.common_name),) is converted to str. What is the right β¦ -
Creating a Quote form in Django
i am creating a django powered website. Specifically, a courier website. I need to create an application that serves as a quoting app. The user will type in the dimensions of the package into a form and after submitting the form, a price/quote will be returned , based on the dimensions inputted. I have done this so far (views.py) from django.shortcuts import render, redirect from quote.forms import QuoteForm def quoting(request): if request.method == 'GET': form = QuoteForm() else: form = QuoteForm(request.POST) if form.is_valid(): Length = form.cleaned_data['Length'] Breadth = form.cleaned_data['Breadth'] Height = form.cleaned_data['Height'] return redirect('thanks') return render(request, "quote/quote.html", {'form': form}) (forms.py) from django import forms class QuoteForm(forms.Form): Length = forms.Integer() Breadth = forms.Integer() Height= forms.Integer() (quote.html) {% extends "shop/base.html" %} {% block content %} <form method="post"> {% csrf_token %} {{ form }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> {% endblock %} Then i am aware i am lacking an html that would display the answer. I am not sure how to do this. The price is determined by: price= Shipping weight X distance shipping weight= (length X breadth X height) / 5000 Thanks in advance :) -
How to display a ManyToMany field within the admin field of another ManyToMany field
(django V1.3, python 2.7) Title is confusing, I'll do my best to make this clear. I have three models, Branch, Event and Update: class Branch(models.Model): branch = models.CharField(max_length=20) def __unicode__(self): return self.branch class Event(models.Model): title = models.CharField(max_length=50) branches = models.ManyToManyField(Branch) updated = models.DateTimeField(auto_now=True) def get_branches(self): return ", ".join([str(p) for p in self.branches.all()]) def __unicode__(self): return '%s (%s)' % (self.get_branches, self.title, self.updated.strftime('%Y-%m-%d')) class Update(models.Model): title = models.CharField(blank=False, max_length=45) body = models.TextField(blank=False) related_event = models.ManyToManyField(Event, blank=True) def __unicode__(self): return self.title When adding an Update via the admin interface I want the related_event field to display the title, branches and updated fields of the Event model to make selecting the correct related_event easier for a user (rather than just a long list of titles). Example of how I want this to display in a pulldown or horizontal related_event admin field: ThisIsATitle Branch1, Branch2 (yyyy-mm-dd) I have this simple function in the Event model that gets all branches for an Event and joins them into a string which I successfully use in the list_display of the Event admin page: def get_branches(self): return ", ".join([str(p) for p in self.branches.all()]) Event Admin: ... list_display = ('title','get_branches', 'updated') ... I thought I could use that function like β¦