Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RUN PYTHON ON HOST WHO NOT SUPPORTING PYTHON
In my region, few hosts support python. Is the way to run python(3.x) script(or django projects) on HOSTS that not supporting python??? Note 1: I think can use Google App Engine But I'm not sure -
django project with private app
Currently I have a django project called Foobar. It consists of several apps that work together. Most of them are basic utilities for this one app(called star) that is the secret sauce. What I would like to do is is invite people to contribute to the project (to all it's utility apps) but not be able to see star. I wish star be closed sourced and developed only by the core team. How can I handle this? Should I move star to another repository on Github? Moreover, how do I deploy this project? Needless to say star needs all the utility apps to work. -
Django rest framework request data is always null
I just want to try simple Django rest framework code, I used APIVIEW and posted data through browser. CODE: class GetData(APIView): def post(self, request, format=None): if request.method == 'POST': item_id = request.data.get('item_id') return Response({"return": "OK ","item_id":item_id}) else: return Response({"return": "NOT OK "}) The above code should echo the item_id whatever i "POST"ed. but the result is always null. POST data: { "item_id" : "3456787"} result: {"item_id":null,"return" :"OK "} I don't understand where I went wrong. the above code works fine in my Loaclhost but does not work in production server. -
Entity.resource error in google drive api call
after connected to Google drive, I want to follow user changes. credentials = json.loads(flow.step2_exchange(code).to_json()) headers = {'Authorization': 'Bearer {}'.format(credentials['access_token']), 'Content-Type': "application/json"} token_url = 'https://www.googleapis.com/drive/v3/changes/startPageToken' token_resp = requests.get(token_url, headers=headers) pageToken = json.loads(token_resp.content)['startPageToken'] url = 'https://www.googleapis.com/drive/v3/changes/watch?pageToken={}&alt=json'.format(pageToken) headers = {'Authorization': 'Bearer {}'.format(credentials['access_token']),} data = { "id": str_tools.random_str(40), "type": "web_hook", "address": "https://portal.besafe.io/integrations/google-drive/webhooks" } response = requests.post(url, data=json.dumps(data), headers=headers) and I'm receiving this error { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "entity.resource" } ], "code": 400, "message": "entity.resource" } } What does it means "entity.resource" and how can I fix this error Thanks. -
Django Issue: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am completely new to Django. I created a class: from django.db.models import Model from cqlengine import columns class Rsvpstream(Model): venue_name = columns.Text() venue_lon = columns.Decimal(required=False) venue_lat = columns.Decimal(required=False) venue_id = columns.Integer() visibility = columns.Text() response = columns.Text() guests = columns.Integer() member_id = columns.Integer() member_name = columns.Text() rsvp_id = columns.Integer(primary_key=True) rsvp_last_modified_time = columns.DateTime(required=False) event_name = columns.Text() event_time = columns.DateTime(required=False) event_url = columns.Text() group_topic_names = columns.Text() group_country = columns.Text() group_state = columns.Text() group_city = columns.Text() group_name = columns.Text() group_lon = columns.Integer() group_lat = columns.Integer() group_id = columns.Integer() When I run this code, I got the following errors: Traceback (most recent call last): File "", line 1, in File "/Users/hpnhxxwn/anaconda/envs/magenta/lib/python2.7/site-packages/django/db/models/base.py", line 105, in new app_config = apps.get_containing_app_config(module) File "/Users/hpnhxxwn/anaconda/envs/magenta/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "/Users/hpnhxxwn/anaconda/envs/magenta/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Can someone please advise how to proceed? Thank you in advance! -
Second Django Logout Does Not Work
I am currently trying to get my Django login/logout to work correctly. However, I am having a problem where once I have logged in once, logged out once, and then logged in again to any other user, the logout function no longer works. I am curious if anybody has ever experienced this before because I am currently unable to figure out what is happening, and I have tried the contrib.auth.logout as well as my own logout view that calls logout(request). Thank you -
Django-Geopostion default value error
I'm trying to integrate location into my Django project. I have my model: class Post(models.Model): position = GeopositionField(default= Geoposition(40.00,73.88)) votes= models.IntegerField(default=0) date= models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) sound= models.FileField() I've tried leaving no value for position, but I can't make migrations without a default value. I've also gone ahead and removed all instances of the model from the admin. Even with what I have above (which I found from another person with the same issue) I'm getting a AttributeError: 'Geoposition' object has no attribute 'split' when I try to make the migration. Anyone have any pointers? -
cannot import name patterns - django
I am using Visual Studio 2013, and, Python Tools for VS 2013 to get started with a Django website. manage.py #!/usr/bin/env python """ Command-line utility for administrative tasks. """ import os import sys if __name__ == "__main__": os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "DjangoWebProject1.settings" ) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) It gives the following error, How can I fix that? My solution space looks like the following, -
Capturing user response for outgoing call(call from twilio to user) using twilio and django
I am using twilio and django to make calls to user. Once user answers the call, he is supposed to press 1 0r 0 after listening to voice message. How can I capture the user input here. -
Wagtail model with ParentalKey cannot translate along with the other models
I am working on a Wagtail CMS project. Everything has been working fine so far. But when I started translating each model field using Wagtail-modeltranslation package (wagtail-modeltranslation==0.6.0rc1), the model with ParentalKey is not showing properly in my admin interface. I am including my model and translation.py files along with this. It would be greate if someone gives a helping hand to find a solution to this problem. class HomePage(Page): # Home page fields home_page_title = models.CharField(max_length=200) short_description = RichTextField(null=True, blank=True) main_image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+') content_panels = Page.content_panels + [ FieldPanel('home_page_title'), ... ... ... InlinePanel('related_partners', label="Related Parnters"), #Child class class Partner(Orderable): partners = ParentalKey(TranslationChild, related_name='related_partners', null=True, blank=True) partner_image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+') partner_url = models.URLField(max_length=500) And my translation.py file looks like this, #!/usr/bin/env python # -*- coding: utf-8 -*- from .models import HomePage, TranslationChild, Partner from wagtail_modeltranslation.translation import TranslationOptions from modeltranslation.decorators import register @register(HomePage) class FooTR(TranslationOptions): fields = ( 'home_page_title', 'short_description', 'body', 'translation_section_title', ) @register(Partner) class PartnerTR(TranslationOptions): fields = ( 'partner_description', 'partners', ) Here in the admin page, the partner section is not showing properly. Django version 1.8.5 and Wagtail version 1.9 -
In Django, how to pass the input from user to the url of next page?
In my Django project, I have two webpages.User input data in the first webpage, and then the second webpage provides the user something that is selected by user's input in the first webpage. But I do not know how to pass the input from the user in the first webpage to the view function of the second webpage. Here is my view.py which include the code for the first webpage: class MajorProgramForm(forms.Form): major_programs = forms.ChoiceField(label='Major Programs', choices=MAJORS, required=True) def choose_major_program(request): if request.method == "GET": form = MajorProgramForm(request.GET) context = {'form': form} return render(request, "program.html", context)) Here is the urls.py: urlpatterns = [ url(r'^$', choose_major_program, name="choose_major_program")] And below is my template for the first webpage: <html> <head> <title>Choose Major Program</title> </head> <body> <div id="header"> <h1>Choose Major Program</h1> </div> <div class="frame"> <form name="form" action="{% url 'choose_major_program' %}" method="GET"> {% csrf_token %} <ul> <select name="major_choice"> {% for value, text in form.major_programs.field.choices %} <option value="{{ value }}">{{ text }}</option> {% endfor %} </select> </ul> <input type="submit" value="Submit" /> </form> </div> </body> Thanks for your help! -
Django - show loading message with Jquery
I need help please, I'm using Paramiko to send command to my virtual machine, so as it takes some time I want to tell the user to please wait for a moment. I want to show a message when I hit a button on my td. I'm not really familiar with front-end to be honest I was trying to do a jquery to make it work. this is my div: <div id="loading" class="alert alert-info" style="display:none;">Please, wait...</div> that's what I want to show when the button is clicked. My td: <td id="myDiv" class="animate-bottom" ><a id="paramiko" class="btn btn-xs btn-info" title="paramiko" href="{% url 'paramiko_function' item.id %}"><span class="fa fa-signal"></span> </a> </td> as you can see I got a button that when I hit on that it will run my paramiko_function and make the process. This is my JS: $("td").submit(function() { { if( $("[a_pressed]").get(0) === undefined ) { $('#loading').show(); } } return true; }); $(":a").live('click', function() { $(this).attr("a_pressed", $(this).val()); }); what I was trying to do is when that td is pressed show my div with the message but that's not working. Hope you could help me. Thanks in advance!! -
Give load time to datatable javascript block in django
I have the below block, {% block worklistsjqonloadscript %} $( "<span>&nbsp;&nbsp; Selected ReviewId:</span>" ).insertAfter( "#DataTables_Table_0_length" ); # code for data-table jquery var dtWorklist = datatable_worklist.get_selected_rows(); datatable_worklist.refresh(); if (dtWorklist.length > 0) { var mask = dtWorklist[0].si_site__si_device__si_report__maskset; console.log("maskset", mask);} {% endblock %} In this block, I want to give load time for the data-table javascript (i.e after the HTML is executed). Is there any way to do this. New to javascript. -
Understanding how Models and Forms affect one another and database
I am creating form for users to input information too. I then want to save that information to a database and be able to extract information. I am having difficulty however when I try to create a drop down list and multiple selection list. For example say I define a model as in my models.py file as such: gi_category = models.CharField(max_length=4, choices=GI_NOGI) Where I have GI_NOGI specified as GI_NOGI = (('GI','GI'),('NOGI','NO-GI')) My forms.py looks something like this class RegisterForm(forms.ModelForm): weightclass = forms.ChoiceField(choices=WEIGHTCLASS, required=True,label='Weight Class') gi_category = forms.MultipleChoiceField(choices=GI_NOGI, label='Contest You Intend to Enter', widget=forms.CheckboxSelectMultiple(), required=True) class Meta: model = Register fields = ['name', 'age', 'birthdate', 'address', 'city', 'state', 'zip', 'phone', 'email'] labels = {'name':'Name', 'age':'Age on April 21', 'birthdate':'Birth date', 'address':'Address', 'city':'City', 'state':'State', 'zip':'Zip', 'phone':'Phone', 'email':'Email'} widgets = { 'birthdate':forms.TextInput(attrs={'placeholder': 'MM/DD/YYYY'}), 'phone':forms.TextInput(attrs={'placeholder': '(###)-###-####'})} Now I believe I am overwriting the gi_category and weightclass from models somehow because I cant access their respective values in the database. I don't know how to create a SelectMultiple any other way than I had I did(If this is problem any insight would be great. I am wondering what I am doing wrong? Also on a related note I want to have a database value for … -
Heroku Django ApplicationError: 'module' has no attribute 'TemporaryDirectory'
In a django app I have hosted on Heroku, I have one view that generates a PDF from a LaTeX template, and stores it as a temporary file. The view is: from django.http import HttpResponse from django.template import Context from django.template.loader import get_template from subprocess import Popen, PIPE import tempfile import os def pdf(request): #entry = Entry.objects.get(pk=pk) context = Context({ # 'content': entry.content, }) template = get_template('cv/simple.tex') rendered_tpl = template.render(context).encode('utf-8') with tempfile.TemporaryDirectory() as tempdir: ## ERROR RAISED HERE ## process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r This works fine locally. However, when I push it to Heroku and try to visit the URL pointed at the view, I get the following error: Internal Server Error: /cv.pdf Traceback (most recent call last): File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/cv/views.py", line 34, in pdf with tempfile.TemporaryDirectory() as tempdir: AttributeError: 'module' object has no attribute 'TemporaryDirectory' Other questions for similar errors suggest that it may be due to one having a script call tempfile.py that gets imported instead of … -
AttributeError: 'function' object has no attribute 'as_view' for django pyhton3 custom view decorator
i am trying to write a url_context for my project and using an decorator to limit user to access the webpages using their access level. here is the code: def get_current_path(request): return { 'current_path': request.get_full_path() } def url_context(view_func): def _view(request, *args, **kwargs): if request.user.is_admin(): return HttpResponseRedirect({{get_current_path(request)}}) elif request.user.is_leader(): if {{get_current_path(request)}}.__contains__(AdminUser.username): print('You are not allowed to view the admin contend!!') else: return HttpResponseRedirect({{get_current_path(request)}}) elif request.user.is_member(): if {{get_current_path()}}.__contains__(AdminUser.username): print('You are not allowed to view the admin content!!') elif {{get_current_path()}}.__contains__(LeaderUser.username): print('You are not allowed to view the leader content!!') else: return HttpResponseRedirect({{get_current_path(request)}}) else: return view_func(request, *args, **kwargs) _view.__name__ = view_func.__name__ _view.__dict__ = view_func.__dict__ _view.__doc__ = view_func.__doc__ return _view however when implementing @url_context on the views there is an AttributeError: 'function' object has no attribute 'as_view' error -
how to implement django microservices?
1 Like in spring boot , how to use django framework to build microservice. 2 Also next question is how can i use Ouath created in spring boot , consume in python django. -
Django -- it's not directing to next page
On my home page, there is a submit button. But if I click it, it won't go to next page but stay on the home page. Here is my view.py: class MajorProgramForm(forms.Form): major_programs = forms.ChoiceField(label='Major Programs', choices=MAJORS, required=True) def choose_major_program(request): if request.method == "GET": form = MajorProgramForm(request.GET) context = {'form': form} return render(request, "program.html", context) def choose_major_taken_courses(request): query_pre = "SELECT must_take FROM major_requirements WHERE track_name=?" query_elec = "SELECT elective0, elective1, elective2, elective3, elective4, elective5, elective6 FROM minor_requirements WHERE track_name=?" results_pre = c.execute(query_pre, request.GET['major_programs']) results_elec = c.execute(query_elec, request.GET['major_programs']) output_pre = results_pre.fetchall() output_elec = results_elec.fetchall() PRESCRIBED = build_drop_down(output_pre) ELECTIVE = [(x,x) for x in output_elec[0]] class MajorTakenForm(forms.Form): pre_courses = forms.MultipleChoiceField(label="Prescribed Courses", choices = PRESCRIBED, widget=forms.CheckboxSelectMultiple, required=True) elec_courses = forms.MultipleChoiceField(label="Elective Courses", choices = ELECTIVE, widget=forms.CheckboxSelectMultiple, required=True) form = MajorTakenForm(request.GET) context["form"] = form return render(request, "program/major_courses_taken.html", context) Here is my urls.py: urlpatterns = [ url(r'^$', choose_major_program, name="choose_major_program"), url(r'^majortaken/$', choose_major_taken_courses, name="choose_major_taken_courses")] And here is my major_courses_taken.html: <html> <head> <title>Choose Courses You Have Taken</title> </head> <body> <div id="header"> <h1>Choose Courses You Have Taken</h1> </div> <div class="frame"> <form name="form" action="courses/majortaken/" method="GET"> {% csrf_token %} <ul> <select name="pre_choice"> {% for value, text in form.pre_courses.field.choices %} <option value="{{ value }}">{{ text }}</option> {% endfor %} </select> </ul> <input type="submit" … -
dyld: Library not loaded: @executable_path/../.Python
Awhile ago I had both Python2.7 and 3.5 installed on my Mac and was able to use them both successfully. Not too long ago I installed Anaconda and IPython. I have used those for a couple weeks for prototyping and in-console programming. After I went back to the regular Python for my Django and Flask projects, I discovered an unpleasant thing. Namely, whenever I try to run python or python3 I get the following error: dyld: Library not loaded: @executable_path/../.Python Referenced from: /Users/name/anaconda3/bin/python3 Reason: image not found Abort trap: 6 When I run conda I also get the same error. If I create a new virtual environment with virtualenv django-project, I am able to activate it, and it allows me to run Python 2.7 successfully. My question is the following. How can I fix python and python3 for the command line while also retaining the working Anaconda and IPython? How can I make sure that the virtual environments are able to carry Python3? -
AJAX is working properly on the items with variation but not with with the items having no variation
In the Django product page my items which are having variation is updating properly but the one without any variation are the one on which AJAX is not working I have also checked my view.py and it also seems to look good % extends "base.html" %} <script> {% block jquery %} function setPrice(){ var price = $(".variation_select option:selected").attr("data-price") var sale_price = $(".variation_select option:selected").attr("data-sale-price") if (sale_price != "" && sale_price != "None" && sale_price != null ) { $("#price").html("<h4>" + sale_price + " <small class='og-price'>" + price + "</small></h4>"); }else { $("#price").html(price); } } setPrice() $(".variation_select").change(function(){ setPrice() }) $("#submit-btn").click(function(event){ event.preventDefault(); var formData = $("#add-form").serialize(); console.log(formData); $.ajax({ type: "GET", // "POST" url: "{% url 'cart' %}", data: formData, success: function(data) { $("#jquery-message").text("Added " + data.item_added + " Deleted " + data.deleted) }, error: function(response, error) { // console.log(response) // console.log(error) $("#add-form").submit() } }) // $("#add-form").submit() }) {% endblock %} </script> {% block content %} <div class="row"> {% for object in object_list %} <div class="col-sm-6 col-md-4"> {% if object.productimage_set.count > 0 %} {% for img in object.productimage_set.all %} <div class="thumbnail"> <img class='img-responsive' src="{{ img.image.url }}" > {% endfor %} {% endif %} <div class="caption"> <h3>{{ object.title }}</h3> <form id='add-form' method='GET' action="{% url 'cart' … -
Running manage.py command through Gunicorn
I followed this tutorial to set up Gunicorn to run Django on a VPS, this is working perfectly fine and the web server is running on Nginx. I created a separate manage.py command that I want to run Async using a worker, I am unsure how to integrate this through Gunicorn. -
Factory_boy not creating different User objects Django
I am new to Factory_boy with Django. After spending some time I understood how to create a factory for User model. I am using the default user model and following is my factory. I am using Faker for randomness import factory from . import models from django.contrib.auth.models import User from faker import Faker from django.contrib.auth.hashers import make_password fake = Faker() class UserFactory(factory.DjangoModelFactory): class Meta: model = User django_get_or_create = ('email',) first_name = fake.first_name() last_name = fake.last_name() email = first_name+"."+last_name+"@gmail.com" password = make_password("ojasojas") username = first_name+"_"+last_name Now in the django shell I use UserFactory.create() to crate an user. this works fine. Is it possible to loop through create statement and crate 5 different users? Now when I am doing that I am getting only one user (crated once and 'get' 4 times) as follows. What am I missing? -
Autocomplete jquery in django
I use autocomplete in my site on Django, but i have a problem with output data. I have database (all city in Russia) and search field from this cities. <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> $(function() { $( "#automplete-2" ).autocomplete({ source: '/asearch/', minLength:2, autoFocus:true }); }); <input class="city_search" name="city" id = "automplete-2" placeholder="Введите город"> views.py: def autocomplete(request): if request.method == 'GET': list = City.objects.filter(title__istartswith=request.GET.get('term', None)).values_list('title', flat=True) results = '' if list: for l in list: results = results + "%s\n" % (l) return HttpResponse(results) else: return HttpResponse('Не правильная раскладка', content_type="text/plain") When I receive a response from the server, it is placed in one line. Several cities in one line. I need every city on a separate line. How to do it? Please, help) http://promspros.ru/ the third field, but only Cyrillic. <li class="ui-menu-item"><div id="ui-id-13" tabindex="-1" class="ui-menu-item-wrapper">Пятиверстица Пятигорская Пятигорский Пятигоры Пятидворка Пятидорожное Пятиизбянский Пятиморск -
Django: How to show Groups field in Custom UserAdmin?
I created a custom User class, and a custom UserAdmin / Form class. Everything looks fine, but I'm still missing the groups field (auth_group). I don`t know the field name. https://gist.github.com/CoinBR/c49c05f24bd5dcd3b4d4f2d205143a2e Django Version: 1.10 -
How to set environment variables for your run configurations in PyCharm?
I have started to work in a Django project, and I would like to set some environment variables without having to set them manually or having a bash file to source. I would like to set the following variables: export DATABASE_URL=postgres://127.0.0.1:5432/my_db_name export DEBUG=1 # there are other variables, but they contain personal information Before you start downvoting, I have read this, but that does not solve what I want. In addition, I have tried setting the environment variables in Preferences-> Build, Execution, Deployment->Console->Python Console/Django Console, but it sets the variables for the interpreter.