Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
APP: ERROR (no such file) error happens
APP: ERROR (no such file) error happens. I wanna run APP server which I made Python&Django on Nginx & Gunicorn & Supervisor.I could run Nginx & Gunicorn's install command, so now I have to use and run Supervisor.I run command supervisord & supervisorctl reread ,it was successful.But when I run command supervisorctl start APP,APP: ERROR (no such file) happens.Why does this error happen but can't I use only this command ?What is wrong?How should I fix this? -
Running Django server on localhost
I would like to run a Django server locally using a local IP. I have localhost mapped here: $ head -n 1 /etc/hosts 127.0.0.1 localhost I have this chunk of code in my settings.py: import os ALLOWED_HOSTS = ['HERE.IS.MY.IP', 'localhost', '127.0.0.1'] print "ALLOWED_HOSTS: {}".format(ALLOWED_HOSTS) In my mysql database I have this site table: mysql> select * from django_site; +----+--------------------+----------------+ | id | domain | name | +----+--------------------+----------------+ | 1 | example.com | example.com | | 5 | HERE.IS.MY.IP:8000 | projectsdb | | 8 | 127.0.0.1:8000 | projectsdb | | 9 | localhost:8000 | projectsdb | +----+--------------------+----------------+ I run the server locally on 127.0.0.1: $ python manage.py runserver 8000 ALLOWED_HOSTS: ['HERE.IS.MY.IP', 'localhost', '127.0.0.1'] Performing system checks... # ... Django version 1.10.5, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. If I go to this address http://HERE.IS.MY.IP:8000 it works. But of course I'd like to open it using a local IP such as http://localhost:8000 or http://127.0.0.1:8000. But this does not work. What am I missing? -
DRF Serializer readable - writeable non-model field
On a project with Django / DRF; I have the following model structure: class City(models.Model): name = models.CharField(max_length=100) class Company(models.Model): city = models.ForeignKey(City) . . And following serializer structure for Company model: class CompanySerializer(serializers.ModelSerializer): city_name = serializers.CharField(write_only=True) . . class Meta: model = Company fields = ('city_name',) While creating a company through the serializer, user provides a city_name, I create a new city with that name if not exists or use an existing entry if exists. In this structure, I want to be able to return city_name field while returning companies. It is not a field on the model, so I could use SerializerMethodField normally, but I also want this field to be writable as well. Do I have any options here? -
VariableDoesNotExist inplaceeditform on Django
so, basically I have this player_list.html {% extends 'football/base.html' %} {% load inplace_edit %} {% inplace_static %} {% block content %} <div class="body"> <h3>Player list</h3> <table style="width:100%"> <tr> <th>No.</th> <th>Name</th> <th>1st position</th> <th>2nd position</th> <th>3rd position</th> <th>Age</th> {% if user.is_authenticated %} <th>Remove</th> {% endif %} </tr> {% for player in players %} <tr> {% if user.is_authenticated %} <td>{{ forloop.counter }}</td> <td>{% inplace_edit "player.name" %}</td> <td>{% inplace_edit "player.first_Pos" %}</td> <td>{% inplace_edit "player.second_Pos" %}</td> <td>{% inplace_edit "player.third_Pos" %}</td> <td>{% inplace_edit "player.age" %}</td> <td><a href="{% url 'player_remove' pk=player.pk %}" onclick="return confirm('Are you sure you want to remove this player?')">remove</a></td> {% else %} <td>{{ forloop.counter }}</td> <td>{{ player.name }}</td> <td>{{ player.first_Pos }}</td> <td>{{ player.second_Pos }}</td> <td>{{ player.third_Pos }}</td> <td>{{ player.age }}</td> {% endif %} </tr> {% endfor %} </table> </div> {% endblock %} and I get this error Failed lookup for key [ "player] in u"[{'False': False, 'None': None, 'True': True}, {}, {}, {u'players': <QuerySet [<Player: Juara>, <Player: Teguh>, <Player: Champion>, <Player: Jaguh>]>}]" and this is my views for the player_list #football_player def player_list(request): players = Player.objects.all().order_by('first_Pos_id') return render(request, 'football/player_list.html',{'players':players}) Do I need to do any modification in inplace_edit.py or else? I did refer to this and this. -
Update a field on a different model using django signals and GenericForeignKey
Using Django 1.11 and Python 3.5 I am working on a points app where a source user assigns points to a target user for completing tasks. In the end, I want to keep a total points count in the User profile. That total has to update via a post_save signal from the points app. I have the models and signal set up. But the points being assigned in the points app are not being updated in and totaled in the points app. Can someone help me make this work? User model from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) image = models.ImageField(upload_to='user/%Y/%m/%d', default='') point_total = models.IntegerField(default=1) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) Points models import datetime from django.db import models from django.db.models import Count, Min, Sum, Avg from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth import get_user_model User = get_user_model() class PointValue(models.Model): """ Stores an action and … -
Django: DateTimeField is off by an hour when passed to strftime method
I am trying to get a DateTimeField element to render appropriately. Updating the timezone field in my settings.py file allowed me to display the correct time, I did so by simply modifying one field in said file: TIME_ZONE = 'Europe/Berlin' But I am using this method in order to format it: def displayTime(self): return self.added.strftime('%a %H:%M:%S %d/%m/%y') The problem is that when I use this method, the time is off by an hour again, as if I never edited the timezone field inside settings.py. -
Django - How to only save form to database if a specific field is NOT filled out (honeypot trap for signup spam)
I have recently been having some trouble with fake signups on my website signup form. I've decided the best way to deal with this is to create an 'invisible' honeypot form field. I have created this new 'fake' form field in my models.py and forms.py, I have rendered the field in my template, and I have hidden the field from real users using 'display: none' in my CSS. What I want to be able to do now is only save the form to the database if the 'fake' field is NOT filled out. For example, I want to do something like this: if form.is_valid() and fakeformfield.is_null(): instance = form.save(commit=False) instance.save() return redirect('thankyou') If you need to see my code just say and I will update the question. Any help would be much appreciated! -
Django-storages S3Boto3Storage makes HEAD and GET requests on read
I am using the S3Boto3Storage storage backend from the django-storages package in my Django application. I use the backend to handle large amounts of files in S3. When reading a file from the storage, the backend makes separate HEAD and GET requests. I am doing this operation many times, so I would prefer to skip the HEAD requests if possible. My read operation looks similar to this: class MyModel(models.Model): img = FileField() instance = MyModel.objects.filter().first() instance.img.read() I am using the default preload_metadata flag, which is False. Is there another setting that controls this behavior of the read method? My guess is that the HEAD request checks if the file exists before getting the file content. So maybe the HEAD call could be replaced with a try/except statement. But I could not figure out how to do that. -
How to save the attachment from an incoming email in Django's FileField?
I'm trying to save any attachments of incoming emails to a FileField in Django. The model looks like this: class Email(models.Model): ... attachment = models.FileField(upload_to='files/%Y/%m/%d', null=True, blank=True) ... def __unicode__(self): return self.contents[:20] I wrote this function to return the attachments. def get_attachments(email_object): attachments = [] for part in email_object.walk(): # content_type = part.get_content_type() content_disposition = part.get("Content-Disposition") if content_disposition and content_disposition.lower().startswith("attachment"): attachments.append(part) return attachments Now I have a list of instances of the email object, and I'm not sure how to save them as a file in the FileField. attachment.get_content_type() returns image/jpeg. But how do I go from here to making it somehting that can be saved in the file field? Thanks for all help. -
Duplicate regex syntax in urls Django
I have three buttons in a template. When clicked, each will perform a specific function from the views.py. With each, I send a PK in the url. My question is, they now all kind of have the same url and for that all the buttons access one method only. How do I fix this? Here is my code: In the template: <form method="GET" action="{% url 'register' activity.pk %}"> {% csrf_token %} <button onClick="return showLogoutMessage()" type="submit" class="btn btn-primary" id="Register">Register </button> </form> <form method="GET" action="{% url 'volunteer' activity.pk %}"> {% csrf_token %} <button onClick="return showLogoutMessage()" type="submit" class="btn btn-warning" id="Register">Volunteer </button> </form> <form method="GET" action="{% url 'cancel' activity.pk %}"> {% csrf_token %} <button onClick="return showLogoutMessage()" type="submit" class="btn btn-danger" id="Register">Cancel </button> </form> In views.py: def registerAttendee(request,pk): act = Activity.objects.get(pk=pk) act.save() attendee, _ = Attendee.objects.get_or_create(student=request.user) act.attendee.add(attendee) return redirect('home/#work') def registerVolunteer(request,pk): act = Activity.objects.get(pk=pk) act.save() volunteer, _ = Volunteer.objects.get_or_create(student=request.user) act.volunteer.add(volunteer) return redirect('home/#work') def cancel(request,pk): act = Activity.objects.get(pk=pk) act.save() attendee, _ = Attendee.objects.get_or_create(student=request.user) act.attendee.remove(attendee) return redirect('home/#work') In urls.py: url(r'^(?P<pk>\d+)', authentication_views.registerAttendee, name='register'), url(r'^(?P<pk>\d+)', authentication_views.cancel, name='cancel'), url(r'^(?P<pk>\d+)', authentication_views.registerVolunteer, name='volunteer'), Like I mentioned, the problem is when clicking any button, it performs the registerAttendee method only for all of them. -
py.test: Show local variables in Jenkins
Up to now we call py.test via Jenkins. If a test fails, we see the usual stacktrace like this Traceback (most recent call last): File "/home/u/src/foo/bar/tests/test_x.py", line 36, in test_schema_migrations errors, out)) AssertionError: Unknown output: ["Migrations for 'blue':", ...] It would be really great, if I could see local variables like in the django debug page (See https://djangobook.com/wp-content/uploads/figure2_3a.png). Is there a way to enable this? -
ElasticBeans/EB django, Can't access my server..
I deploy my server through http://docs.aws.amazon.com/ko_kr/elasticbeanstalk/latest/dg/create-deploy-python-django.html I created virtual environment. run my server "python manage.py runserver". initialized eb. "eb init -p python2.7 django-tutorial" created eb. "eb create django-env" oepn eb. "eb open" access through public dns But I can't access my server through the public DNS. This is my terminal and AWS instances AWS instances EB terminal Thank you! -
How to send javascript value to views.py django
I am trying to send a value from javascript to views.py function in Django. The code as following: <form name="myform" action="" method="get"> <button id="button" name="button" onclick="click()">send</button> <input type="hidden" id="data" name="data" value=""> <script> function click() { var d = 100 document.getElementById("data").value = d; document.myform.submit(); } </script> </form> In views.py, def views(request): #assume function name is views result = request.GET.get("data") , but this method is failed, please guide me. -
How to retrieve exact label values from a checkbox using django html tables
Here is my code for the checkbox. At the moment I retrieve all labels in each of the rows. <table id="mytable"> <tr> <p><label for="id_q">Enter Gene:</label> <input textarea name="Text1" cols="40" rows="5" name="q" type="search" value="CYP17A1" /></p> <p><label for="id_models_0">Disease:</label> <ul id="id_models[]"><td><li><label for="id_models_0"><input checked="checked" id="id_models_0" name="models" input type="checkbox" value="predictgene.amyotrophic_lateral_sclerosis_motor_neuron_disease" /> ALT</label></li></td> <td><li><label for="id_models_1"><input id="id_models_1" name="models[]" input type="checkbox" value="predictgene.arthrogryposis" /> AR</label></li></td> <td><li><label for="id_models_2"><input id="id_models_2" name="models[]" input type="checkbox" value="predictgene.congenital_myaesthenia" /> CM</label></li></td> <td><li><label for="id_models_3"><input id="id_models_3" name="models[]" input type="checkbox" value="predictgene.early_onset_dystonia" /> ED</label></li></ul></p></td> <br/><br> </tr> <button id="save">Click</button> </table> -
Stripe: Error "This application is not authorized to edit this account" while updating the account in stripe
I am very new the stripe & stripe API, right now am integrating the stripe into the django python server. I am able to create the customers & accounts. While updating the account with the bank token, I got an error "This application is not authorized to edit this account". I am able to see the connected accounts on the connected accounts page in stripe dashboard. Here is my code where I got the issue when account.save() try: account = stripe.Account.retrieve(user_account_id) account.external_accounts = bank_account_token account.save() except Exception as e: retrun e.message return account -
Download (PDF format) using Django
I am Trying to add download option(pdf format) it works fine but when I open downloaded the file it looks like a page only 1 line is visible, but when I copy that content and paste somewhere else there total content is visible. can anyone help me to overcome this issue HTML: <div class="dropdown-menu dropdown-primary pull-right" id="dashboard_download_button" aria-labelledby="dropdownMenu"> <a class="dropdown-item waves-effect waves-light download-file" id="csv" href="#"><i class="fa fa-file-excel-o download-icons"></i>&nbsp;&nbsp;CSV</a> <a class="dropdown-item waves-effect waves-light download-file" id="json"href="#"><b class="download-icons">&#123;&nbsp;&#125;</b>&nbsp;&nbsp;JSON</a> <a class="dropdown-item waves-effect waves-light download-file" id="pdf" href="#"><i class="fa fa-file-pdf-o download-icons">&nbsp;&nbsp;PDF</i></a> </div> JavaScript: var download_url = '/download/' + '?term=' + search_term + '&' + 'server=' + encodeURIComponent(server) + '&' + 'results=' + encodeURIComponent(results) + '&occurrence=' + occurrence; //download link for pdf format var pdf_href = $('#pdf').attr('href',''); var pdf_format_link = download_url + '&' + 'type=' + 'pdf'; $('#pdf').attr('href', pdf_format_link); Views.py (Items a list - the content which I want to download): response = HttpResponse(content_type = 'application/pdf') response['Content-Disposition'] = 'attachment; filename=%s'% smart_str(fname) p = canvas.Canvas(response) p.drawString(100,100,"\n".join(str(x) for x in items)) p.showPage() p.save() return response -
Celery worker doesn't see tasks from a specific Django app
Can't understand why celery worker suddenly stopped discovering tasks from a specific app, i.e. it can find all tasks except the ones from the app (though it worked fine some time ago, no changes were made to the settings). Has anyone ever encountered this problem before? -
Django: How to show all images in images model
I am trying to show all images associated with the currently selected user This is built off of this solved question: django upload to image model with foreign key to user Model.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE) Views.py @login_required def index_account(request): args = {'user': request.user } return render(request, 've/cp/index_account.html', args) Template > index_account.html <p><a href="{% url 've:edit_images' %}">Edit your images</a></p> # test to see if it worked w/o if {{ user.images.image}} # ideal solution {% if user.images.images %} {% for img in user.images %} <img src="{{ user.images.image.url }}"><br> {% endfor %} {% else %} <p>No images</p> {% endif %} <br> <hr> -
How to run the same Django test for different datasets?
I want to run the same exact test in a django.test.TestCase for different datasets: class MyTestCase(django.test.TestCase): fixtures = ['datasets.json'] @classmethod def setUpTestData(cls): super(MyTestCase, cls).setUpTestData() self.datasets = [] # get from fixtures def test(self): for dataset in self.datasets: self._test_dataset(dataset) def _test_dataset(self, dataset): # peforms the actual test for the given dataset self.assertEquals(...) How can I do that in a more elegant way? Does Django test framework provide a tool to do this? The main issue is determining what dataset has failed, if the test fails. Since my example uses a for loop that would not be easy unless we used additional statements. Let me mentioned that I found out that this can apparently be done with pytest, but I am using django.test here. -
Django create a register page which contains extra field
I am trying to create a register page which located www.mysite.com/register and contains "username,email,password" as usually and extra (gender,dateofbirth,workposition). Firstly i tried to make this by using this code but i failed. How can i create a Profile and RegisterPage which is using same User? in my accounts/forms.py class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=100, label='Kullanıcı Adı') password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) class Meta: model = User fields = [ 'username', 'password1', 'password2', 'gender', ] in my accounts/views.py def register_view(request): form = RegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password1') user.set_password(password) # user.is_staff = user.is_superuser = True user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) return redirect('home') return render(request, "accounts/form.html", {"form": form, 'title': 'Üye Ol'}) -
WebGUI Deployment with Python and Bash
I would like to build a simple webGUI interface for Python/Bash execution scripts running on a Linux VM. My ultimate idea is to create a Docker container out of it for easy deployment. So in principle, the website will have some input fields and depending on the input it should show the output fields, allow the ability to export the data in different formats and plot some graphs. It would be great if the webGUI has also responsive design, but it is not a must. The website should also support setting some parameters on remote machines using HTTP PUT/POST REST API and display the output of REST API GET requests. I have so far created command line bash script doing just this, but it requires access to the command line and it is not very user friendly, that's why I am looking for a way to put all this functionality on a webGUI. Do I need to re-write my script in Python, or I can still use Bash? I am a beginner, but I feel comfortable with Linux command line, Python and bash scripting. I just don't know what to use for the underlying web platforms. I was thinking that … -
Django optimistic concurrency on save - is it possible?
I don't currently have optimistic concurrency implemented in my application. Only the version field that gets updated on each save. However, all my form edits are implemented with save and not update. Is it possible to implement optimistic concurrency with save or I have to rewrite every edit method to update? (See this article https://invalidpatent.wordpress.com/2016/08/03/two-approaches-to-concurrent-write-safety-in-django/ it claims only update can be used) -
Django OAuth2 authorization server setup
I found django-oauth-toolkit, which I think will serve my purpose.As I'm new to Django, Oauth documentation seems confusing to me. DhaWhat I am trying to achieve is to link Alexa smart home skill with Django user accounts.Thus registered users will be able to use my smart home skill after completing account linking from Alexa app. From my research, I found that I need to create an authorization server for Alexa smart home skill and grant Alexa to access to User's data. So how can I create a such an Authorization server.? -
Run DJango server from outside of virtual environment by using script
I have created DJango Project inside virtual environment. Let's say virtual environment DJangoProject project name is Mysite I am tired of running ./manage.py runserver everytime so that I wanted to automate running server when I was logged into ubuntu.I tried many ways but was always failing to access the path of virtual environment. So help me to run manage.py runserver from outside of virtual environment using bash or shell scripting. any help can be appreciate! -
How to create queryset expression containing different types
I have two models like: class Category(models.Model): title = models.CharField(max_length=100) expires_in_days = models.PositiveIntegerField(default=20) class Item(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100) description = models.TextField() category = models.ForeignKey(Category) And I need to determine which items I should set expired: items_to_cancel = Item.objects.annotate(expires_date=F('created') + F('category__expires_in_days'))\ .filter(expires_date__lte=timezone.now().date()) Running this query raises an exception: FieldError: Expression contains mixed types. You must set output_field. Adding days to date is valid operation in Postgres, and since I have a simple arithmetic operation here, I don't understand where I should add this output_field parameter. And if I won't be able to get expiration date this way after all, how can I do it with raw SQL?