Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WebApp giving DEBUG error on some of the browsers
After a quick research I was able to build a very basic Django app to find the weather using the openweathermap api.I deployed it using Digital Ocean after getting a free domain from freenom.Problem is when I sent to to some of my friends to see it wont open in some of them, giving the error as follows: Change that to <code>False</code>, and Django will display a standard page generated by the handler for this status code. Thanks! Here is the link to the app: http://currweather.cf PS:It's not much as I am new to Django -
Django choices. How to set a option to be selected only once
I am working on a blog. I have a section where there will be a special post. And another page where I have collection of special posts. Here is my model.py class Post(models.Model): post = models.TextField() SPECIAL = ( ('0', 'Special Post'), ('1', 'General Post'), ('2', 'Inactive Special Post'), ) specialpost = models.CharField(max_length=1, choices=SPECIAL, default='1', ) Only One post should be in the Special Post. When new special post is added, the old special post should be shifted to Inactive Special Post. So it can be shown in the Collection of Special post page. How can I do this? -
Deploying django(python) project with mod_wsgi
I am new to django and mod_wsgi, when I was trying to deploy a django project(in python) demo on Apache using mod_wsgi, I encountered some problem as following: When the demo runs on django's built-in webserver with command 'python manage.py runserver', everything looks normal like Running on built-in server while when running on Apache/mod_wsgi with command 'mod_wsgi-express start-server wsgi.py' , it looks like this: Running on Apache/mod-wsgi I have no idea which part of my code or configuration goes wrong, could anyone help me out? -
Best Web Framework for High-Traffic Website
Which is the best framework to work with high-traffic website (100 millions per day for example)? Django is very good for that? Or I should use another framework for this. I've heard that Google use python as backend language in their websites, but I put in builtwith (page to see in what language was developed a website) some site like YouTube, for example, and I see PHP... If Google really work with python, which framework they use? Or they use another unknown framework or language developed by themselves? Thank you for answer, have a good day. -
when get_context_data(...) is called in django?
I am redericting to url with Class Updateview in Django $('.edit_btn').on('click',pop_up); function pop_up() { $.ajax({ url: $(this).data('url'), data: { }, dataType: 'json', success: function ( ) { alert("success"); } }); } }); and the UpdateView class is : class stock_update_view(UpdateView): model = part_stock fields = ['part_id','entry_date','supplier','amount','remaining'] success_url = reverse_lazy('parts:part_list') template_name = 'part_detail.html' def get_context_data(self, **kwargs): context = super(stock_update_view, self).get_context_data(**kwargs) context['update_form'] = context.get('form') return context def get(self, request, *args, **kwargs): username = request.GET.get('username', None) data = { } return JsonResponse(data) i am callling the stock_view_updat just to get context['update_form'] will calling it though the ajax will get_context_data(...) be called and will i be able to use 'update_form' in my template?? -
HttpAccessTokenRefreshError at ... unauthorized_client: Client is unauthorized to retrieve access tokens using this method
I have set up a service account for my google calendar api project. The idea is that my web site can connect to my google calendar and display events, etc. As it was put by google Service account clients are created when domain-wide delegation is enabled on a service account. Which indeed happened and so I have a connecting OAuth 2.0 client ID. So far so good. I generated a json file that I used to connect and try to authenticate using this code from cal.models import Cal as Caldb import httplib2 from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import OAuth2WebServerFlow from oauth2client import tools from calendar import monthrange from calendar_gui import MyCalendar from datetime import datetime from datetime import date from django.utils.safestring import mark_safe from oauth2client.service_account import ServiceAccountCredentials import os from django.conf import settings def authenticate(): scope= ['https://www.googleapis.com/auth/calendar'] credentials = ServiceAccountCredentials.from_json_keyfile_name(os.path.join(settings.PROJECT_ROOT, '../', 'myjson.json'), scopes=scope) delegated_credentials = credentials.create_delegated('email@email.com') http = httplib2.Http() http = delegated_credentials.authorize(http) service = build(serviceName='calendar', version='v3', http=http, credentials=credentials) return service But alas service = build(serviceName='calendar', version='v3', http=http, credentials=credentials) File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 214, in build cache) File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 261, in _retrieve_discovery_doc resp, content = http.request(actual_url) File … -
Form is not looping and displaying when i am trying DJANGO
I am running into a small issue that i was hoping someone can help me with. I have a django view that i am trying to submit and process. I have a ModelForm that i am trying to pass through to the HTML template. Now with the form, I want to loop through it and every time i loop through it, i want to add a prefix to the fields names so that i can process it easier. What i have now is a view that is correctly looping though each of the items and adding the prefix, but when it is passed and displayed to the HTML template, I am only getting the result of the last template that goes through the form. I am not sure how to get that to happen and what I need to do to get it to work. Here is the view that I have: def addTransaction(request, groupId, recordId): user = User.objects.get(username='omar') group = Group.objects.get(id=groupId) record = Record.objects.get(id=recordId) transactions = Transaction.objects.all() if request.method == 'POST': if record.split == 1: form = EvenSplitTransactionForm(request.POST) if form.is_valid(): cd = form.cleaned_data amount = cd['amount'] description = cd['description'] split_amount = SplitEven(record, amount) for trans in transactions: if trans.record.id … -
Correctly migrate from Python 3 md5 library to Python 4 hashlib
I'm trying to integrate a 3rd party payment gateway (CCAvenue) in Django 1.11, Python 3.5.2 The reference code provided by the 3rd party uses the deprecated library md5 to encrypt texts. from Crypto.Cipher import AES import md5 def pad(data): length = 16 - (len(data) % 16) data += chr(length)*length return data def encrypt(plainText,workingKey): iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f' plainText = pad(plainText) encDigest = md5.new () encDigest.update(workingKey) enc_cipher = AES.new(encDigest.digest(), AES.MODE_CBC, iv) encryptedText = enc_cipher.encrypt(plainText).encode('hex') return encryptedText How do I make the above encrypt() method Python 3 compatible using the hashlib library of Python 3? Can you post the whole method? -
json parsing in django
I've built a webhook to receive json POST. However, I'm recieving an error from json decoder. Here's the view.py file from the webhook import json from django.shortcuts import render from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import UserText # Create your views here. @csrf_exempt @require_POST def webhookmb(request): usrtxt = json.loads(request.body) UserText.objects.create( id = usrtxt['id'], recipient = usrtxt['recipient'], originator = usrtxt['originator'], body = usrtxt['body'], createdDatetime = usrtxt['createdDatetime'], ) # redirect to API.AI # TODO return HttpResponse(200) This is the error I am receiving 2017-07-09T00:19:45.559146+00:00 app[web.1]: Internal Server Error: /webhookmb/ 2017-07-09T00:19:45.559154+00:00 app[web.1]: Traceback (most recent call last): 2017-07-09T00:19:45.559155+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner 2017-07-09T00:19:45.559156+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_respon se 2017-07-09T00:19:45.559157+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2017-07-09T00:19:45.559155+00:00 app[web.1]: response = get_response(request) 2017-07-09T00:19:45.559159+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2017-07-09T00:19:45.559158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_respon se 2017-07-09T00:19:45.559160+00:00 app[web.1]: return view_func(*args, **kwargs) 2017-07-09T00:19:45.559159+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_v iew 2017-07-09T00:19:45.559161+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner 2017-07-09T00:19:45.559161+00:00 app[web.1]: return func(request, *args, **kwargs) 2017-07-09T00:19:45.559162+00:00 app[web.1]: File "/app/webhookmb/views.py", line 12, in webhookmb 2017-07-09T00:19:45.559162+00:00 app[web.1]: usrtxt = json.loads(request.body) 2017-07-09T00:19:45.559163+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 354, in loads 2017-07-09T00:19:45.559163+00:00 app[web.1]: return _default_decoder.decode(s) 2017-07-09T00:19:45.559164+00:00 … -
How to force add unchanged django instances to database
i am working on a website that saves different both true/false answer and multiple choice answer to the same model (Answer) class Answer(models.Model): question = models.ForeignKey(Question, related_name='answers') correct = models.BooleanField() a_text = models.CharField(max_length=255, null=True, blank=True) created = models.DateTimeField(auto_now_add="True") whenever i save to the model i delete existing data of that model and intend to repopulate it from data in instance and request.POST then i read that in the django documentation that The save() method returns the instances that have been saved to the database. If a given instance’s data didn’t change in the bound data, the instance won’t be saved to the database and won’t be included in the return value (instances, in the above example). Please help out, Am stucked. Here is my form declaration class AnswerForm(ModelForm): class Meta: model = Answer fields = ['a_text', 'correct'] widgets = { 'correct': RadioSelect(choices=[(True, "True"), (False, "False")]) } AnswerFormSet = modelformset_factory( Answer, fields = ('a_text', 'correct'), max_num = 4, min_num = 4 ) Here is my view def create_question(request, quiz_id, que_id=None): quiz = get_object_or_404(Quiz, id=quiz_id) created_questions = Question.objects.filter(quiz=quiz_id) if que_id: que_id = int(que_id) que = get_object_or_404(Question, id=que_id, quiz=quiz) question_form = QuestionForm(instance=que) if que.question_type == 'multiplechoice': multiple_choice_answer_form = AnswerFormSet( queryset=que.answers.all(), ) truefalse_answer_form = … -
Why won't Django acknowledge my class variable?
I've defined the following form class in a Django project (Django 1.11, Python 3.5), but when I execute python3 manage.py runserver, I receive a NameError: name 'month_names' is not defined: class MonthForm(forms.Form): month_names = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] MONTH_CHOICES = [(i + 1, month_names[i]) for i in range(len(month_names))] month = forms.ChoiceField(choices=MONTH_CHOICES, label='Month', widget=forms.Select()) I can't figure out why this doesn't work. I've noticed that if I move the initial month_names assignment outside of the class definition, then it works. Any explanation would be greatly appreciated. Thank you in advance. -
Dockerized Angular 4, Django and postgresql - Process exited with status 127, error code=H10 desc=“App crashed”
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I noticed that in logs there is Process exited with status 127. I have found here 127 Return code from $? that Value 127 is returned by /bin/sh when the given command is not found within your PATH system variable and it is not a built-in shell command. In other words, the system doesn't understand your command, because it doesn't know where to find the binary you're trying to call. Besides, when I was trying different commands I very often were getting error like /bin/sh: 1 not found what I described in this post. To sum up, it seems to me that it may be root of the problem. Any suggestions how can I solve it? Logs: 2017-07-08T13:19:48.882112+00:00 heroku[web.1]: Process exited with status 0 2017-07-08T13:20:40.336825+00:00 heroku[run.9745]: Awaiting client 2017-07-08T13:20:40.395900+00:00 heroku[run.9745]: Starting process with command `docker-compose up` 2017-07-08T13:20:40.542168+00:00 heroku[run.9745]: State changed from starting to up 2017-07-08T13:20:45.727667+00:00 heroku[run.9745]: State changed … -
Django - form field depends on another field
I have a simple form field: form.base_fields['user'] = forms.ChoiceField( label="User", choices=choices, initial=request.user) I would like to fill another field depending of user choice: form.base_fields['email'] = forms.EmailField(label="Email adress", initial=request.user.email) When I choose user (for example user1) I would like to fill email field by x = User.objects.get(username='user1') email = x.values('email') email variable. Can you give me any clues how can I achieve that? -
How to restore Django project with pg_dump file?
What is the procedure to restore a Django project using an already restored database from a PostgreSQL pg_dump. All django source code also exist. Will Django migration safe? -
IdentationError: Unexpected indent following Django Tutorial
I'm following the tutorial on django on the following link: https://docs.djangoproject.com/en/1.11/intro/tutorial02/ Specifically the part where its adding the str methods on both classes, but I'm getting the indent error! I used python before and after looking for a while I still can't see my error! See the image with the hidden characters of my code, what is it!? It's been driving me crazy: See the error when trying to run the python shell: So what could it be? I am legit running out of ideas. Thank you! -
How can I establish grouping in Django through models?
I am not sure why I cannot figure this part out but I created a model named MenuItems which will allow for me to enter all of the items that a restaurant has on their menu, later I will use these on the front end. I also created a model name MenuGrouping so that on the front end, I can have Bootstrap tabs show the group_title and under each, show the items in that group. What field should I add in the MenuItems model to associate it to a group? I attempted to use group = models.ForeignKey(MenuGrouping) but then I run into the issue of showing each item in the specific group. Models.py: class MenuItems(models.Model): menu_item_title = models.CharField(max_length=256) menu_item_description = models.TextField() menu_item_price = models.DecimalField(max_digits=4, decimal_places=2) customer_favorite = models.BooleanField(default=False) is_on_menu = models.BooleanField(default=True) class Meta: ordering = ('menu_item_title', ) class MenuGrouping(models.Model): group_title = models.CharField(max_length=256) Is there a relationship that I can add in the MenuGrouping model that I can associate multiple MenuItems? Thank you in advance! -
Mocking a helper function in django view test
I have a view function that initiates user login requests it looks something like this: def initiate_login(request): # get request parameters return check_user_and_send_otp(login_id) The request is then processed by another function def check_user_and_send_otp(login_id): # check if user exits return send_otp_to_user(phone_number) And then another function def send_otp_to_user(phone_number): # sends a message to user return response The problem is while testing my code, I don't want to send messages to a phone number while testing. My login test function looks somewhat like this, is it possible to mock it without changing my code? def test_login_initiator(self): response = self.client.post(self.login_url, data=self.login_data, content_type="application/json", **self.headers) self.assertEqual(response.status_code, 200) All these functions that were called by others are located in seperate modules -
Creating a Django sign up form with two password inputs only one of which is sent to the database
I wanted to create a sign up page with two inputs for a password, to see if they match and then input only one final password into the database. I have seen people suggest putting in two separate password fields: a 'password1' and 'password2'. Then creating a form with these two fields and then checking if the two match one another. However I wanted to know if there was a way I could create a model class with just one 'password' field and still create a form with two inputs that will check if both inputs match. Then return only one password to the 'password' field in the database. I am new to Django and programming in general. Your help would be much appreciated, thank you. -
Django Rest Framework filtering calculated model property
Sorry for a newbie question. I have a following model: class WeightSlip(models.Model): grossdate = models.DateTimeField(auto_now=False, auto_now_add=False) grossweight = models.DecimalField(max_digits=6, decimal_places=2, default=0) taredate = models.DateTimeField(auto_now=False, auto_now_add=False) tareweight = models.DecimalField(max_digits=6, decimal_places=2, default=0) vehicle = models.CharField(max_length=12) @property def netweight(self): return self.grossweight - self.tareweight @property def slipdate(self): if self.grossdate > self.taredate: return grossdate.date() else: return taredate.date() Serializer: class WeightSlipSerializer(serializers.ModelSerializer): class Meta: model = models.WeightSlip fields = ('grossdate', 'grossweight', 'taredate', 'tareweight', 'slipdate', 'netweight', 'vehicle') read_only_fields = ('slipdate', 'netweight') I am trying to use the django-rest-framework-filters to filter on the calculated 'netweight' and 'slipdate' properties: class WeightSlipFilter(FilterSet): class Meta: model = WeightSlip fields = ('slipdate', 'netweight', 'vehicle') This gives me an error: TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: slipdate, netweight Is there a workaround to this problem other than adding the calculated fields to the database ? Thanks in advance. -
parse a list of objects in django
There is a list of objects which is printed like this: [<Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>, <Intermediate_table: Intermediate_table object>] I want to extract the email attribute of an individual object for which I used json.loads(queryset),it shows an error:Expecting value: line 1 column 1 (char 0) #I also tried without json.loads: for i in queryset:#the list is in queryset variable print(i.email)#this gives an error Please suggest the correct of parsing each object. Thanks. -
AttributeError: 'FlashPolicyServer' object has no attribute 'kill'
I get the following error as soon as I run django app along with the django-socketio app using python manage.py runserver_socketio SocketIOServer running on 127.0.0.1:8001 KeyboardInterrupt Thu Jul 6 22:04:52 2017 Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django_socketio-0.3.9-py2.7.egg/django_socketio/management/commands/runserver_socketio.py", line 65, in handle server.kill() File "/usr/local/lib/python2.7/dist-packages/socketio/server.py", line 43, in kill self.policy_server.kill() AttributeError: 'FlashPolicyServer' object has no attribute 'kill' Am I missing something ? -
display the UpdateView form on the same page as CreateView form in django
I want to display the UpdateView form on the same page as CreateView form so whenever "Edit" button is clicked the UpdateView form is displayed on the same page <button type="button" class="edit_btn" data-url="{% url 'parts:stock_update_view' stock.id %}">Edit</button> ajax for edit button: $.ajax({ url: $(this).data('url'), data: { }, dataType: 'json', success: function (data) { alert(data.name); } }); } }); class stock_update_view(UpdateView): model = part_stock fields = ['part_id','entry_date','supplier','amount','remaining'] success_url = reverse_lazy('parts:part_list') template_name = 'part_detail.html' def get_context_data(self, **kwargs): context = super(stock_update_view, self).get_context_data(**kwargs) context['update_form'] = context.get('form') return context def get(self, request, *args, **kwargs): username = request.GET.get('username', None) data = { } return JsonResponse(data) I want to get back the UpdateView form as jsonResponse so that I can render it in my template.after returning context['update_form'] = context.get('form') will I be able to render the pre-filled form in my template if yes then how can I return it? -
Import font in Django template
I want to import a font in django template I use this code @font-face { font-family: 'sans-serif'; src: url('{% static 'fonts/20db.otf' %}'); } This is where my static file is. Any help please? -
Strange user profile data in header Django
What I am trying to do is make it so that in the header, when I enter a profile in the menu that is not my own, the data of that user is displayed in the header. But when I enter the timeline, my data comes out. Here is my code. models.py (Perfil) class Perfil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='avatar', default='avatar/default.png') cabecera = models.ImageField(upload_to='cabecera', default='cabecera/default.png') biografia = models.TextField(max_length=140, blank=True) web = models.URLField(max_length=200, blank=True) ubicacion = models.CharField(max_length=30, blank=True) fecha_nacimiento = models.DateField(null=True, blank=True) creado = models.DateTimeField(auto_now_add=True) actualizado = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username class Conexion(models.Model): seguidor = models.ForeignKey(User, related_name='seguidor') siguiendo = models.ForeignKey(User, related_name='siguiendo') fecha_seguimiento = models.DateTimeField(auto_now_add=True) def __str__(self): return "{} : {}".format(self.seguidor.username,self.siguiendo.username) views.py (Perfil): class PerfilDetailView(generic.DetailView): model = User slug_field = 'username' template_name = 'perfil/perfil.html' def get_context_data(self, **kwargs): context = super(PerfilDetailView, self).get_context_data(**kwargs) context['perfil'] = Perfil.objects.filter(user=self.get_object()) context['posts'] = Post.objects.filter(user=self.get_object()) context['siguiendo'] = Conexion.objects.filter(seguidor=self.get_object()) context['seguidores'] = Conexion.objects.filter(siguiendo=self.get_object()) return context header.html (Fragment): {% if user.is_authenticated %} <ul class="nav navbar-nav"> <li {% url 'timeline_global' as home_url %}{% if request.get_full_path == home_url %}class="active"{% endif %}><a href="{% url 'timeline_global' %}"><span class="glyphicon glyphicon-home" aria-hidden="true"></span> Inicio</a></li> <li><a href="#">Grupos</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{ user.get_full_name }} <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a … -
Updating my Django website's database from a third party service, strategies?
Hello people from stackoverflow. I'm learning Django and to practice I'm currently developing a clon page of YTS, it's a movie torrents repository (disclaimer below). As of right now, I scrapped all the movies in the website and have them on a single db table called Movie with all the basic information of each movie (I'm planning on adding one more for Genre). Every few days YTS will post new movies and I want my clone-web to automatically add them to the database. I'm currently stuck on deciding how to do this: I was planning on comparing the movie id of the last movie in my db against the last movie in the YTS db each time the user enters the website, but that'd mean make a request to YTS every time my page loads, it'd also mean some very slow code should be executed inside my index() views method. Another strategy would be to query the last time my db was updated (new entries were introduced) and if it's let's say bigger than a day then request new movies to YTS. Problem with this is I don't seem to find any method to query the time of last db …