Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Reverse with a named url
I feel like this is one that I shouldn't be having trouble with, but I'm stumped. I tried to Google around, but the every post I see has the issue in the template. I have the following in urls.py: path('AddStudent/thanks', views.thanks, name='AddStudentThanks') I have an FBV from another view that I want to link to that one. I can do it explicitly with return HttpResponseRedirect("AddStudent/thanks") but when I try to future-proof it and use the named url with the following code return HttpResponseRedirect(reverse("AddStudentThanks")) #go I get the following error & traceback NoReverseMatch at /advising/AddStudent Reverse for 'AddStudentThanks' not found. 'AddStudentThanks' is not a valid view function or pattern name. Request Method: POST Environment: Request Method: POST Request URL: http://127.0.0.1:8000/advising/AddStudent Django Version: 2.1.2 Python Version: 3.6.6 Installed Applications: ['advising.apps.AdvisingConfig', '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 "/home/ne573414/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ne573414/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/ne573414/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ne573414/Desktop/School/SD/proj/tnb/tnb/ETM_Advising/advising/views.py" in AddStudent 48. return HttpResponseRedirect(reverse("AddStudentThanks")) #go File "/home/ne573414/env/lib/python3.6/site-packages/django/urls/base.py" in reverse 90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/ne573414/env/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix 622. raise NoReverseMatch(msg) Exception Type: NoReverseMatch at β¦ -
Django MultipleModelChoiceField gives me a ProgrammingError
I would like to get your help because I'm getting an issue which is a little bit weird to my mind. I'm using Django 1.11.16 I have in my forms.py file this class : class PublicationStatForm(forms.Form): # publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id')) publication_list = forms.ModelMultipleChoiceField( queryset=Publication.objects.all().order_by('pub_id'), label=_('Publication Choice'), widget=ModelSelect2Widget( model=Publication, search_fields=['pub_id__icontains', 'title__icontains'], attrs={'data-placeholder': "Please select publication(s)"} ) ) def __init__(self, *args, **kwargs): super(PublicationStatForm, self).__init__(*args, **kwargs) Then, in my views.py file : class StatsView(TemplateView): """ Create statistics pageview """ template_name = 'freepub/stats.html' form_class = PublicationStatForm def get_context_data(self, **kwargs): subtitle = _("Statistics") context_data = super(StatsView, self).get_context_data(**kwargs) context_data['form'] = self.form_class() ... return context_data And finally in my template, I just have : <form class="date-form" method="GET"> <div class="row"> <div class="col-md-7"> {{ form.publication_list }} </div> </div> <input id="submit-date-stats" type="submit" class="btn btn-default" name="SearchPublicationPeriod" value="{% trans 'Submit' %}"/><br/> </form> I don't understand why, when I have this line in my form it works : # publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id')) But when I replace this line by this : publication_list = forms.ModelMultipleChoiceField( queryset=Publication.objects.all().order_by('pub_id'), label=_('Publication Choice'), widget=ModelSelect2Widget( model=Publication, search_fields=['pub_id__icontains', 'title__icontains'], attrs={'data-placeholder': "Please select publication(s)"} ) ) I get this issue : Exception Type: ProgrammingError at /freepub/stats Exception Value: relation "select_cache" does not exist LINE 1: SELECT COUNT(*) FROM "select_cache" ^ Do you β¦ -
django testing Assertquerysetequal not working
I have trying to do an assertqueryset with django testing using the following commands but all of them work if there is only one object in the list, but when I insert multiple objects in the list to compare both sets of queries all of them fail sometimes and pass sometimes which is completely strange(running with same set of code). The list of assertquerysetequal I used to test I sourced from two other questions in How do I test Django QuerySets are equal? and in Django 1.4 - assertQuerysetEqual - how to use method as well as the django documentation. This could be because the sequence is not in order when it fails the comparison test. Because when I did a print - my querysets were exactly matching. Because when I run the tests, sometimes the tests passes, sometimes it fails when I compare multiple objects in my lists. I can tell them the list differ when it fails because of the error message but I don't understand why the commands that I used does not compare them in order. (They were accepted/upvoted answers) Any advice on how I can fix this permanently would be welcome. Thank you. class TestViews(TestCase): β¦ -
django ajax audio file upload to views.py
m a newbie in django. the problem m facing is that i cant send an audio file to views,py for further processing.kindly help me in this thanks enter image description here ` upload var recorder = document.getElementById('recorder'); var player = document.getElementById('player'); recorder.addEventListener('change', function(e) { var file = e.target.files[0]; enter code here player.src = URL.createObjectURL(file); }); ` -
Django: creating a text with gaps for input
I want to create a text on my website, where the gaps, in which the user can input a word (like the c-tests for learning language) are dynamically created depending on the text that the function gets from the database (not yet implemented). My idea was it to create a formset in which each label is different depending on a variable I give it. Here is my views.py def ctest(request): c_test_tokens, gaps, tokenindexe = generate_c_test(beispieltext()) # EXAMPLE # NOT WORKING ON POST REQUEST YET # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CTestform(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: CTestform.creatingForm(tokenindexe) ctestformset = formset_factory(CTestform, extra=len(gaps)) return render(request, 'ctest.html', {'form': ctestformset}) Here is my forms.py class CTestform(forms.Form): hello = forms.CharField(widget=forms.TextInput(attrs={'size': '5'}), required=False, label='hello', label_suffix='') Is this approach fine and how do I give the form a list with each element being the label for β¦ -
how to show data from 2 models in django with one to many relashion in template
Hello i have 2 classes in my model: class MO (models.Model): many variables class PhotoMO (models.Model): mo = models.ForeignKey(MO, on_delete=models.CASCADE) photo = models.ImageField( upload_to='img/photo/%Y/%m/' ) my views for template class MOListView(DetailView): template_name = 'main_site/mo_view.html' model = models.MO with template : {% block content %} <h1>{{ mo.name }}</h1> <h3>{{ mo.phone_number }}</h3> <h3>{{ mo.email_mo }}</h3> <h3>{{ mo.adress_mo }}</h3> {% for photos in mo.photomo.set.all %} <img src="{{ photos.photo.url }}" alt="no img"> {% endfor %} {% endblock %} How can I display all the pictures from PhotoMO that refer to a specific entry in MO. With my "for" it dosen't work -
Does form.save() save cleaned_data value or non clean value to the model
I have a model form in Django. if form1.is_valid(): form1.save() Does this save cleaned_data to the model or does it save unclean data. Thanks -
URL configuration in Django
I have a Django in which the HTML page has a simple GitHub link. <a href="www.github.com">Github</a> When I click on it, the URL it gets redirected to is "localhost/app/github.com" Can you please explain why is it happening and what should I do to correct it? -
Admin page couldn't get found
Here come my urls.py page code: from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), ] When I run Django I get 404 error. I know this is a famous problem but couldn't find any answer for it. What is wrong? -
python ImportError: cannot import name 'Faker' from 'faker'
hello so I've been writing this script to pre-populate my Django database but when I stopped writing it I got a weird error: My Script: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() ## FAKE POPULATION SCRIPT: import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker # Creating a fake generator: fakegen = Faker topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N = 5): for entry in range(N): # GET THE TOPIC FOR THE ENTRY: top = add_topic() # Create the fake data for that entry: fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry: webpg = Webpage.objects.get_or_create(topic = top, url = fake_url, name = fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.get_or_create(name = webpg, date = fake_date)[0] if __name__ == '__main__': print("Populating Script!") populate(20) print("Populating Complete!") The error I get: python populate_first_app.py Traceback (most recent call last): File "populate_first_app.py", line 11, in <module> from faker import Faker File "E:\Python\Projects\Python And Django FullStack\Django\first_project\faker.py", line 1, in <module> from faker import Faker ImportError: cannot import name 'Faker' from 'faker' I've never seen the error like this I am using this script β¦ -
Django - fetch data from Elasticsearch as QuerySet.
I have an ordinary ViewSet that fetch data from PostgesDB, applies some BackEnd filters etc. All of the processing works thanks to the fact that Notes.objects.all() returns a QuerySet. How do I turn a free Elasticsearch query result to QuerySet? Alternatively, How do I turn a Dict into QuerySet? Thank in advance. -
Django Forms - How to create a "Save and New" button?
Is there a way in Django Forms that I could implement a button "Save and New"? For example: I'm registering a new Book, I have both "Save" and "Save and New" buttons in the HTML template. The "Save" button behaves normally. You put the data in the form fields, click on it, the new object is created and saved and then redirects to the list of books. But I would like that the "Save and New" button redirects to the same form creation page after clicked. Plese, how could I do that? I didn't find anything about this in the docs. -
ImportError: cannot import name 'X' - Compile Python class with Cython
I'm creating a web application (using Django 1.11.2, Python 2.7.15) that will be deployed in a IIS server (actually now I'm only working on my local PC with Windows 10). Since that server will be reachable by another user and since I need to protect the application's back-end, I compiled the Python's core classes with Cython getting the ".pyd" files. Then I deleted the ".py" files (after a back-up =)). My folders organization is (note: py2_env is the virtualenv directory): C:\ βββ Software\ βββ MyApp\ βββ py2_env\ β βββ Include\ β βββ Lib\ β βββ Scripts\ β βββ tcl\ βββ MyAppServer\ βββ manage.py βββ ... βββ myapp_django_server\ βββ urls.py βββ wsgi.py βββ ... βββ myapp_web_app\ βββ ... βββ myapp_core\ βββ __init__.py βββ db.pyd βββ all_other_classes.pyd βββ ... The problem is that, when I try to run the application, using ISS I get this error in the browser: Traceback: File "C:\Software\MyApp\py2_env\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Software\MyApp\py2_env\lib\site-packages\django\core\handlers\base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "C:\Software\MyApp\py2_env\lib\site-packages\django\urls\resolvers.py" in resolve 362. for pattern in self.url_patterns: File "C:\Software\MyApp\py2_env\lib\site-packages\django\utils\functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "C:\Software\MyApp\py2_env\lib\site-packages\django\urls\resolvers.py" in url_patterns 405. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Software\MyApp\py2_env\lib\site-packages\django\utils\functional.py" in __get__ 35. res = β¦ -
Sending JSON to the Django backend
I have an object in Angular const obj = {name: 'someName'}; And I stringify it: const data = JSON.stringify(obj); And when I'm trying to send this data to Django backend (and then, backend try to deserialize string I get an error) JSONDecodeError at /some_endpoint Expecting property name enclosed in double quotes: line 1 column 2 (char 1) And how request looks like in Chrome DevTools, in request payload data: "{"name":"someName"}" How to correct send this payload? Do I have to change data before send? -
OSError: Too Many Open Files during SMTP send email Django Core. How do I close the SMTP connection opened by Django Core send_mail method?
Traceback (most recent call last): File "/opt/anaconda/lib/python3.6/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/opt/anaconda/lib/python3.6/site-packages/django/core/mail/message.py", line 294, in send return self.get_connection(fail_silently).send_messages([self]) File "/opt/anaconda/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/opt/anaconda/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 63, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/opt/anaconda/lib/python3.6/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/opt/anaconda/lib/python3.6/smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "/opt/anaconda/lib/python3.6/smtplib.py", line 307, in _get_socket self.source_address) File "/opt/anaconda/lib/python3.6/socket.py", line 704, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): File "/opt/anaconda/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): OSError: [Errno 24] Too many open files -
How I can show multiple with respect to count in D3?
Here is an example taken from : http://bl.ocks.org/natemiller/7dec148bb6aab897e561 working fine. <!DOCTYPE html> <meta charset="utf-8"> <style> svg { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .y.axis path { fill: none; stroke: #000; shape-rendering: crispEdges; } .brush .extent { stroke: #fff; fill-opacity: .125; shape-rendering: crispEdges; } .line { fill: none; } </style> <body> <script src="http://d3js.org/d3.v3.min.js"></script> <script> var margin = {top: 10, right: 10, bottom: 100, left: 40}, margin2 = {top: 430, right: 10, bottom: 20, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom, height2 = 500 - margin2.top - margin2.bottom; var color = d3.scale.category10(); var parseDate = d3.time.format("%Y%m").parse; var x = d3.time.scale().range([0, width]), x2 = d3.time.scale().range([0, width]), y = d3.scale.linear().range([height, 0]), y2 = d3.scale.linear().range([height2, 0]); var xAxis = d3.svg.axis().scale(x).orient("bottom"), xAxis2 = d3.svg.axis().scale(x2).orient("bottom"), yAxis = d3.svg.axis().scale(y).orient("left"); var brush = d3.svg.brush() .x(x2) .on("brush", brush); var line = d3.svg.line() .defined(function(d) { return !isNaN(d.temperature); }) .interpolate("cubic") .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.temperature); }); var line2 = d3.svg.line() .defined(function(d) { return !isNaN(d.temperature); }) .interpolate("cubic") .x(function(d) {return x2(d.date); }) .y(function(d) {return y2(d.temperature); }); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + β¦ -
Celery dont register periodic tasks
Im trying to run celery worker, but when i do that Celery cant see my periodic tasks for some reason. Here is my console output: ------------- celery@andrey-MS-7996 v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Linux-4.15.0-39-generic-x86_64-with-Ubuntu-18.04-bionic 2018-12-03 13:49:13 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: sjimalka:0x7fa69bef3e48 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] [2018-12-03 13:49:13,380: INFO/Beat] beat: Starting... [2018-12-03 13:49:13,385: INFO/MainProcess] Connected to redis://localhost:6379/0 [2018-12-03 13:49:13,392: INFO/MainProcess] mingle: searching for neighbors [2018-12-03 13:49:14,409: INFO/MainProcess] mingle: all alone [2018-12-03 13:49:14,432: WARNING/MainProcess] /home/andrey/.local/lib/python3.6/site-packages/celery/fixups/django.py:200: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('Using settings.DEBUG leads to a memory leak, never ' [2018-12-03 13:49:14,433: INFO/MainProcess] celery@andrey-MS-7996 ready. init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sjimalka.settings') app = Celery('sjimalka') app.conf.timezone = 'Europe/Moscow' app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() β¦ -
ModuleNotFoundError: No module named 'gamingispassion/settings.production' PYTHONANYWHERE
I'm trying to host my website on pythonanywhere but after lots of trying I'm gettings this error. This is the path of settings file: '/home/gamingispassion/django_project/src/gamingispassion/settings/production' I have tried 'gamingispassion.settings', 'gamingispassion/settings/production' but not any success. Please help me out with this problem. EDIT: I have tried '.gamingispassion/settings/production' and now i'm gettings this error TypeError: the 'package' argument is required to perform a relative import for '.gamingispassion/settings/production' -
How to update the database by getting the data from chart(created by using random number) using sqlite in django and stored that random no to database
I want to know that how to update the database by getting the data from the random value of temperature and humidity chart and that value will automatically update and store the database with timespan. view.py from django.contrib.auth import get_user_model from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from .models import * import random from rest_framework.views import APIView from rest_framework.response import Response User=get_user_model() class HomeView(View): def get(self,request,*args,**kwargs): return render(request,'charts.html',{}) def get_data(request,*args,**kwargs): data={ } return JsonResponse(data) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): qs_count=User.objects.all().count() labels=["0", "2", "4", "6", "8", "10","12","14","16","18"] default_items=[] for items in range(10): t=random.randint(0,50) default_items=default_items+[t] data={ "labels":labels, "default":default_items, } return Response(data)`` chart.html <meta http-equiv="refresh" content="2"> {% extends 'base.html' %} <script type="text/javascript"> {% block jquery %} var endpoint='/api/chart/data/' //{% url "api-data" %} var defaultData=[] var labels=[] $.ajax({ method:'GET', url:endpoint, success:function(data) { labels=data.labels defaultData=data.default setChart() }, error:function(error_data){ console.log(error) console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("Temp"); var ctx2 = document.getElementById("Hmdt"); var Hmdt = new Chart(ctx2, { type: 'bar', data: { labels: labels , datasets: [{ label: 'Max Humidity', data: defaultData, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, β¦ -
KeyError when trying to publish some pages in django-cms 3.0 under python 2.7
After some moment on some pages, not all, such an error takes off: <div> <div> <div class="adm"> <div id="q_3471" class="ajR h4" data-tooltip="Π‘ΠΊΡΡΡΡ ΡΠ°Π·Π²Π΅ΡΠ½ΡΡΡΡ ΡΠ°ΡΡΡ" aria-label="Π‘ΠΊΡΡΡΡ ΡΠ°Π·Π²Π΅ΡΠ½ΡΡΡΡ ΡΠ°ΡΡΡ"> <div class="ajT"></div> </div> </div> <div class="im"> <h1>KeyError at /ru/admin/cms/page/6154/ru/<wbr>publish/</h1> <pre style="font-size:12pt">221273</pre> <br> <h2>Traceback</h2> </div> </div> <div style="font-size:10pt"> <ul> <div> <div class="adm"> <div id="q_3469" class="ajR h4" data-tooltip="Π‘ΠΊΡΡΡΡ ΡΠ°Π·Π²Π΅ΡΠ½ΡΡΡΡ ΡΠ°ΡΡΡ" aria-label="Π‘ΠΊΡΡΡΡ ΡΠ°Π·Π²Π΅ΡΠ½ΡΡΡΡ ΡΠ°ΡΡΡ"> <div class="ajT"></div> </div> </div> <div class="im"> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/core/handlers/base.py</code> in <b><i><code>get_response</code></i></b><br> <div> <ol start="112"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> response = wrapped_callback(request, *callback_args, **callback_kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/utils/decorators.py</code> in <b><i><code>_wrapped_view</code></i></b><br> <div> <ol start="99"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> response = view_func(request, *args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/views/decorators/cache.<wbr>py</code> in <b><i><code>_wrapped_view_func</code></i></b><br> <div> <ol start="52"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> response = view_func(request, *args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/contrib/admin/sites.py</code> in <b><i><code>inner</code></i></b><br> <div> <ol start="198"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> return view(request, *args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/db/transaction.py</code> in <b><i><code>inner</code></i></b><br> <div> <ol start="431"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> return func(*args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>reversion/revisions.py</code> in <b><i><code>do_revision_context</code></i></b><br> <div> <ol start="300"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> return func(*args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/cms/<wbr>admin/pageadmin.py</code> in <b><i><code>publish_page</code></i></b><br> <div> <ol start="1038"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> published = page.publish(language)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/cms/<wbr>models/pagemodel.py</code> in <b><i><code>publish</code></i></b><br> <div> <ol start="567"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> β¦ -
Multiple Models in Django-filter 1.1.0
I'd like to implement a filter for the end user of the site, so that they can filter by price, rating, gender and location. The problem here is that price and rating are stored in the models class "comment" and the location and gender in the models class "adventure". In the class "comment" the "adventure" is referenced by a foreign key. How can I use Django-filter 1.1.0 in my filters.py to address both models "comment" and "adventure" that reference each other, to filter according to the above mentioned arguments? Here is my code that works, but only filters the class "adventure". How can I extend this code to also filter by the foreign referenced arguments to return the matching adventures? filters.py import django_filters class AdventureFilter(django_filters.FilterSet): class Meta: model = Adventure fields = { 'gender', 'location', } models.py class Comment(models.Model): verfasser = models.ForeignKey(User, on_delete=models.CASCADE) related_adventure = models.ForeignKey(Adventure, on_delete=models.CASCADE, related_name='comments') rating_choices = ( (1, '1 Stern'), (2, '2 Sterne'), (3, '3 Sterne'), (4, '4 Sterne'), (5, '5 Sterne') ) Rating = models.PositiveIntegerField(null=True, choices=rating_choices,blank=False, default=0) verfasst_am = models.DateTimeField(default=timezone.now, blank=True, null=True) heading = models.CharField(max_length=100,blank=True,null=True, help_text="100 Zeichen") ratingtext= models.TextField(max_length=400, blank=True, null=True,help_text="400 Zeichen") price = models.PositiveIntegerField(null=True, help_text="Deine Ausgaben (pro Kopf) bei diesem Adventure", blank=True) class Adventure(models.Model): β¦ -
How to save data to the same model from forms in different pages...Registration multiple fields? Django
i'm trying to make a user registration with multiple fields to save in the same model. The idea is have a form in the home page with username and password and when press button continue the user is redirected to another page with multiple fields to insert personal info for the user profile. I imagine i must have to different views for that, but i don't understand how put all this data together. Thanks! -
Update value of a column using existing column value in Django
how to perform following SQL operation using Django object: update table set column = column+x where column>5 -
How to make a simple ini of this uwsgi launch command
I would like to create a uwsgi_websocket.ini for a process that I launch using this command: uwsgi --http-socket web.socket --gevent 1000 --http-websockets --workers=2 --master --module main.wsgi_websocket So far my uwsgi file looks like this [uwsgi] # ----- Django-related settings ----- # the base directory (full path) chdir=/home/ec2-user/FooVenv/FooWeb/ module=main.wsgi_websocket # the virtualenv (full path) home=/home/ec2-user/FooVenv/ # pidfile=/path/to/site1.pid # master master=true # maximum number of worker processes processes=1 # the socket (use the full path to be safe) socket=/home/ec2-user/FooVenv/FooWeb/web.socket chmod-socket=664 # clear environment on exit vacuum=true My question is how do I specify the followings in my ini file --http-socket web.socket --gevent 1000 --http-websockets Also what is the purpose of specifying a pid file and what should that be ? -
Adding numbers from SQlite in django showing in WebApp
I'm trying to make a personal WebApp with Django/Python, all works out so far, just that i want to display: total ammount, balance ect...... in my WebApp and i can't figure it out how to do is. Can someone help me out here? Thanks! Models.py class Bills(models.Model): bank = models.CharField(max_length=40) name = models.CharField(max_length=40) ammount = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.bank Views.py def index(request): return render(request, 'budget/index.html') def bills(request): bills_list = Bills.objects.order_by('id') context = {'bills_list': bills_list} return render(request, 'budget/bills.html', context)