Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Blockchain API Error: Wallet Password incorrect [And It's correct]
I want to work with blockchain api in my django web app. After installing the blockchain-service module and starting the server, I input the right wallet password and I'm getting error: main wallet password incorrect The endpoint http://localhost:3000/merchant/d536-46464-9575756-38474646/enableHD?password=pooo Versions: Nodejs: 8.9.1 npm: 5.5.1 wallet-service: 0.26.0 Could this be a bug with blockchain module or what am I missing? -
Django automatically converting datetime stirng to local timezone
I am adding timestamp in my payload and storing it in the database for every record. Suppose say a part of my payload is {"content":[{"timestamp":"2017-12-12 08:05:30"}] This is how I process it. content['timestamp'] = parser.parse(content['timestamp'],dayfirst=True) My model has timestamp field as : timestamp = models.DateTimeField(null=True) When I check in my database it stores timestamp field as : 2017-12-12 13:35:30 Which should be stored as it is as per my requirement. 2017-12-12 08:05:30 i.e it stores the timestamp field + my local timezone(+5:30) hours. I want it to store the timestamp field as it is. I tried other posts where they suggest using del os.environ['TZ']. Any help is appreciated. -
Django form with checkbox is always False
I'm looking to create a Django form with a checkbox.Irrespective of weather I check or uncheck the box,it is not detected in POST request.Here is the code of the template- <form action="annotate_page" method="post">{% csrf_token %} <input id="repeat" type="checkbox" > <label for="repeat">Repeat Sentence?</label> <br> <button type="submit">Next</button><br> </form> Here is my forms.py- from django import forms class AnnotateForm(forms.Form): repeat=forms.BooleanField(required=False) Here is my views logic- if request.method=="POST": form = AnnotateForm(request.POST) if form.is_valid(): print(request.POST)#prints only csrf_token in Query_dict print(form.cleaned_data["repeat"])#Always false Irrespective of weather the checkbox is checked or not,the print statement always gives False. I know there are questions similar,but they don't solve my problem. -
'User' object has no attribute 'student_set'
class BasicInfo(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=250) class Student(Basicinfo): ... When I query : user=user.objects.get(user="name") student=Student.objects.get(username=user) But : user.student_set.all() gives error 'User' object has no attribute 'student_set'?? -
Python Django Model inheritance and display form by selected subclass type which are populated to the dropdown list
I'm beginner on django. I want to make a form which will be dynamic. I wrote a code like below but could not work it properly. models.py class Parca(models.Model): parcaAdi = models.CharField(max_length=200) parcaFiyati = models.IntegerField() iscilikUcreti = models.PositiveIntegerField() def __str__(self): return self.parcaAdi class Kaporta(Parca): boyananParca = models.CharField(max_length=100, default="") boyamaUcreti = models.PositiveIntegerField(default=0) def __str__(self): return self.parcaAdi + "\t" + self.boyananParca class Motor(Parca): pass class Elektrik(Parca): pass forms.py class ParcaForm(forms.ModelForm): class Meta: model = Parca fields = ( 'parcaAdi', 'parcaFiyati', 'iscilikUcreti', ) # sub-classes class KaportaForm(ParcaForm): class Meta(ParcaForm.Meta): model = Kaporta fields = ParcaForm.Meta.fields + ('boyananParca', 'boyamaUcreti') class MotorForm(ParcaForm): class Meta(ParcaForm.Meta): model = Motor class ElektrikForm(ParcaForm): class Meta(ParcaForm.Meta): model = Elektrik As you can see 'KaportaForm' will get extra fileds. myhtml file <form method="post"> {% csrf_token %} <table class="tablo_parca"> {{ form }} </table> <br/> <input class="submit" type="submit" value="Kaydet"/> </form> <br/> <br/> <label style="margin-left:10px;"><b>Parça Türü : </b></label> <select class="dropdown" id="dropdown" name='parcaAdi'> <option value="">Parça Türü</option> <option value="kaporta">Kaporta</option> <option value="motor">Motor</option> <option value="elektrik">Elektrik</option> </select> my ajax file: $(document).ready(function(){ $('#dropdown').on('change',function(e){ e.preventDefault(); var parca_turu = $(this).val(); console.log("Secilen: "+parca_turu); $.ajax({ url:"", method:'GET', data : {'parcaAdi' : $(this).val()}, success:function(gelen_parca_turu){ //console.log(gelen_parca_turu); } }); }); }); and my views.py def parca_kayit(request): if request.method == 'GET' and request.is_ajax(): parca_turu = request.GET.get('parcaAdi') print(parca_turu) if … -
Celery ImportError: No module named tasks while running celery process
I am trying to run a celery process using the command: /opt/vso/orchestration/uat/bin/celery -A tasks worker --loglevel=debug --config=/opt/vso/orchestration/config/celeryconfig.py However, I am getting error ImportError: No module named tasks File "/opt/vso/orchestration/uat/lib/python2.7/site-packages/celery/bin/base.py", line 311, in find_app sym = self.symbol_by_name(app) File "/opt/vso/orchestration/uat/lib/python2.7/site-packages/celery/bin/base.py", line 322, in symbol_by_name return symbol_by_name(name, imp=import_from_cwd) File "/opt/vso/orchestration/uat/lib/python2.7/site-packages/kombu/utils/__init__.py", line 80, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/opt/vso/orchestration/uat/lib/python2.7/site-packages/celery/utils/imports.py", line 99, in import_from_cwd return imp(module, package=package) File "/opt/vso/software/py275/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named tasks -
Best practice working with python variables in javascript django
I am currently access my python data in javascript like this: <script> var x = {{x|safe}}; var l = {{ l|safe }}; var sf ={{ sf|safe }} </script> this works but does not seem like the most ideal to transfer data. What is the best practice for accessing and saving data between python and javascript using django? What I am trying to do is send data from the view, manipulate using the ui and javascript/vue.js and then save the data calculated in javascript. -
how to get the email sent for VerifiedEmailField from verified_email_field.1.2.3
I want to get users that signup to verify their email addresses and from reading a previous thread on doing this, someone posted about django-verified-email-field which I have installed and followed the guidance for but am getting no email sent through. I have added verified_email_field to my settings.py in the INSTALLED_APPS. I added: url(r'^verified-email-field/', include('verified_email_field.urls')), to my urls.py I then used the field inside one of my forms: email = VerifiedEmailField(label='email', required=True) this gives no errors and renders the signup form correctly from my signup.html page, however the validation email is never sent to me. I tried the final step of adding the code: {% addtoblock "js" %} {{ form.media.js }} {% endaddtoblock %} to my html template but I get the error that the "js" block doesn't exist. I'm not sure (based on a couple of quick Google searches and dredging through the source code for the verified_email_field) whether this is part of django or part of the package. I'm also not certain if I'm doing the right thing by trying to solve this or whether I should be adding my own clean method to the form instead and then calling a function from there to send the validation … -
Enter A Valid Date issue with form - django
I notices this question came up a few times in stackoverflow but none of the answers I read worked in helping me with my situation... I have a form that is using the DatetimeField. I am submitting a proper time but it is saying that for some reason there is an error that is not validating the form before collecting the information and storing it. I want to grab the date and time that the user is submitting.. here is my code: form.py: class CreateEventForm(forms.ModelForm): alert_choices = (('1', '1 hour before'), ('2', '2 hour before'), ('3', '3 hour before'), ) start_date = forms.DateTimeField( label='Start', widget=forms.widgets.DateTimeInput(format="%d/%m/%Y %H:%M:%S", attrs={'type':'datetime-local'}), ) end_date = forms.DateTimeField( label='End', widget=forms.widgets.DateTimeInput(format="%d/%m/%Y %H:%M:%S", attrs={'type':'datetime-local'}) ) alert = forms.TypedChoiceField( choices = alert_choices, label = "Alert" ) class Meta: model = Event fields = ['name', 'start_date', 'end_date', 'location', 'notes'] Models.py class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE) name = models.CharField(max_length=30, default='Event') start_date = models.DateTimeField(default=datetime.now) end_date = models.DateTimeField(default=datetime.now) email = models.CharField(max_length=40, default='example@example.com') location = models.CharField(max_length=40, default='location') notes = models.CharField(max_length=200, default='note') repeat = models.IntegerField() # 0 = no repeat # 1 = daily # 2 = weekly # monthly created = models.DateTimeField(auto_now_add=True) screenshot my settings file: LANGUAGE_CODE = 'en-us' TIME_ZONE … -
Jinja lookup key in for loop
I pass 2 groups of data from my view.py to my html file. But only one group of data is shown in the webpage. html: <h3>Database: A</h3> <table> <tr> <th>A</th> <th>Counts A-1</th> <th>Counts A-2</th> <th>Value</th> </tr> {% load lookup %} {% for i in Amatch %} <tr> <th> {{ Amatch|lookup:forloop.counter0 }} </th> <td> {{ Amatchtotal|lookup:forloop.counter0 }} </td> <td> {{ AmatchCount|lookup:forloop.counter0 }} </td> <td> {{ Avalue|lookup:forloop.counter0 }} </td> </tr> {% endfor %} </table> <h3>Database: B</h3> <table> <tr> <th>B</th> <th>Counts B-1</th> <th>Counts B-2</th> <th>Value</th> </tr> {% load lookup %} {% for i in matchAnno %} <tr> <th> {{ Bmatch|lookup:forloop.counter0 }} </th> <td> {{ Bmatchtotal|lookup:forloop.counter0 }} </td> <td> {{ BmatchCount|lookup:forloop.counter0 }} </td> <td> {{ Bvalue|lookup:forloop.counter0 }} </td> </tr> {% endfor %} </table> view.py return render(request, 'analysis/result.html', {'Amatch':Amatch, 'Amatchtotal':Amatchtotal, 'AmatchCount':AmatchCount, 'A_re':A_re, 'Avalue':Avalue, 'Bmatch':Bmatch, 'Bmatchtotal':Bmatchtotal, 'BmatchCount':BmatchCount, 'B_re':B_re, 'Bvalue':Bvalue,}) Two groups of data are supposed to be shown on the page as I expected. However, only the data from group B is shown on the page. I tried to switch the order of group A and group B, but still only group B is shown. I'm pretty sure data are passed successfully by checking them in terminal. Are there anything wrong with my code? -
Writing a for loop with an IntegerField rather than an int
I'm trying to create a for loop for creating a dynamic number of objects in Otree, which extends Django (I know, crazy idea, but bear with me). Unfortunately the latest version of otree will throw compile time errors if you attempt to use integers in your code. So for example, the following code: num_decs = 8 for d in range(1, num_decs + 1): locals()['dec_r'+str(r)+'_'+str(d)]= models.CharField(choices=[Constants.choice1_name, Constants.choice2_name],widget=widgets.RadioSelectHorizontal(),blank=False,initial='blank') Will throw the following error (as opposed to a warning, which occurred with previous versions of Otree): (otree.E111) NonModelFieldAttr: Player has attribute "d", which is not a model field, and will therefore not be saved to the database. I imagine that the best way to resolve this would be to declare d in the for loop as an IntegerField object and then cast it as an int using the int() method as follows: num_decs = models.IntegerField(initial=8) d = models.IntegerField(default=0) for d in range(1, num_decs.__int__() + 1): But I receive an error that IntegerField lacks a int() method. What should I do to cast an IntegerField as an int for a for loop? Thanks! -
passing template name into DJango view for rendering
I am working with a DJango View. It is being implemented as a function-based view. What I would like to do is to pass in a template into the function for rendering into an HTML document. In the example below, instead of hardcoding 'storeowner/mstrstorehead_form.html', I would like to pass in a template name for use. How can this be done? I saw the information here: How should template names be set dynamically using class based views? but it deals more with Class-Based-Views TIA views.py @login_required def edit_store_data(request): success = False message = 'No changes to report' message_color = 'green' username = request.user.username local_email = request.user.email local_pass = request.user.password [... snip ... ] return render(request, 'storeowner/mstrstorehead_form.html', {'form': master_store_head_form, 'success': `success, 'message': message, 'message_color': message_color})` -
Is it possible to create partitions on db tables with django==1.11 and postgresql?
Is it possible to create partitions on db tables with django==1.11 and postgresql? Thanks a lot! -
multiple input entry search in html
` Just a quick question. I was wondering whether any one could be of help. Any idea on how to search multiple text input either as strings with comma separation or nextline (inline search) example: search (SPEED1, SPEED2, SPEED3). and get results for all the SPEEDs` -
No module named rest_framework
i've seen a lot of people having trouble with this here, and i always see them saying other to use pip3 or just pip to install it. But in my case i've uninstalled it and installed id multiple times both using pip or pip3 and none of them seem to work. I've added 'rest_framework' to my settings as well and still doesn't seem to work. Help me out please -
How to Handle Error during Django CreateView
Using Django, I have a model and a class based view based on the provided CreateView class. Everything works fine - I can have a template that renders the form, validation occurs, the data is properly saved and the success_url redirected to on completion. The problem occurs in that I have a unique_together constraint on two of the fields. If this error is hit, it appears that form_valid() doesn't catch it, and an error page is produced instead. My goal is to be able to catch this ahead of time and return the user to the form - with the data filled in from their last attempt - and display a message to them. Feels like this should be simple, and I added code to form_valid() in the view to identify the problem, but I have no clue what to do next. A redirect doesn't work because I can't add the context in (or can I?) and I really don't want to put everything in the URL. Any ideas where to look? -
How to serialize a Django MPTT family and keep it hierarchical?
I was trying to find solution for this (Google cache) And I could only came up with a solution like this: import json from mptt.utils import tree_item_iterator from rest_framework import generics from rest_framework.response import Response from .models import Category def tree_family_items_to_json(instances): data = '' channel = '"{}"'.format(instances[0].channel.slug) for category, structure in tree_item_iterator(instances): if structure['new_level']: data += '{' else: data += '],' data += '"channel": {}'.format(channel) data += '},{' data += '"slug": "{}",'.format(category.slug) data += '"name": "{}",'.format(category.name) data += '"subcategories": [' for level in structure['closed_levels']: data += '],' data += '"channel": {}'.format(channel) data += '}' return json.loads(data) class CategoryFamily(generics.RetrieveAPIView): lookup_field = 'slug' queryset = Category.objects.all() def retrieve(self, request, *args, **kwargs): instances = self.get_object().get_family() json_data = tree_family_items_to_json(instances) return Response(json_data) The point is that I used tree_item_iterator from mptt and now I'm looking for something more fancy. It suited the need for a while. But now sure for how long. Any ideas? -
object.get_or_create works, but stops working when I use models.FileField(upload_to)
I designed a webpage for users to upload and extract data from a test file. But I'm trying to prevent them from uploading and extracting data if this file has previously been uploaded (a mistake that has happened several times in the past) I created a model for the file class TestFile(models.Model): file = models.FileField() test_object = models.ForeignKey(TestObject) I created a view for the users to upload def upload_data_file(request, pk): try: mytempfile = request.FILES['myfile'] created = process_data_file(mytempfile, pk) if created: return HttpResponseRedirect(reverse('myApp:object-detail', kwargs={"pk": pk})) else: return HttpResponse("This data has previously been uploaded" "You are not allowed to upload and match this data to a different test object")) except KeyError: return HttpResponseRedirect(reverse('myApp:object-detail', kwargs={"pk": pk})) And here is my function where I process the data (removed all the processing code because my trouble is in the get_or_create) def process_data_file(myfile, my_id): a, created = TestFile.objects.get_or_create(file=myfile) if created: analyze and extract a bunch of information from the data file a.save() return created This has been working just fine except that I didn't think ahead. All of my files are going into my /media/ directory. At first this was ok but now there are at least 100 files in there and it doesn't seem like … -
voice enabled auction system in django
I wanna do my project That consists of designing and implementing a voice enabled - auction system (AS) which offers its services to end-users who can offer items for auction and bid for items.The AS allows for the end-users to register. At registration time, end-users might select the option of being notified by voice when selected events happen (e.g. end-users registering /leaving, new items put on sale, items sold).my question is how could I enable voice notification on django? thank you for your help. -
django allauth registration link issue
django v1.11.17 django-allauth: 0.34.0 Person creates new account by filling his e-mail address and password, then receives an e-mail. In this e-mail the link is clicked. PROBLEM: A user with EDGE browser v40, clicking the link from outlook sees this error message appearing in the EDGE browser itself: /head>HTTP/1.1 301 Moved Permanently Server: openresty/1.9.15.1 Date: Mon, 11 Dec 2017 22:05:32 GMT Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: keep-alive x-xss-protection: 1; mode=block x-content-type-options: nosniff Content-Language: nl strict-transport-security: max-age=600; includeSubDomains Vary: Accept-Language Location: /swingit/ X-Frame-Options: SAMEORIGIN X-Clacks-Overhead: GNU Terry Pratchett Note the missing '<' in the head tag? Could this be a link to the problem? When he presses BACK button, he ends up on the site and can login. When I try the same with a mac (Mac Mail & Safari) or windows PC (gmail & EDGE 40) there is no issue... Seeing the SAMEORIGIN remark, I tried both django settings below, but both fail: X_FRAME_OPTIONS = 'ALLOW' X_FRAME_OPTIONS = 'SAMEORIGIN'` Security Settings: SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False X_FRAME_OPTIONS = 'SAMEORIGIN' SECURE_HSTS_SECONDS = 600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True Thank you for your help! DJ -
Django objects.get not working
I'm having an trouble pulling data from my database. I'm trying to get it to display New York Yankees (or any American League team) in html from my database, using the get function. If one of you folks can point out why it may not be working, that would be greatly appreciated. Thank you. standings/models↓ from __future__ import unicode_literals from django.db import models class AlStandings(models.Model): team = models.CharField(db_column='TEAM', max_length=30, blank=True, null=True) w = models.IntegerField(db_column='W', blank=True, null=True) l = models.IntegerField(db_column='L', blank=True, null=True) pct = models.DecimalField(db_column='PCT', max_digits=4, decimal_places=3, blank=True, null=True gb = models.DecimalField(db_column='GB', max_digits=65535, decimal_places=65535, blank=True, null=True) rs = models.IntegerField(db_column='RS', blank=True, null=True) ra = models.IntegerField(db_column='RA', blank=True, null=True) diff = models.IntegerField(db_column='DIFF', blank=True, null=True) home = models.CharField(db_column='HOME', max_length=7, blank=True, null=True) road = models.CharField(db_column='ROAD', max_length=7, blank=True, null=True) east = models.CharField(db_column='EAST', max_length=7, blank=True, null=True) cent = models.CharField(db_column='CENT', max_length=7, blank=True, null=True) west = models.CharField(db_column='WEST', max_length=7, blank=True, null=True) l10 = models.CharField(db_column='L10', max_length=6, blank=True, null=True) strk = models.CharField(db_column='STRK', max_length=3, blank=True, null=True) standings/urls↓ from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), ] standings/views↓ from django.shortcuts import render from django.template.response import TemplateResponse from standings.models import AlStandings def index(request): data = AlStandings.objects.get('New York Yankees’) return TemplateResponse(request, 'standings/index.html', {"data": data}) standings/index.html↓ {% extends 'layout/layout.html' %} {% block content … -
displaying both date and time inputs from DateTImeField - Django
I have a django template and a form where I want the user to input a date and time into the right fields and save the date and time into the database. I also want to initialize a specific time when ever the form is created. I currently have the date time field in my model and form but I am not sure how to get it to display both the time and date. it is only showing the default date so far. Here is the code that I have right now. models: class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) calendar = models.ForeignKey(Calender, on_delete=models.CASCADE) name = models.CharField(max_length=30, default='Event') start_date = models.DateTimeField(default='1950-01-01') end_date = models.DateTimeField(default='1950-01-01') email = models.CharField(max_length=40, default='example@example.com') location = models.CharField(max_length=40, default='location') notes = models.CharField(max_length=200, default='note') repeat = models.IntegerField() # 0 = no repeat # 1 = daily # 2 = weekly # monthly created = models.DateTimeField(auto_now_add=True) forms: class CreateEventForm(forms.ModelForm): start_date = forms.DateTimeField( label='Start', widget=forms.widgets.DateInput(attrs={'type':'date'}), ) end_date = forms.DateTimeField( label='End', widget=forms.widgets.DateInput(attrs={'type':'date'}) ) class Meta: model = Event fields = ['name', 'start_date', 'end_date', 'location', 'notes'] views: form = CreateCalenderForm() parameters = { 'form':form, } return render(request, 'calender/create_calender.html', parameters) here is what it looks like: -
Deploying django app with channels on Daphne - SSL
I am trying to deploy a simple django app to receive websocket messages (wss). I am using the following command: daphne -e ssl:443:privateKey=key.pem:certKey=cert.cer bms_project.asgi:channel_layer with the following included in the settings.py file: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECRET_KEY = os.environ["SECRET_KEY_BMS"] and the following asgi.py file: import os from channels.asgi import get_channel_layer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bms_project.settings") # secret key os.environ["SECRET_KEY_BMS"] = "some random self-signing key off the internet" channel_layer = get_channel_layer() the following error is given: File "c:\program files\python36\lib\site-packages\django\conf\__init__.py", line 129, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I feel like I am handling the key incorrectly, no idea what the correct method is. -
How to fill a field with pre-defined options in the admin page
I'm new to Django and to learn it I'm trying to create a news-like site, where the news-posts are written in the admin page. To achieve this I created a model called Post, and, among other things, I want it to store the post genre. Therefore I made a variable called genre which equals models.CharField() method. The problem with this approach is that in the admin page I have to write the post genre every time, when instead I'd like to choose the genre from a set of pre-defined genres. How can I achieve this functionality in the admin page? -
Authenticate client in Heroku/Django
I have a Django app running on Heroku and would like to authenticate clients with SSL certificates. Idea is to store CA on a server, which generates and signs client certificates. Certificate's "Subject" field contains, say, username: ➜ cli git:(master) ✗ openssl x509 -in client.crt -text -noout | grep Subject Subject: CN=lev When I send requests to server, I specify client certificate: def test_cn(): url = "/".join([HOST, "test_cn"]) print(requests.post(url, cert=("client.crt", "client.key")).text) Server verifies that client's certificate is indeed valid and fetches username from "Subject" field. The question is, what is needed to be done on Heroku/Gunicorn/Django side to make it work?