Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web framework for facebook chatbot
I'm improving my simple chatbot on FB with new features. I want to use the templates - buttons etc to confirm requests/choose options. It means for each button I send to the user, I need to somehow keep its ID and wait for the response. I'm currently using Django framework, but I'm wondering if there is anything more suitable. I looked up Twisted and Tornado, but not sure if its exactly what I want? My plan is to keep the button IDs in SQLite/Mongo and when callback comes, check which button it is and respond accordingly. But then isn't it too slow? Or would get slow? PS: I know it's bordering on relevancy to SO as an opinion-based question, I'd just like to verify what sort of principles I'm looking for, because that's not my strongest suit. Many thanks -
Get data from dynamically added elements and pass to Django request.POST
I have a restaurant_form which allows user to input menu items. Each menu item represent a table row which is added dynamically. Each table row has input for: menu item, price, halal(Boolean), and notes. Here is a sample entry. data-ids and names of input elements are incremented. <tbody class="menu-entry "> <tr id='menu0' data-id="0" class="hidden"> <td data-name="name" class="name"> <input type="text" name='name0' placeholder='Menu Item' class="form-control"/> </td> <td data-name="price"> <input type="text" name='price0' placeholder='0.00' class="form-control"/> </td> <td data-name="halal"> <input type="checkbox" name="veg0" value="halal" class="form-control"> </td> <td data-name="notes"> <textarea name="notes0" placeholder="Contains soy." class="form-control"></textarea> </td> <td data-name="del"> <button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'></button> </td> </tr> </tbody> What is the best way to retrieve data from the table? I have tried this: $('#restaurant_form').submit(function () { $('.menu-entry').each(function() { $(this).find('td').each(function(){ $(this).find("input").each(function() { alert(this.value) }); $(this).find("textarea").each(function() { alert(this.value) }); }) }) }) The alert() shows the correct values however I am wondering if there is a better way to do this? Also, after retrieving the values, how can I pass it to the view with a POST request? I would like to save the values to model RestaurantMenu with columns name, price, halal and notes. Thank you. -
How to correct logic in comments View?
I build comments functional for post but has bug. When someone comment post, another user see correct comment body, but incorrect image and def p(request, pk): user = request.user #user_that_text_comment = User.objects.filter(pk=pk) topic = get_object_or_404(Topic, pk=pk) post = get_object_or_404(Post, pk=pk) comment = Comments.objects.filter(pk=pk) if request.method == 'POST': form = CustomCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.creator = user comment.save() comment = Comments.objects.create( body=form.cleaned_data.get('body'), creator=user, ) return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment, 'form': form}) else: form = CustomCommentForm() return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment, 'form': form}) I builded comment function for post but it has bug. When someone comment post, another user see correct comment body, but incorrect image and name. i know why i has this problem(i suppose), it happend because i use user=request.user. Notice on string that i comment on 3 line. I was think that will help me,but it isn't. I use primary key in my url. url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), and when i use primary key in filter it return to me user that has same pk as post pk. I need that it return to me username and picture of user that create this comment. Html template: <div … -
Django admin - Use inlines in django admin saving data in current model
I need use inlines in django admin for show relation between two models but in the moment that i do, i had to do the reverse relationship to show inlines. Example: class OtherModel(models.Model): field1=models... ........ class Model(models.Model): field1 = models.... other_model = models.ForeignKey(OtherModel) I create the inline... class OtherModelInline(admin.StackedInline): model = OtherModel extra = 1 @admin.register(Model): class ModelAdmin(admin.modelAdmin): inlines = [OtherModelInline] So... When I create the Inline it required foreign key on OtherModel.. How can I show this without change the relationship? -
Why does django pgm crash when entered number exceeds DecimalField max_digits?
I have the following field in my Django model: price = models.DecimalField(max_digits=8, decimal_places=2, default=0) and the following code in my form: price = forms.DecimalField(widget=forms.NumberInput(attrs={'step': '0.01', 'text-align': 'right;'})) (BTW, the text-align doesn't work - different problem, I think) It works when displayed in a form. In fact, when I try to use more than 2 decimal places, the form pops up a message: However, if I enter too many digits, as in: Django throws the following error: InvalidOperation at /balancer/set_security_prices/2017-10-14 [] Request Method: POST Request URL: http://localhost:8000/balancer/set_security_prices/2017-10-14 Django Version: 1.9.1 Exception Type: InvalidOperation Exception Value: [] Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py in format_number, line 200 Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 Python Version: 3.5.1 The is_valid() check I do before saving the data doesn't trap the problem. This doesn't make sense to me. Shouldn't Django protect against this or must I add try ...except code? Thanks! -
Django UnicodeDecodeError: utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte
I am making an app with Django. I want to generate pdf when I browse select link. So I used weasyprint module for convert my pdf. I import weasyprint module. But When I run that app, I found some error. This is views.py file def customersProfile(request, customer_id, sys_type): sys_type=sys_type area="profile" site_credit = site_credit1 time_now=timezone.now() customers=get_object_or_404(CustomerInfo, pk=customer_id) html_string = render_to_string('shop/profile.html', {'customers': customers, 'todaydate': today_date,'site_name': 'Moon Telecom', 'time_now': time_now, 'site_credit': site_credit, 'area': area}) html = HTML(string=html_string) result = html.write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=list_people.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'r') response.write(output.read()) return response This is HTML file. I wanna create pdf this html file. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body style> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="site_title" style="text-align:center; margin:0 auto"> <h3>মুন টেলিকম</h3> <h3> <a href="{% url 'shop:index' %}" target="_blank">{{site_name}}</a> </h3> <div class="invoice_info_one" style="width:100%; text-align:center"> <p>সকল প্রকার মোবাইল সেট, সীম কার্ড, মেমোরী কার্ড, MP-3, সোলার চার্জার, সোলার ফ্যান, মোবাইল ফোনের ব্যাটারী, চার্জার, ক্যাচিং,কাভার,হেডফোন, রেবন, ডিসপ্লে এবং ইলেট্রিক মালামাল বিক্রেতা</p> </div> <div class="invoice_location"> <p>জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ।</p> </div> <div class="invoice_contact"> <p>01717-051200(সুকান্ত) 01828-163858(দোকান)</p> <p><b>Email:</b> moontelecom2008@gmail.com</p> </div> <div class="copy_right"> {% … -
Unable to config django for mysql
I'm trying to connect Django app to MySQL on windows 10. I have installed mysqlclient as an interface between my Django app and MySQL. Whenever I try to open dbshell I'm getting error something like this:- django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured Here is my setting.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER':'root', 'PASSWORD':'root', 'HOST':'127.0.0.1', 'PORT':'3306' } } I have tried other solutions on StackOverflow but it didn't work for me. I also tried deleting the dbsqlite3 file from the project directory. Versions for different elements are as follows:- Python (3.6) Django (1.11.4) mysqlclient (1.3.12) pip (9.0.1) MySQL(5.7) -
html form creating user but not connecting to django model
I am creating a user sign-in system using the default django authentication system and have attached a model to it. The problem however is that whilst the user is created when I input the data in the form, the rest of the details are not actually transferred to the model i.e First Name and Last Name. It just creates the instance of that model but it has blank values. How do i fix this (among others)? I've tried: With Django ModelForms, how do I including the "id" column or primary key in the HTML? Django - Use multiple models and forms for the same view How to post my html form to django model and save it? HTML {% load account socialaccount %} {% load i18n %} {% load static %} {% load staticfiles %} <form id="register-form" role="form" method="POST" action="{% url 'student-register' %}"> {% csrf_token %} <br> <div class="form-group"> <img src="{% static 'img/logo_dark_100.png' %}"/> </div> <div class="form-group"> <label class="control-label">First Name:</label> <input type="text" id="register-name" name="first_name" class="form-control"> </div> <div class="form-group"> <label class="control-label">Surname:</label> <input type="text" id="register-last_name" name="last_name" class="form-control"> </div> <div class="form-group"> <label class="control-label">Email:</label> <input type="email" id="register-email" name="email" class="form-control"> </div> <div class="form-group"> <label class="control-label">{% trans "Password:" %}</label> <input type="password" id="register-password" name="password1" class="form-control"> </div> <div … -
How to solve error if form is not valid in Django?
I have write down a view like this: views.py def Pep_Des(request): #result_files_list = [] if request.method == 'POST' and request.FILES.get('myfile'): myfile=request.FILES.get('myfile') fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'Peptide_Descriptor/success.html', {}) if request.method == 'POST': form = Random_pep_seq(request.POST) else: myfile=None Fasta = "MGSSHHHHHHSS,GLVPRGSHMARV,TLVLRYAARSDRG,LVRANNEDSVYA,GARLLALADGMG,GHAAGEVASQLV,IAALAHLDDDEP,GGDLLAKLDAAV,RAGNSAIAAQVE,MEPDLEGMGTT,LTAILFAGNRLG,LVHIGDSRGYLL,RDGELTQITKDD,TFVQTLVDEGRI,TPEEAHSHPQRS,LIMRALTGHEVE,PTLTMREARAGD,RYLLCSDGLSDP,VSDETILEALQI,PEVAESAHRLIE,LALRGGGPDNVT" form = Random_pep_seq(initial={'Sequence':Fasta}) return render(request, 'Peptide_Descriptor/des.html', {'form':form}) #return render(request, 'FragBuild/Rand_Frag.html', {'form': form}) def success_file(request): return render(request, 'Peptide_Descriptor/success.html', {}) def Pep_Des_generated(request): Fasta = "MGSSHHHHHHSS,GLVPRGSHMARV,TLVLRYAARSDRG,LVRANNEDSVYA,GARLLALADGMG,GHAAGEVASQLV,IAALAHLDDDEP,GGDLLAKLDAAV,RAGNSAIAAQVE,MEPDLEGMGTT,LTAILFAGNRLG,LVHIGDSRGYLL,RDGELTQITKDD,TFVQTLVDEGRI,TPEEAHSHPQRS,LIMRALTGHEVE,PTLTMREARAGD,RYLLCSDGLSDP,VSDETILEALQI,PEVAESAHRLIE,LALRGGGPDNVT" form = Random_pep_seq(initial={'Sequence':Fasta}) form = Random_pep_seq(request.POST) if form.is_valid(): val_1 = form.cleaned_data['Sequence'] else: val_1 = " form is not valid" return render(request, 'Peptide_Descriptor/des_result.html',{'val_1':val_1}) "forms.py" like this from django import forms class Random_pep_seq(forms.Form): Sequence = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Ex.: ATTHYILLKY,ATTYYILLKY,ATTIILLKY'})) myfile = forms.FileField(allow_empty_file= True, label='3 Upload file 1', help_text='*') class Meta: fields = ['Sequence'] template like this: {% extends 'protocol/base.html' %} {% load staticfiles %} {% block content %} <style type="text/css"> .button { background-color: #ff9800; /* Green */ border: none; color: black; padding: 10px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin-top: 10px; margin-bottom: 30px; } </style> <div style="margin-left: 50px; margin-right: 300px "> <form action="/Pep_Des_generated/" method="post"> <div class="heading"> <h2> Peptide Descriptor Generation..... </h2> <h5> Submit Peptide directly or upload ".csv" file contains peptide library.. </h5> <div class="form-group"> {%csrf_token%} {{form.Sequence}} </div> {% csrf_token %} … -
Using custom python classes alongside Django app
First and foremost, this is my very first question on Stackoverflow. Any positive criticism is welcome. I tried looking everywhere for an answer, this is my last resort. In a school project, my team and I have to create a shopping website with a very specific server-side architecture. We agreed to use python and turned ourselves towards Django since it seemed to offer more functionalities than other possible frameworks. Be aware that none of us ever used Django in the past. We aren't masters at deploying application on the web either (we are all learning). Here's my problem: two weeks in the project, our teacher told us that we were not allowed to use any ORM. To me, this meant bye bye to Django models and that we have to create everything on our own. Here are my questions: as we already have created all our python classes, is there any way for us to use them alongside our Django app? I have not seen any example online of people using their own python classes within a Django app. If it were possible, where should we instantiate all our objects? Would it be easier to just go with another framework … -
NVD3 Chart won't render in Django
I'm having trouble getting my nvd3 pie chart to render. I'm using a template tag (simple tag) to return the data required to construct the pie chart. Already verified: All static files are loading The template tag is passing the correct dictionary to the template All templates are loading No errors The chart appears to be loading in the source code header color-id.html (template for just the pie chart) {% load static %} <link media="all" href="{% static 'nvd3/build/nv.d3.css' %}" type="text/css" rel="stylesheet" /> <script type="text/javascript" src='{% static 'd3/d3.min.js' %}'></script> <script type="text/javascript" src='{% static 'nvd3/build/nv.d3.min.js' %}'></script> {% load nvd3_tags %} {% load basic_deck_stats %} <head> {% include_chart_jscss %} {% color_id deck as data %} {% load_chart data.charttype data.chartdata data.chartcontainer data.extra %} </head> <body> <h3>Color Identity</h3> {% include_container "asdf" 400 400 %} charttype: {{ data.charttype }}<br> chartdata: {{ data.chartdata }}<br> chartcontainer: {{ data.chartcontainer }}<br> extra: {{ data.extra }} </body> basic_deck_stats.py (template tag) from django import template from card_search.views import Card, Deck, Quantity from django.shortcuts import render_to_response register = template.Library() @register.simple_tag def color_id(deck): black=blue=red=white=green = 0 queryset = Quantity.objects.filter(deck__deck_name=deck.deck_name).all() for item in queryset: if item.card.mana_cost: black += item.card.mana_cost.count("{B}") * item.qty blue += item.card.mana_cost.count("{U}") * item.qty red += item.card.mana_cost.count("{R}") * item.qty white += item.card.mana_cost.count("{W}") * … -
Can't make Gdal 1.11.2 work from binaries
I am trying to install GEOS for Django project and following Docs but while compiling on Ubuntu 16.04 Xenial I get this error. There was some fix for it here but it also didn't worked. Following is the error I get while I ran "make" as per official Django docs. Error: gdalserver.c: In function 'CreateSocketAndBindAndListen': gdalserver.c:125:21: error: storage size of 'sHints' isn't known struct addrinfo sHints; ^ gdalserver.c:127:31: error: invalid application of 'sizeof' to incomplete type 'struct addrinfo' memset(&sHints, 0, sizeof(struct addrinfo)); ^ gdalserver.c:130:23: error: 'AI_PASSIVE' undeclared (first use in this function) sHints.ai_flags = AI_PASSIVE; ^ gdalserver.c:130:23: note: each undeclared identifier is reported only once for each function it appears in gdalserver.c:133:12: warning: implicit declaration of function 'getaddrinfo' [-Wimplicit-function-declaration] nRet = getaddrinfo(NULL, pszService, &sHints, &psResults); ^ gdalserver.c:136:48: warning: implicit declaration of function 'gai_strerror' [-Wimplicit-function-declaration] fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(nRet)); ^ gdalserver.c:136:25: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'int' [-Wformat=] fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(nRet)); ^ gdalserver.c:142:39: error: dereferencing pointer to incomplete type 'struct addrinfo' psResultsIter = psResultsIter->ai_next) ^ gdalserver.c:163:5: warning: implicit declaration of function 'freeaddrinfo' [-Wimplicit-function-declaration] freeaddrinfo(psResults); ^ gdalserver.c:125:21: warning: unused variable 'sHints' [-Wunused-variable] struct addrinfo sHints; ^ ../GDALmake.opt:565: recipe for target 'gdalserver.lo' failed … -
Django CSRF cookie not set. Stuck
I'm learning how work Django and I've bought a book for this. I try to do a connection system with method="post" for the form. And when I submit there's CSRF cookie not set etc... I saw a lot of similar problems on the forum but still a bit stuck as I don't understand all the answer and I've not found something which worked excepted @csrf_exempt but I saw it was like disabling the things and it wasn't a good idea. Here's the code : My html login.html page : <form action="." method="post">{% csrf_token %} {% if error %} <p class="error">{{ error }}</p> {% endif %} <p> <label for="email">E-mail :</label> <input name="email" id="email" size="30" type="email" /> </p> <p> <label for="password">Password :</label> <input name="password" id="password" size="30" type="password" /> </p> <p> <input type="submit" value="Log-in" /> <a href="">Créer un compte</a> </p> My views.py : from django.shortcuts import render_to_response from datetime import datetime from django.views.decorators.csrf import csrf_protect from django.http.response import HttpResponseRedirect # from django.http import HttpResponseRedirect def welcome(request): return render_to_response('welcome.html', {'curent_date_time' : datetime.now}) @csrf_protect def login(request): if len(request.POST) > 0: if 'email' not in request.POST or 'password' not in request.POST: error = "Veuillez entrer un adresse mail et un mot de passe." return render_to_response('login.html', {'error': … -
Update existing base.html path without modifying all the paths
I need to update the path for mezzanine in django. Is there a way to update {% extends "base.html" %} to {% extends "index/base.html" %} without changing all the files that include the extends? -
Where to host simple landing page with django backend
I'v got a simple landing page, and there is django backend only for sending email from form submitted data. The question, whether there is simple django hosting, where I can host simple website fast. I mean, not some VPS like Digital Ocean, where I need to setup lots of things. Or the only option nowadays is to setup VPS? -
Django queryset - Filtering related table objects before aggregation
Consider this model in Django documentation: Aggregation and Avg There is a queryset like this: Author.objects.annotate(average_rating=Avg('book__rating')) which returns all authors annotated by average rate of all of their books. What if I want to query authors annotated by average rate of their books which have been published for example in 2016. Note that I want to get results with as few queries as possible. -
djstripe (django stripe) - should I create local or remote customers first?
When I receive my stripe token after a valid form: what data should I be using to create my local customer model? Many fields returned from the stripe create customer JSON response are incompatible with the local dj.stripe Customer model. Am I supposed to be deleting and changing fields from the stripe JSON response to shoehorn it into my local model or am I missing the advantage of using djstripe? -
Integrate Django with VueJs
How to Integrate Django with VueJs? What is the Standard way to integrate Django and VueJs? can anyone provide project structure and reference to learn -
Deploy django in ec2 instance with nginx and uwsgi which only allow HTTPS connections
I tried many tutorials for the same but none of them worked for me. I am not able to connect Django with uwsgi. -
Orderdict is not defined in django template when using in js
I have implemented nested serailizer via djangorestframework. I am sending the variable as a context in my django template. I struck with a problem while using template variable inside <script> tag it is showing an error that Error: Orderdict is not defined var data = {{ data.companies|safe }}; what i get after rendering was [OrderedDict([('id', 4), ('name', 'axis'), ('acronym', 'axis'), ('growth', [OrderedDict([('datetime', '2007-11-30T00:00:00+05:30'), ('_close', 224.199997)]), OrderedDict([('datetime', '2007-12-31T00:00:00+05:30'), ('_close', 169.125)]), OrderedDict([('datetime', '2008-01-31T00:00:00+05:30'), ('_close', 160.024994)]), OrderedDict([('datetime', '2008-02-29T00:00:00+05:30'), ('_close', 123.199997)]), OrderedDict([('datetime', '2008-03-31T00:00:00+05:30'), ('_close', 155.300003)]), OrderedDict([('datetime', '2008-04-30T00:00:00+05:30'), ('_close', 140.300003)]), OrderedDict([('datetime', '2008-05-31T00:00:00+05:30'), ('_close', 112.074997)]), OrderedDict([('datetime', '2008-06-30T00:00:00+05:30'), ('_close', 99.224998)]),.....] So as Orderdict is not a valid thing in JS but it is rendering as such. How can i solve this? I have also tried escapejs filter but no help. -
How to configure .htaccess Django deployment
I am trying to deploy my first Django application (on A2 Hosting). Unfortunately, I don't have access to my Apache2 conf file (and/or httpd), I can only modify the .htaccess file than you can see below. After many try, I think it is the Apache server who can't load the wsgi.py, because I add a logs file, create when the wsgi.py file is called and it wasn`t create (I tried manually and the logs file are correctly created). Right now, all I am trying to do its to print the Django "Wello World", because I thought, if I can't pass through this basic step, how can I deploy my "real" application ... Finally, I am running with Django 1.11.6 and Python 3.5.4 on a virtual env. .htaccess DirectoryIndex /home/hairduseres/public_html/myapp/myapp/myapp/wsgi.py WSGIScriptAlias / /home/user/public_html/myapp/myapp/myapp/wsgi.py WSGIPythonHome /home/user/virtualenv/myapp/3.5 WSGIPythonPath /home/user/public_html/myapp <Directory /home/user/public_html/myapp/myapp/myapp/> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/user/public_html/myapp" PassengerBaseURI "/myapp" PassengerPython "/home/user/virtualenv/myapp/3.5/bin/python3.5" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END wsgi.py """ WSGI config for myapp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi … -
Changing django form from POST to GET
I have my view with form where I use POST and I want to switch my form method from POST to Get. @login_required def payment_range_list(request): #import pdb; pdb.set_trace() title = 'payment list' #import pdb; pdb.set_trace() if request.method == "POST": form = PaymentRangeForm(request.POST) #import pdb; pdb.set_trace() if form.is_valid(): start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] building = form.cleaned_data['building'] if building == '': payment_list = LeasePayment.objects.filter(payment_date__range=[start_date, end_date] ) building = 0 else: payment_list = LeasePayment.objects.filter(payment_date__range=[start_date, end_date],lease__unit__building = building ) total = payment_list.aggregate(Sum('amount')) else: payment_list = None payment_page = None start_date = None end_date = None building = None total = None form = PaymentRangeForm() else: payment_list = None payment_page = None start_date = None end_date = None building = None total = None form = PaymentRangeForm() return render(request,'payment/payment_range.html', {'form':form, 'payment': payment_list,'page_payment':payment_page, 'start_date':start_date, 'end_date':end_date, 'building':building, 'total':total, }) and I have my form class PaymentRangeForm(forms.Form): start_date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'} )) end_date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'} )) building = forms.ChoiceField(choices=BLANK_CHOICE_DASH + list(Building.objects.values_list('id', 'name')), required=False) I want to switch my form method from POST to Get . What should I do? I tried simply changing POST to GET in my view but it is not working. -
Django - Update a Model every couple of minutes
I am building an app, where I need to fetch some data from an API and update all the models with that data every few minutes. What would be a clean way to accomplish something like this? -
Facebook Social Auth Login: Can't Load URL: The domain of this URL isn't included in the app's domains
I am developing a web application using Django and python-social-auth. I want users to login with Facebook. I have this in my python settings: SOCIAL_AUTH_FACEBOOK_KEY = '...' SOCIAL_AUTH_FACEBOOK_SECRET = '...' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] When my users enter the facebook page where they should provide credentials they see an error like this: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. In Facebook for Developers dashboard I have added "Facebook Login" product and added redirect url: http://localhost:8000/complete/facebook/ In settings, Website Site URL is set to: http://localhost:8000/ and App Domains is set to localhost. What am I doing wrong? BTW this is the url that my users see when the facebook page opens: https://www.facebook.com/v2.9/dialog/oauth?scope=email&state=HSfkstGUR5028DMhUzfWOSgo6fpPx29E&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcomplete%2Ffacebook%2F%3Fredirect_state%3DHSfkstGUR5028DMhUzfWOSgo6fpPx29E&client_id=...&return_scopes=true -
Django unit tests fail when ran as a whole and there is GET call to the API
I am facing an issue when I run the tests of my django app with the command python manage.py test app_name OR python manage.py test All the test cases where I am fetching some data by calling the GET API, they seem to fail because there is no data in the response in spite of there being in the test data. The structure which I have followed in my test suite is there is a base class of django rest framework's APITestCase and a set_up method which creates test objects of different models used in the APIs and I inherit this class in my app's test_views class for any particular API such as class BaseTest(APITestCase): def set_up(self): ''' create the test objects which can be accessed by the main test class. ''' self.person1= Person.objects.create(.......) class PipelineViewTestCase(BaseTest): def setUp(self): self.set_up() def test_get_pipeline_sales_person_no_closed_lost_deals(self): ''' To test if the logged in user is a person from the Sales group,then they shouldn't see closed deals and they should see only their deals :return:QuerySet-> All the non closed lost deals of the sales person ''' #Person.objects.get.reset_mock() url='/crmapi/pipeline/' self.client.login(username='testusername3',password='testpassword3') response=self.client.get(url,{'person_id':self.person3.id}) self.assertEqual(response.status_code, status.HTTP_200_OK) #excludes closed lost deal self.assertFalse(self.is_closed_deal_exist(response.data)) self.assertTrue(self.is_same_person_deal_exist(response.data,'testusername3')) self.assertEqual(len(response.data),6) So whenever I run the test as …