Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: TestCase shows error only in script
I am checking whether my code runs correctly or not, using testcases If I run in the command line it works correctly >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> from django.urls import reverse >>> response = client.get(reverse('polls:detail',args=(1,))) >>> response.context [{'True': True, 'False': False, 'None': None}, {'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0xb74425ec>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0xb69feecc>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0xb7440bfc>>, 'csrf_token': <SimpleLazyObject: 'FrAJ52rWG57SSbSE9y4V2tammjvQqjBUyl2tK6aEzj8ZfENSyFl7Fy05bnQh3XyQ'>, 'request': <WSGIRequest: GET '/polls/1/'>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'object': <Question: What's Up?>, 'question': <Question: What's Up?>, 'view': <polls.views.DetailView object at 0xb6a2fd4c>}] >>> response.context['question'] <Question: What's Up?> But if test in the script it throws a key error: from django.test import TestCase from django.utils import timezone import datetime from polls.models import Question from django.urls import reverse def create_question(question_text,days): time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text,pub_date=time) class QuestionDetailViewTests(TestCase): def test_past_question(self): past_question = create_question(question_text='past question',days=30) response = self.client.get(reverse('polls:detail',args=(past_question.id,))) self.assertQuerysetEqual(response.context['question'],['<Question: past question>']) It throws the following error: (mysite) sugumar@sugushivaatgmaildotcom:~/python/django/mysite$ python manage.py test polls Creating test database for alias 'default'... System check identified no issues (0 silenced). ......... ---------------------------------------------------------------------- Ran 9 tests in 0.061s OK Destroying test database for alias 'default'... (mysite) sugumar@shiva:~/python/django/mysite$ … -
How to apply variable taxes in a Strategy in django oscar?
I am working on an oscar project for India and now I want to apply taxes on products. I have followed the docs for applying taxes over prices and availability , forked the partner app. When I specified rate=('0.20'), it applied a tax of 20 % on all products, now I want to make it dynamic. So I went through the code for strategy.FixedRateTax,and I tried implementing the code for get_rate(), since it gets called for all the products. How I want to make it dynamic is, based on the product category I want to apply the tax on the product which is in get_rate(). So I created a model in core/models.py class CategoryTax(models.Model): category = models.OneToOneField(Category, on_delete=models.CASCADE, unique=True) gst_tax = models.DecimalField(max_digits=11, decimal_places=4, null=True, default=0) def __str__(self): return "%s" % self.category Here importing of the category model is working fine,but when I go to the strategy.py and import models from core, and the other apps, django gives an exception. My forked_apps/partner/strategy.py is: from decimal import Decimal as D from oscar.apps.partner import strategy, prices from django.conf import settings from oscar.core.loading import get_model from core.models import CategoryTax Partner = get_model('partner', 'Partner') Category = get_model('catalogue', 'Category') Product = get_model('catalogue', 'Product') ProductCategory = get_model('catalogue', … -
How to create a custom default text in choicefield
In my web application, i have a drop-down list created using ModelForm which is rendering well, however, i can't set default text like "Choose One Option", rather its showing the default "----" which I would love to override I have tried using forms.ChoiceField in my widgets but its still not making any difference from django import forms from . import models from .models import FacultyData class DepartmentCreationForm(forms.ModelForm): class Meta: model = models.DepartmentData fields = ['fid', 'dept_name'] data = [] #data.append((None, 'select one')) data.append(('20', "---Choose One---")) CHOICES = FacultyData.objects.all() for v in CHOICES: # fname = "%s -- $%d each" % (v.faculty_name, v.created_on) data.append((v.id, v.faculty_name)) widgets = { 'fid': forms.Select(attrs={'class': 'form-control'}), 'dept_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Department Name'}) } I expect the default output to be "Select One" but the actual output is "-----" -
Google Sign-in in Android with django-rest-auth
I've been trying to add Google Sign-In in Android but have a couple of doubts. From the Android documentation Integrate google sign in android In the server side authentication part Client Id is required which is OAuth 2.0 web application client ID for your backend server. From android's documentation: Get your backend server's OAuth 2.0 client ID If your app authenticates with a backend server or accesses Google APIs from your backend server, you must get the OAuth 2.0 client ID that was created for your server. To find the OAuth 2.0 client ID From my understanding the flow would be: Android app will get the auth code from google which will be passed to the backend. The backend will get the access token with the auth code from the android app and the client secret. With the acess token we get the user's information and the access token is saved in the database. My doubts are: I read somewhere on StackOverflow that we need to create two OAuth client one for Android and one for Web Application. Is this True? Django Rest Auth Login View need to have one redirect_url defined but I don't understand what would be the … -
django PDF FileResponse "Failed to load PDF document."
I am trying to generate and output PDF from a django view. I followed the example in django documentation using ReportLab but the downloaded PDF is not opening in any PDF readers. I use Python 3.7.0, Django==2.1.3, reportlab==3.5.12. I tried adding content_type="application/pdf" to 'FileResponse` but still having the same issue. import io from django.http import FileResponse from reportlab.pdfgen import canvas def printPDF(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) p.drawString(100, 100, "Hello world.") p.showPage() p.save() return FileResponse(buffer, as_attachment=True, filename='hello.pdf') The generated PDF should be opening in all PDF readers. But I am getting 'Failed to load PDF document.' -
How can I resize only the width in django Imagefield
Intro: I need to reduce the size of django images in my Profile Images such that the width is 300px and the height is decided automatically as proportionate to the original picture. How do I do that with my below code class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(upload_to='profile_images/', default='', blank=True, null=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # Opening the uploaded image im = Image.open(self.profile_image) output = BytesIO() # Resize/modify the image im = im.resize((300, 250)) #Here the width is 300 and height is 250. I want width to be 300 and height to be proportionately added. How do I modify the above code # after modifications, save it to the output im.save(output, format='JPEG', quality=100) output.seek(0) # change the imagefield value to be the newley modifed image value self.profile_image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.profile_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Profile, self).save() -
Display Image from another website on Django template
I'm here wondering over one problem since 2 days and still not getting the solution. The problem is, I have one website URL e.g. "www.something.org/abc/xyz/". On this website there is a list of URLs which contains some images in JPG format. This URLs are like e.g."2019_01_03_11_12_12_..>" and when I click it, it opens as "www.something.org/abc/xyz/2019_01_03_11_12_12_648626_155_72_6372_6835.jpg". I also want to store these Image Name values separately in database models with certain fields like FacultyID, CourseID, Datetime and likewise. Image must will be stored on server or some other location. Now what I have to do is, I have to display these images from the website on my Django Template. I tried several approaches for doing this. First I tried to scrap this website data and stored it in textfile on my local machine. But after that I din get how to use this data to display images. Now please help me out to find the proper approach of this problem in Django- Python. Forget my approach and suggest me something which carry out the results. I'm waiting for the answers. Please help and get me out of this. -
django rest-auth/registration email validation
I have the following in my settings in the django rest framework app: #settings.py REST_USE_JWT = True SITE_ID = 1 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'mytestaccount@gmail.com' EMAIL_HOST_PASSWORD = 'mytestaccountPassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER ACCOUNT_EMAIL_REQUIRED = True with this settings I can sign up a new user and the following message pops up in console upon registration : """""From: mytestaccount@gmail.com To: test3@gmail.com Date: Sat, 05 Jan 2019 05:15:11 -0000 Message-ID: <154666531119.43600.12499673333763651759> Hello from example.com! You're receiving this e-mail because user amir3 has given yours as an e-mail address to connect their account. To confirm this is correct, go to http://127.0.0.1:8000/rest-auth/registration/account-confirm-email/OA:1gfeIh:QM0KigIvCJXX5otapkQccUMfbwk/ Thank you from example.com! example.com"""""" my question is that how can I make it to actually email me rather than just printing in console. I tried the following setting instead: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' but what happens is that the user will be added to the database with no email sent, let alone verifying by clicking the link, Would you please let me know what am I missing here, Thanks, -
How to use slave database when master database is locked in django?
I am using sqlite3 and MySQL databases. When sqlite3 is locked is there any way to use MySQL? -
Nonetype object has no attribute is_ajax
I am using Django-bootstrap-modal-forms in my project. But I want little customization and have added Upload and Author field as foreign key. If I do as of the library it works fine. But here I am getting Nonetype object has no attribute is_ajax. I don't know why it is Nonetype even though I am logged in. Model : class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) visible_to_home = models.ManyToManyField(Home, blank=True) # when none visible to all home visible_to_company = models.ManyToManyField(Company, blank=True) # when none visible to all company # To determine visibility, check if vtc is none or include company of user and if true, check same for home created_date = models.DateTimeField(auto_now=True) published = models.BooleanField(default=True) upload = models.FileField(blank=True, null=True, upload_to=update_filename) title = models.CharField(max_length=225, blank=True, null=True) description = models.TextField(blank=True, null=True) Forms class FileForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm): class Meta: model = File fields = ('title', 'description', 'upload') View class FileCreateView(PassRequestMixin, SuccessMessageMixin, CreateView): template_name = 'file/upload-file.html' form_class = FileForm success_message = 'File was uploaded successfully' success_url = reverse_lazy('home') def post(self, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ #form = self.get_form() form = self.form_class(self.request.POST, self.request.FILES) if self.request.method … -
serve static files from Django Docker to nginx
I'm dockerizing Django application but static files are not being served. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(os.path.dirname(BASE_DIR), 'static_my_project') ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'static_root') docker-compose.yml services: nginx: image: nginx:alpine container_name: "originor-nginx" ports: - "10080:80" - "10443:43" volumes: - .:/app - ./config/nginx:/etc/nginx/conf.d - originor_static_volume:/app/static_cdn/static_root - originor_media_volume:/app/static_cdn/media_root depends_on: - web web: build: . container_name: "originor-web" command: ["./wait-for-it.sh", "db:5432", "--", "./start.sh"] volumes: - .:/app - originor_static_volume:/app/static_cdn/static_root - originor_media_volume:/app/static_cdn/media_root ports: - "9010:9010" depends_on: - db db: image: postgres:11 container_name: "originor-postgres-schema" volumes: - originor_database:/var/lib/postgresql/data ports: - "5432:5432" pgadmin: image: dpage/pgadmin4 container_name: "originor_pgadmin" volumes: - originor_pgadmin:/var/lib/pgadmin volumes: originor_database: originor_static_volume: originor_media_volume: originor_pgadmin: and nginx.conf server { ... location / { proxy_pass http://web; } location /static/ { alias originor_static_volume; } } But on access /admin/ in browser, it consoles f032d416bce1_originor-web | Not Found: /static/admin/css/login.css f032d416bce1_originor-web | Not Found: /static/admin/css/responsive.css f032d416bce1_originor-web | Not Found: /static/admin/css/base.css f032d416bce1_originor-web | Not Found: /static/admin/css/base.css I can verify the files there in /app/static_cdn/static_root directory by executing docker exec -it <container_id> ls -la /app/static_cdn/static_root -
How to make a reverse in DefaultRouter()
I'm setting up a new tests, and i want to make an reverse. router = DefaultRouter() router.register('profile', views.UserProfileViewSet, base_name='profile') urlpatterns = [ url(r'', include(router.urls)) ] So , i want make a reverse in tests.py. my shot is: CREAT_USER_URL = reverse('profile-create') And I simply get: Reverse for 'profile-create' not found. 'profile-create' is not a valid view function or pattern name. How should I set up a reverse in this case. -
Running setup.py install for mod-wsgi-packages: finished with status 'error'
I get this error below when i am trying to deploy my python app on heroku. Attached here are my requirements.txt file. certifi==2018.11.29 cfe==0.0.15 chardet==3.0.4 Cython==0.29.2 dj-database-url==0.5.0 Django==2.1.2 gitdb2==2.0.5 GitPython==2.1.11 gunicorn==19.9.0 idna==2.8 libsass==0.16.1 mod-wsgi==4.6.5 numpy==1.15.4 olefile==0.46 Pillow==5.3.0 pipenv==2018.11.26 psycopg2==2.7.6.1 pystan==2.18.0.0 pytz==2018.7 requests==2.21.0 setuptools==40.5.0 six==1.12.0 smmap2==2.0.5 urllib3==1.24.1 virtualenv==16.2.0 virtualenv-clone==0.4.0 wheel==0.32.2 the error message: remote:Running setup.py install for mod-wsgi-packages: started remote:Running setup.py install for mod-wsgi-packages: finished with status remote:adding packages/apr/build-1/mkdir.sh remote:adding packages/apr/build-1/libtool remote:adding packages/apr/build-1/make_exports.awk remote:adding packages/apr/build-1/apr_rules.mk remote: adding packages/apr/build-1/make_var_export.awk . . . . remote:/usr/bin/ld: final link failed: Bad value remote:collect2: error: ld returned 1 exit status remote:error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote:Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-3h0_r0m2/mod- wsgi/setup.py';f=getattr(tokenize, 'open', open) (file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install -- record /tmp/pip-z7cobg1q-record/install-record.txt --single-version- externally-managed --compile" failed with error code 1 in /tmp/pip- build-3h0_r0m2/mod-wsgi/ remote:Push rejected, failed to compile Python app. remote: remote:Push failed remote: Verifying deploy... remote: remote:Push rejected to python-tehila. remote: To https://git.heroku.com/python-tehila.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/python- tehila.git' -
Django & beforeunload event
I wanted to use the following code to fade the page out when the beforeunload event is fired. window.addEventListener("beforeunload", function (event) { $(document.body).fadeOut(600); }); I noticed that the page fades as expected when leaving and going to a different site, but the page does not fade when going from one app in my Django-powered site to another. Can anyone explain this behavior to me? I am just curious as to how Django is not causing the beforeunload event to fire. -
Some changes in docker container not being reflected in local code
Inside the docker container, I can make changes to /app directory and the changes will be reflected in my local code. Similarly, I can make changes in my local code and these changes will be reflected in the docker container. Inside the /app folder I have got /static directory. I can make changes inside /static and I can run the updated application, however these changes are not reflected in my local code. So basically changes to anything in static folder is not being reflected in local code. I thought it could be a permissions problem, ls -l showed that every folder in the /app directory was owned by user 'm' and group 'm', except the static directory which was owned by the user 'm' but belonged to the group 'root', but changing the group using chgrp didnt fix the issue. I thought I would try and seek some solution before attempting docker system prune. version: '3.2' services: app: #build: . image: tutorial:v1 volumes: - .:/app - static_volume:/app/static/ networks: - nginx_network - db_network depends_on: - db nginx: image: nginxtest ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/app/static/ depends_on: - app networks: - nginx_network db: image: tutorialdb:v1 env_file: - .env restart: always … -
Django-React app puts Error when deploying to heroku
I've created a very simple Django - React app which actually shows only the main page. I used create-react-app. when I type git push heroku master I receive that error: remote: Building source: remote: remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_ENV=production remote: NODE_MODULES_CACHE=true remote: NODE_VERBOSE=false remote: remote: -----> Installing binaries remote: engines.node (package.json): 8.10.0 remote: engines.npm (package.json): 3.5.2 remote: remote: Resolving node version 8.10.0... remote: Downloading and installing node 8.10.0... remote: Bootstrapping npm 3.5.2 (replacing 5.6.0)... remote: npm 3.5.2 installed remote: remote: -----> Building dependencies remote: Installing node modules (package.json) remote: npm ERR! Linux 4.4.0-1031-aws remote: npm ERR! argv "/tmp/build_0a81cf9bbf3f1ba3a96d3d0cf2296f25/.heroku/node/bin/node" "/tmp/build_0a81cf9bbf3f1ba3a96d3d0cf2296f25/.heroku/node/bin/npm" "install" "--production=false" "--unsafe-perm" "--userconfig" "/tmp/build_0a81cf9bbf3f1ba3a96d3d0cf2296f25/.npmrc" remote: npm ERR! node v8.10.0 remote: npm ERR! npm v3.5.2 remote: npm ERR! code MODULE_NOT_FOUND remote: remote: npm ERR! Cannot find module 'internal/util/types' remote: npm ERR! remote: npm ERR! If you need help, you may report this error at: remote: npm ERR! <https://github.com/npm/npm/issues> remote: remote: npm ERR! Please include the followingfile with any support request: remote: npm ERR! /tmp/build_0a81cf9bbf3f1ba3a96d3d0cf2296f25/npm-debug.log remote: remote: -----> Build failed remote: remote: We're sorry this build is failing! You can troubleshoot common issues here: remote: https://devcenter.heroku.com/articles/troubleshooting-node-deploys remote: remote: Some possible problems: … -
Sending Data from jsavascript to python
I have read through all the postings and cannot find anything that will work for my program. I am using the mapbox js framework and want to send the users location 'position' to my python view code to store it in a database. When I do a console.log() in the js code it doesnt print anything. When I do a print in python it prints 'None'. I tried ajax like other posts had but nothing seems to work. Maybe I am going about passing data from templates to python code in the wrong way... Please help home.html {% extends "geotracker/base.html" %} {% load static %} {% block content %} <body> <div id='map' width='100%' style='height:400px'></div> <form id="myform" name="myform"> {% csrf_token %} <input type="hidden" id="location" name="location"/> </form> <script> mapboxgl.accessToken = 'mytoken'; var map = new mapboxgl.Map({ container: 'map', // container id style: 'mapbox://styles/mapbox/streets-v9', center: [-96, 37.8], // starting position zoom: 3 // starting zoom }); // Add geolocate control to the map. var geolocate = new mapboxgl.GeolocateControl(); map.addControl(geolocate); geolocate.on('geolocate', function(e) { var lon = e.coords.longitude; var lat = e.coords.latitude var position = [lon, lat]; var element = document.getElementById('location'); element.innerHTML = position; //console.log(position); var frm = $('#myform'); frm.submit(function (ev) { console.log('submitting...'); $.ajax({ type: … -
Django Authentication credentials separate from user data
I am building a system where many accounts will not have login credentials (e.g companies) unless specifically provided. In order to achieve this, I have the following account model (not implemented yet, currently designing on a piece of paper): Table: Account Fields: ID, fname, lname, type, created_at, activated_at Table: AccountCredentials Fields: Account ID, email, password Relations: Account <- 1-to-1 -> AccountCredentials All permissions, operations etc will be performed over the Account model; so, the Account model will be the django auth user model. I have used custom User models and managers before; however, this is something I am not sure how to implement. How should I tell the AbstractBaseUser model to authenticate using credentials.email and credentials.password (credentials being the relation name between Account and AccountCredentials)? From checking AbstractBaseUser source code and checking some files, it seems like I can override get_username method; so that, the username field is being read from credentials. However, I am not sure how to do the same for password as it is hard coded in model. -
Django optional field with format check
i want to make the key field optional at the signup. but i dont know why i can't use == None here. The form always responses that it expected data for the key field. how do i skip this check if no key has been provided? It should only get checked if the user has provided a key. def signup(request): if request.method == 'POST': form = RegistrationForm(request.POST) key = Key.from_blob(request.POST['key'].rstrip("\r\n"))[0] if form.is_valid(): if key == None: form.save() messages.add_message(request, messages.INFO, "Thanks for you Registration, you are now able to login.") return redirect(reverse('login')) if key.key_algorithm == KeyAlgorithm.RSAEncryptOrSign: form.save() messages.add_message(request, messages.INFO, "Thanks for you Registration, you are now able to login.") return redirect(reverse('login')) else: messages.add_message(request, messages.INFO, "Only RSA keys are allowed.") else: return render(request, 'signup.html', {'form': form}) else: form = RegistrationForm() args = {'form': form} return render(request, 'signup.html', args) -
django-admin dbshell raises django.core.exceptions.ImproperlyConfigured
I know this question has been asked before, but none of them worked for me so far, so I'm going to give it a chance here. I'm trying to use MySQL as my database in django, but when I modify the settings.py and run the command: django-admin dbshell I get the following error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What I did: - I'm running windows 10. using pipenv, I create fresh virtual environment. install django. start new project. edit the settings.py in the settings.py I change the DATABASES to the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test_db', 'USER': 'root', 'PASSWORD': '****', 'HOST': '127.0.0.1', 'PORT': '3306', } } also pip installed mysqlclient Weird thing is that when I make migrations, new tables are created, which means that DB works. why doesn't the command django-admin dbshell work? -
Django, How to enforce model Foreinkeys to have same value
In Django I want to enforce that a model which has two foreinkeys of differents models which has the same type of field to be the same, in example: class Model1(models.Model): f1 = models.CharField(max_length=48) class Model2(models.Model): f1 = models.CharField(max_length=48) class Model3(models.Model): field1 = models.ForeignKey(Model1) field2 = models.ForeignKey(Model2) I want that creation of objects of Model3 would be made only if f1 field of Model1 and Model2 are the same. Thanks, -
What is the right way to handle views for multiple layers of user privileges?
Imagine this scenario: I want to set up a simple blog with three layers of privileges: author, moderator and admin. I am wondering what the best way to manage templates would be. Depending on the user type, all pages of the app should look in a different way. For example, moderators should have "mod panel" in the navbar and little red "crosses" allowing them to delete comments. Admins should be able to delete posts, etc. The only common element that appears on every page is the navbar. Thus, I have created four basic templates: logged.html, not-logged.html, mod.html and admin.html. Now, let's say that I need the index page to look differently for all types of users - this leads to not-logged-index.html, logged-index.html, mod-index.html, admin-index.html Then, I repeat the same routine for all pages that need to be altered depending on the user. My attempt solves this problem, but the number of templates escalates very quickly. Is there a better way to tackle this? -
Django - getting a syntax error in a class generic views
Right now I`m learning django and going through documentation. And when I try to use generic views it gives me an exeption: File "/home/jeffr/Рабочий стол/codetry/mysite1/polls/views.py", line 8 def IndexView(generic.ListView): ^ SyntaxError: invalid syntax This is my views.py: from django.views import generic from .models import Choice, Question def IndexView(generic.ListView): template_name = 'polls/index.html' contest_object_name = 'latest_question_list' get_queryset(self): """Return the last five published questions""" return Question.objects.order_by('-pub_date')[:5] def DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' The full traceback paste can be found here: http://dpaste.com/3QMN3A0 Any help would be greatly appreciated, Thanks -
Do I even need Django?
I'm currently building a website where vendors from my city can authenticate and post their products, so users can search and buy them. I started building the website with Django; in the meantime, I was taking a beautiful ReactJS 30+ hours online course and learning how much you can do with it: not only pure frontend, e.g. Routing, GET/POST requests, Forms and validation, Authentication. My initial idea was building the website with Django Rest (backend) AND React (frontend), but now I have a question: Can I build my buy&sell website with React ONLY? (maybe using some pre-made backend networks like Firebase to save/fecth data to/from a database, to save time). In your opinion would I need some backend functionalities which would be impossible/inconvenient to implement with React, Firebase or other services? Please consider that I'm talking about a quite standard buy&sell website with authenticated vendors and buyers. Thank you very much for any advice. -
jquery accordion cutting off buttons
I was trying to get fancy and wire in a jquery accordion into my form (to split up parts of the form they may never really want to ever change and keep it out of the way). The original django form was in the html under: just a cold-md-12 with other md-6s to split form into two columns. Now with accordion I have it based on the example on the website (http://jqueryui.com/accordion/#default) : {% block page-js %} $( function() { $( "#accordion" ).accordion({ heightStyle: "content" }); } ); {% endblock %} <div id="accordion"> <h1> Section 1</h1> <div> <div class="col-md-12"> <h2>Group</h2> <form id="group_create_form" action="." class="form-horizontal" method="post"> {% csrf_token %} {{ group_form.non_field_errors }} <div class="col-md-6"> {{ group_form.group_name.errors }} {{ group_form.group_name.label_tag }} {{ group_form.group_name }} </div> ..rest of form.. ..then two form groups side by side <div class="form-group col-md-6"> <label for="provider_search_name">Name: </label> <div class="col-md-6"> <input id="search_name" name="search_name" class="form-control"/> <input type="hidden" id="search_name_id" name="search_name_id" value="" /> </div> <div class="col-md-6"> <button type="button" class="btn" id="SearchAdd">Add</button> <button type="button" class="btn" id="SearchClear">Clear</button> </div> <label for="add_name">Click on name to remove </label> <div class="col-md-12"> <select id='add_name' name='add_name' class='form-control' size='5' multiple='multiple'> {% for pro in associated_providers %} <option value="{{ pro.value }}">{{ pro.label }}</option> {% endfor %} </select> </div> </div> <div class="form-group col-md-6"> ..another …