Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I check model's data is connected accurately?
I wanna check whether model's data is connected accurately or not. models.py is class User(models.Model): trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regist_date = models.DateTimeField(auto_now=True) user_id = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area',null=True, blank=True) class Area(models.Model): name = models.CharField(max_length=20, verbose_name='Area', null=True) class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='Prefecture') area = models.ForeignKey('Area', null=True, blank=True) class City(models.Model): name = models.CharField(max_length=20, verbose_name='City') prefecture = models.ForeignKey('Prefecture', null=True, blank=True) class Price(models.Model): upper1000 = models.CharField(max_length=20, verbose_name='u1000', null=True) from500to1000 = models.CharField(max_length=20, verbose_name='500~1000', null=True) under500 = models.CharField(max_length=20, verbose_name='d500', null=True) city = models.ForeignKey('City', null=True, blank=True) Model's data means Area&Prefecture&City&Price,so I wanna know these data is connected accurately with User.How can I check this?I cannot find it to see db.sqlite3 by using DB Browser for SQLite .How can I print the answer in terminal? -
Create Word Document and then Attach it to Email Django
I'm currently using python_docx in order to create Word Documents in Python. What I'm trying to achieve is that I need to create Document File in Django and then attach it to an email using django.core.mail without having to save the file on the server. I've tried creating the Word File using this (taken from an answer also within StackOverflow): def generate(self, title, content): document = Document() docx_title=title document.add_paragraph(content) f = BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response And then here is where I experimented and tried to attach the response to the email: def sendmail(self, name,email,description,location): message = EmailMessage('Custom Mail', 'Name: '+str(name)+'\nEmail: '+str(email)+'\nDescription: '+str(description)+'\nLocation: '+str(location), 'test@gmail.com',to=['testreceiver@gmail.com']) docattachment = generate('Test','CONTENT') message.attach(docattachment.name,docattachment.read,docattachment.content_type) message.send() Is what I'm trying to achieve even possible? -
What do I have to do for the continuous conversation of watson chatbot?
I want to have a continuous conversation with watson chatbot. current situation : The chatbox does not remember the status of the conversation you previously sent. I installed the Django framework on the server and created a watson.py file to load the workspace and work with KakaoTalk, a Korean chat application. The chatbot's conversation flow that I want is as follows. User: I want to make a reservation Chatbot: When is the meeting date? User: tomorrow Chatbot: How is your meeting time? User: 14:00 We need your help very much. watson.py import json from watson_developer_cloud import ConversationV1 from .models import Test from . import views import simplejson conversation = ConversationV1( username = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxxxxxxxxxxx", version = '2017-05-26' ) workspace_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' #workspace def test(return_str): result = '' except Exception as err: pass response = conversation.message( workspace_id = workspace_id, message_input = {'text': return_str}, ) for i in range(len(response['output']['text'])): result += response['output']['text'][i] +'\n' return result views.py import json from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import Jidum, Test from . import watson # Create your views here. def keyboard(request): return JsonResponse({ 'type':'text', }) @csrf_exempt def message(request): message = ((request.body).decode('utf-8')) return_json_str = json.loads(message) return_str … -
Django asset manager for Views or template tags?
I come to Django having used the Yii2 PHP framework. One of the good features about that is it allows you to create asset files for CSS and JS which are then loaded into the base layout file at runtime. This allows you to keep the base template clean of CSS and JS markup within the head and at the bottom of the HTML document. The CSS and JS files you specify in the asset file are automatically placed in the correct position in the document and you can also specify dependencies if needed. At the moment, with Django I am having to edit the base.html file manually which is not ideal. I know you can use the Media class for forms, and in admin.py, which does a similar job. However, what I would like to do is to something like this (for example) in inclusion template tags or in a class based view perhaps. Is this possible? Many thanks! -
How to get session with suds-jurko
I'm trying to get the sessionID so I can do SOAP requests. To day I can do POST hardcoded requests. But I want to use Suds This is how I can do a POST hardcoded requests today: def GetSession(IP): request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' request = request + ' <soapenv:Body>' request = request + '<login>' request = request + '<UserName>username</UserName>' request = request + '<Password>password</Password>' request = request + '</login>' request = request + '</soapenv:Body>' request = request + '</soapenv:Envelope>' request = u"""""" + request + """""".format() encoded_request = request.encode('utf-8') headers = {"Host": ""+ IP +"", "Content-Type": "text/xml; charset=UTF-8", "Content-Length": str(len(encoded_request)), "SOAPAction": ""} response = requests.post(url="http://"+ url +"/Service", headers=headers, data=encoded_request, verify=False) return response.content I have been trying to do the sessionID request this way. But with out any luck. def status(request): from suds.client import Client from suds.transport.http import HttpAuthenticated t = HttpAuthenticated(UserName='username', Password='password') url= 'http://ip.ip.ip.ip/Service?wsdl' client = Client(url) return HttpResponse(client) I don't know if I'm doing this correctly. In the hardcoded example, I have the login, username and password in the body. And not sure if that is the same way as HttpAuthenticate? Help much appreciated =) -
Webpack TypeScript and xgettext translations
I have a Django app and am using Django's i18n module to help translating my strings. For translating JavaScript, I run python manage.py makemessages -d djangojs which adds all marked strings to a .po file. This works quite well for all my boring .js files in my static folder. However, we are starting to use webpack to pack some typescript (.tsx files) into a bundle.js file. This file is copied to the static folder after building, so I expected Djangos makemessages to pick up the strings from it as well. However, it seems that the strings are not parsed correctly, because most of the code in bundle.js is simply strings wrapped in eval(). I believe this means that I need webpack to - in addition to the bundle.js file - create a .js file for each .tsx file without all of the eval() nonsense, so that django's makemessages can parse it properly. I have no idea how to do this, however. My current config looks like this var path = require("path"); var WebpackShellPlugin = require('webpack-shell-plugin'); var config = { entry: ["./src/App.tsx"], output: { path: path.resolve(__dirname, "build"), filename: "bundle.js" }, devtool: 'source-map', resolve: { extensions: [".ts", ".tsx", ".js"] }, module: { … -
How can I pass the request if I redirect and then render the template
I have a requirement, from login page jump to the admin page, you know the URL address should change to the admin page. If I only use render to admin page, the URL address will not change, so in this post I get the OptimusCrime's good answer. But if I redirect and then render template, I can not pass the request from login page to the admin page. in the login page's views.py: ... return redirect('/app_admin/index/') in the admin page's views.py: ... return render(request, 'app_admin/index.html') # there the request is None. How can I pass the request to the admin page's views.py? -
Separate the values in dictionary into two column. Python and Django
I've one program which will read the data from text file. There is 3 type of data that I read from text file. 1.visual id 2.time 3.tname_pb Problem Supposed I have 3 column and separate the output with a different column. But, visual id is working perfectly, while time and tname_pb are combined together. CLICK HERE TO LOOK AT THE PICTURE Question How if I want to separate time output and tname_pb output into two different column. Current views.py based on the picture with open(path) as input_data: for line in input_data: if line.startswith('2_visualid_'): visual_key = line.lstrip('2_visualid_').rstrip() data.update({visual_key: []}) if 'time' in tokens: if search_time in line and visual_key in data: data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip()) if 'tname_pb' in tokens: if tname_pb in line and visual_key in data: data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip()) Current template based on the picture <div class="input-group" align="center" style=" left:10px; top:-110px; width:99%"> <table class="table table-bordered"> <thead class="success" > <tr> <th class="success"> <b>Visual ID</b> </th> <th class="success"> <b>Time Delay Index</b> </th> <th class="success"> <b>Tname PB</b> </th> </tr> {% for key, values in output.items %} <tr class=""> <td rowspan={{ values|length|add:1 }}><b>{{ key }}</b></td> {% for value in values %} <tr class=""> <td ><b>{{value}}</b></td> </tr> {% endfor %} </tr> {% endfor %} </thead> </table> </div> NOTE I have … -
Redirection issue using PK
I Have a very strange phenomenon In my app the user Create a project and is redirected to that project detail using its pk. On that project detail page he is asked to create a team and when the team is created he is redirected again to the project detail page but to the wrong pk for example: I just created a project and I got redirected to .../project/24. I was asked to create a team, I created it but got redirected to ../project/17 any idea why and how to redirect my page to the right URL ? model.py: class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk}) def __str__(self): return self.team_name class TeamMember(models.Model): user = models.ForeignKey(MyUser) team = models.ForeignKey(Team) def __str__(self): return self.user.first_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk}) def __str__(self): return self.name -
Edit list of pictures that has foreign key to model
I have the following two models: class Profile(AbstractUser, CommonInfo): ... pictures = models.ManyToManyField(Picture, blank=True) and class Picture(CommonInfo): picture = models.ImageField(upload_to='gallery/', blank=True, null=True) What is the best way to display those pictures in a custom template/form/view. I want to display them all and to delete several of them and add new. -
Simple Search Function in Django
I'm using Q lookup for simple search Functionality. Here's the code taken from view, if query: object_list = Post.objects.filter( Q(title__icontains=query) | Q(content__icontains=query) ).distinct() But I have another model "Question", I wants to filter out questions in the search as well along-with Post. How can I use Q lookup for 2 separate models i.e. 'Post' & 'Question' together in one variable i.e "object_list". Please help me with this code! -
user_logged_in signal with REMOTE_USER_BACKEND
i' m using AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.RemoteUserBackend'] which is coming from Apache2 (and ldap). It works well, however i' d like to set a session variable when the user logs is. I could use the from django.contrib.auth.signals import user_logged_in signal if it' d be an application side authentication, but is there any possibility to use it with REMOTE_USER ? How? Python: 3.4.2 Django: 1.9.2 . -
utf-8' codec can't decode byte 0xb5 in position 10: invalid start byte [on hold]
I don't know this error enter image description here Error Meassage ' 'utf-8' codec can't decode byte 0xb5 in position 10: invalid start byte ' Please tell me why show me error I use Python, Django, WeasyPrint -
How to import Celery app in Django app-level task?
I follow the guide http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html but I can't find how to import celery app in app-level tasks.py, where it is used like this: @app.task() def do_my_task(): -
Dynamic models django
Let's say i have 10 tables in 1 Db and the table names differ and data is different, but the structure of the tables are the same. And then i have 1 more table that collects all the table names and the creation date of that table. Example: PrimaryTable table_name_1 table_name_2 .... table_name_10 and the structure of all tables example: class PrimaryTable(models.Model): name = models.CharField(db_column='Name', unique=True, max_length=100) date = models.CharField(db_column='Date', max_length=100) class Meta: managed = True db_table = 'Primary Table' def __str__(self): return self.name class table_name_1(models.Model): title = models.TextField(db_column='Title', blank=True, null=True) url = models.CharField(db_column='Url', unique=True, max_length=250, blank=True, null=True) description = models.TextField(db_column='Description', blank=True, null=True) created_at = models.DateTimeField(db_column='Created_at') class table_name_2(models.Model): title = models.TextField(db_column='Title', blank=True, null=True) url = models.CharField(db_column='Url', unique=True, max_length=250, blank=True, null=True) description = models.TextField(db_column='Description', blank=True, null=True) created_at = models.DateTimeField(db_column='Created_at') and so on... And i only want to make 1 class that includes all those tables that have same structure and call it when i choose the table from the PrimaryTable. I don't want to use "python manage.py inspectdb > models.py" every time i create a table. I want to have access to the new created table instantly when i create it. -
How to customise attributes of forms.Select options in Django
I am working on a custom requirement which demands to customise select option attributes. My dropdown will show the list of options, and some of those options should be shown as disabled as per certain conditions. I have tried customising the Select widget attributes by passing disabled = disabled. But that disables the whole dropdown. By looking into the code of django 1.11.5, it seems that the attributes applied on Select will be applied to its options. Can anyone please suggest how this functionality can be achieved? Thank you -
Change the text of a sidemenu item on django-admin interface
I have a couple of items (namely authentication and user_central) on the side menu of my django-admin interface which are shown in the screenshot below. I want to change their text. How can I do that? I know a litle bit about overriding the template, but which blocks to override for these two menu items? -
Getting error when running sql server query in Python
I am building a web app using Django framework of Python , DB is Sql server Azure ,using Pyodbc. I have an issue i am unable to resolve , i am getting a parameter(file_name) which is a string and when running the query with the parameter i am getting empty results in the first case and "sql = sql % tuple('?' * len(params)) TypeError: not all arguments converted during string formatting" in the 2nd case , what am i doing wrong? file_name=request.POST.get('filetodelete') with connections['default'].cursor() as c: 1st case parms=[file_name] sql='select * from banks_row_data where file_name=%s' c.execute (sql,parms) test=c.fetchall() 2nd case c.execute (sql,file_name) test=c.fetchall() -
AttributeError: module 'app.parse' has no attribute 'sheet'
I got an error: AttributeError: module 'app.parse' has no attribute 'sheet4' . In parse.py I wrote class DataRate(): data_rate ={} data_rate =defaultdict(dict) def try_to_int(arg): try: return int(arg) except: return arg book4 = xlrd.open_workbook('./data/excel1.xlsx') sheet4 = book4.sheet_by_index(0) in data_rate_savedata.py from . import parse def data_rate_save(): for row_index in range(0, sheet4.nrows): row = sheet4.row_values(row_index) row = list(map(try_to_int, row)) value = dict(zip(tag_list, row)) closing_rate_dict[value['ID']].update(value) user = User.objects.filter(corporation_id=closing_rate_dict[value['ID']]['NAME']) in main_save.py from app.parse import DataRate #parse DataRate() #save data_rate_save() When I run main_save.py, the error occurrs. I really cannot understand why this error happens because I import parse.py in data_rate_savedata.py, so I can access parse.py of 'sheet4' in data_rate_savedata.py. Should I write something in main_save.py? How can I fix this error? in models.py class User(models.Model): trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regist_date = models.DateTimeField(auto_now=True) user_id = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) -
Why my django urls gets some bad garbage value
When i call http://127.0.0.1:8000 to call my homepage it automatically redirected to some bad random url like http://127.0.0.1:8000/ADwx or http://127.0.0.1:8000/GRpc urls.py url(r'^$', views.home, name='home'), views.py def home(request): if request.user.is_authenticated(): return HttpResponseRedirect('/dashboard') else: return render(request,'index/index.html') -
Django sending Email confusion
I've used one application with sending email to the user for notification. but in that application setting.py file contains some confusing terms like EMAIL_USE_TLS = True I'm not sure what this is and also EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'rquest186@gmail.com' what is the variety in this two and if host is declared here then def send_mail(title,message,reciver): try: mailS = 'smtp.gmail.com' mailP = 587 mailUsr = "idefusiontest2015@gmail.com" mailPass = "IDEF2017" # Create a text/plain message msg = MIMEMultipart('alternative') msg['Subject'] = title msg['From'] = mailUsr msg['To'] = reciver html="<html><head></head><body><p>"+message.replace("\n","<br>")+"</p></body></html>" part2 = MIMEText(html, 'html') msg.attach(part2) # Send the message via our own SMTP server, but don't include the s = smtplib.SMTP(mailS,mailP) s.ehlo() s.starttls() s.ehlo() s.login(mailUsr,mailPass) s.sendmail(mailUsr, [reciver], msg.as_string()) s.quit() except Exception as e: print(e) in this mailUsr = "idefusiontest2015@gmail.com" ???? what's this for ? I'm new to this. and it's confusing for me. thanks in adv. -
How to add multiple foreign key in Django
i am beginner in Django I have to models class Employee(models.Model): full_name = models.CharField(max_length=120,default=None) designation = models.CharField(max_length=80,default=None) class Leave(models.Model): employee = models.ForeignKey(Employee, related_name='employee') number_of_days = models.IntegerField(default=0) Now I have inline Leave Model with Employee in admin.py so that i can add as many leaves i want in employees But when i retrieve this model in views new leaves are created , all i want is one employee should show total = number of days , but it creates new leaves, not able to build any logic here i am stuck , please ask if u dint get it. -
Import error on my python Chatbot with no known parent pachage
it is my code. i could not solve it. if i comment error line, then next line gets same error -
Django import Models
i m trying to import A model from the file in the path "/usr/local/lib/python2.7/dist-packages". The file witch contain the model it's called table_class_corespondance so when i import it is:from table_class_corespondance import Users. Now in the Users class definition after i declare the field i write : class Meta: managed = False db_table = 'USERS' app_label = "banner_manager" so that Django will know that app will make referance this table. But unfortunatley this error still shows up: RuntimeError: Model class table_class_corespondance.Users doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Any idea what can i do to solve it? Sorry for my english -
Django, how to get information when confirm window'ok button is clicked
I want to know how to get event or result when confirm windows'ok button is clicked. I'm using Django. I wrote the code using xxx,, ((confirm( ,,, )" for u in myList