Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
css style not working in django production enviornment?
I am beginner in Django. When i hosted a django application with mod_wsgi in Apache2.4. I got a 404 error for my base.css. Any help should be appreciated. -
Field defines a relation with model 'MODEL', which is either not installed, or is abstract
Using custom user model in Django is like living in hell for me. After spending endless hours trying to get it done, now I face new problem: once I add some other app that depends on my custom user model I see this for example once I add 'django.contrib.admin', I see the error admin.LogEntry.user: (fields.E300) Field defines a relation with model 'main.Usr', which is either not installed, or is abstract. admin.LogEntry.user: (fields.E307) The field admin.LogEntry.user was declared with a lazy reference to 'main.usr', but app 'main' doesn't provide model 'usr'. my settings is like AUTH_USER_MODEL = 'main.Usr' INSTALLED_APPS = [ 'django.contrib.auth', 'main', # my app 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'debug_toolbar', 'django.contrib.postgres', ] -
Adding TextField to get user input
I have a question which has multiple answers underneath it and user has to select one of them but I also want to add some questions which just have a textfield and user can write and submit. How can I go about it? I have the following models, views and template code. Models.py: class Question(models.Model): text = models.TextField() active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True , auto_now=False) class Answer(models.Model): answers = models.ForeignKey(Question) text = models.TextField() active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True , auto_now=False) Forms.py: class UserResponseForm(forms.Form): question_id = forms.IntegerField() answer_id = forms.IntegerField() Template: <form method='POST' action='' > {% csrf_token %} <h1>{{ instance.text }}</h1> <input type='hidden' name='question_id' value='{{ instance.id }}' /> {% for ans in instance.answer_set.all %} <input type='radio' name='answer_id' value='{{ ans.id }}' {% if user_answer.my_answer.id == ans.id %}checked=checked{% endif %}/> {{ ans.text }} <br/> {% endfor %} <input type='submit' value='Save and continue' /> </form> -
Date formator In django
i working on a registration form in django I taking input from date field from front end is "12/15/2016" but i want to save it like 12 dec 2016 in my django database. I am using this calender <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <script> $(document).ready(function() { $("#datepicker").datepicker(); }); </script> my model.py for date is posting_date = models.DateField(blank=True) Views.py post_date = str(request.POST['date']) date = post_date.split('/') formatted_date= date[1]+"-"+date[0]+"-"+date[2] I want to save Dec instead of 12 for month -
Queuing tasks on an Ubuntu VPS that creates and stores objects
I have a Django application that reads text files and extract relevant data from them. Some text files can be very big and there are many text files to parse hence offloading the file processing is necessary to avoid DOSing the server which the Django application lives in. Here's a simple diagram of what I'm trying to achieve: I have a couple of questions: Should the main database where data is stored/read from be on the same server as that of the Django application or on the Ubuntu VPS? Do I create a second instance of the Django application that acts as a proxy on the VPS? If the answer is no, how do I get the parser script on the VPS to create data objects for (postgres) database insertion? Do I have to use a raw SQL insert query? Is there a specific guide to achieve all of this? The only guide I've come across is this: How To Use Celery with RabbitMQ to Queue Tasks on an Ubuntu VPS -
Django translations not showing from app's po
I've been developing an application which works in English or French (Canadian). Django settings are; LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', gettext('English')), ('fr-ca', gettext('Canadian French')), ] LOCALE_PATHS = ( ... os.path.join(PROJECT_ROOT, 'console', 'locale'), ... ) The app's locale path is console/locale/fr-CA/LC_MESSAGES/ The app however has recently stopped rendering the vast majority of the translations. For example, I've got a form with 'First name', 'Last name', 'Email'. Yesterday this was correctly using the po file; #: console/forms/participants.py:631 msgid "First Name" msgstr "Prénom" #: console/forms/participants.py:635 msgid "Last Name" msgstr "Nom" #: console/forms/participants.py:140 console/forms/participants.py:469 #: console/forms/participants.py:639 console/models/mixins.py:70 msgid "Email" msgstr "Courriel" But today, only the Email string is appearing in French. I assume ugettext is getting that from another application because I've tested it in the shell; >>> from django.utils.translation import ugettext, activate >>> activate('fr-ca') >>> ugettext('Sunday') u'dimanche' >>> ugettext('Event') u'Event' >>> ugettext('Yes') u'Oui' >>> ugettext('Gender') u'Gender' >>> ugettext('enquiry') u'enquiry' >>> ugettext('Enquiry') u'Enquiry' >>> ugettext('Receive notifications about other events.') u'Receive notifications about other events.' These are all taken from the app's po file; #: console/models/events.py:35 console/models/events.py:206 #: console/models/participants.py:81 console/models/vouchers.py:14 msgid "Event" msgstr "Événement" #: console/models/participants.py:113 msgid "Gender" msgstr "Sexe" #: console/models/participants.py:160 msgid "Receive notifications about other events." msgstr "Recevez des notifications pour … -
Django Python - Convert to datetime from Wed Dec 14 2016 14:39:16 GMT+0300 (AST)
I have a function in my backend and I receive the date from the front end in the formart Wed Dec 14 2016 14:39:16 GMT+0300 (AST) date = request.body['date'] d = datetime.strptime(date, '%a %b %d %Y %X %Z%z') I know strptime converts to the datetime object but I keep getting the following 'z' is a bad directive in format '%a %b %d %Y %X %Z%z' What should my string format be? -
Template loader doesn't find /registration/password_reset_form.html
I am having a strange issue using the built in password_rest view of django(1.8). In the documentation they say that the template name defaults to registration/password_reset_form.html. Keeping that in mind, i didn't give any template name in my urls.py, thinking that django will load the default template.Here is my url for the password reset urls.py url(r'^password_reset$', auth_views.password_reset, name='password_reset'), When i click the forgot password link, <p><a href={% url 'password_reset' %}> Forgot your password?</a></p> which executes the password_rest view, i am getting Template DoesNotExist error and below is the error message TemplateDoesNotExist at /accounts/password_reset registration/password_reset.html Template-loader postmortem Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /home/vinothkumar/github/djtest/templates/registration/password_reset.html (File does not exist) Using loader django.template.loaders.app_directories.Loader: /home/vinothkumar/github/djtest/venv_new/lib/python3.4/site-packages/django/contrib/admin/templates/registration/password_reset.html (File does not exist) /home/vinothkumar/github/djtest/venv_new/lib/python3.4/site-packages/django/contrib/auth/templates/registration/password_reset.html (File does not exist) /home/vinothkumar/github/djtest/accounts/templates/registration/password_reset.html (File does not exist) my question is why the template loader is looking for /registration/password_reset.html instead of loading the default /registration/password_reset_form.html? I tried the same approach for password_reset_done, in this case it loads the default template /registration/password_reset_done.html. and everything there works fine. Thank you.any input in the right direction is highly appreciated. -
DRF Upload multiple file
I'm using DRF to create an user with multiple attachments. When you create an user you have to upload one or more files. When I make an update of an user which you load a new file (no other modified field) the response back the old instance. I solved by forcing the '_prefetched_objects_cache' attribute in the serializer before returning the instance. setattr(instance, '_prefetched_objects_cache', True) Is it correct? You have other solutions about it? thanks There is my code in models.py class User(models.Model): #field of user model class Attachment(models.Model): class Meta: db_table = 'attachment' path = models.FileField() user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='attachments') dt_created = models.DateTimeField(auto_now_add=True, verbose_name='Created') in serializer.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = '__all__' class UserSerializer(serializers.ModelSerializer): attachments = AttachmentSerializer(many=True, read_only=True) def create(self, validated_data): user = User.objects.create(**validated_data) for file_item in self.initial_data.getlist('attachments'): c = Attachment(path=file_item, user=user) c.save() return user def update(self, instance, validated_data): for item in validated_data: if User._meta.get_field(item): setattr(instance, item, validated_data[item]) c = Attachment(path=self.context['request'].FILES['attachments'], user=instance) c.save() instance.save() setattr(instance, '_prefetched_objects_cache', True) return instance in test.py io = StringIO.StringIO() io.write('foo') file = InMemoryUploadedFile(io, None, 'foo.txt', 'text', io.len, None) file.seek(0) self.user['attachments'] = [file, file] data = self.user response = self.client.post(url, data, format='multipart') file = InMemoryUploadedFile(io, None, 'foo2.txt', 'text', io.len, None) file.seek(0) … -
Django model inner join issues
suppose I have the following three models, see as follow: I wanna to construct a Django model query to archive the same effect as the following SQL statement. SQL statement select B.value, C.special from B inner join C where B.version = C.version and B.order = C.order; I got the following three models: class Process(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=150) class ProcessStep(models.Model): process = models.ForeignKey(Process) name = models.CharField(max_length=30) ... order = models.SmallIntegerField(default=1) version = models.SmallIntegerField(null=True) class Approve(models.Model): process = models.ForeignKey(Process) content = models.CharField(max_length=300) ... version = models.SmallIntegerField(null=True) order = models.SmallIntegerField(default=0) I want to find all Approves that have the same (version, order) tuple matching against the ProcessStep model. -
request.POST.get() showing a None print is used
Like the question said, when I print, it shows the list/string first then a "None" in the end just like this: ["a","b","c"] "test" None None script $(document).ready(function() { $("#export").click(function () { var test = "test"; var array1 = ['a','b','c']; $.ajax({ url: '/export/csv', data: {'array1': JSON.stringify(array1), 'test': JSON.stringify(test)}, dataType: 'json', type: 'POST', success: function (data) { } }); }); }); views.py def export_csv(request): test1= request.POST.get('test') array1= request.POST.get('array1') print(identifiers) print(test123) urls.py url(r'^export/csv$', product_views.export_csv, name='export_csv') I know I'm missing something in my views.py. If you could point me to the right direction, that would be great. Thanks in advance! -
Unable to do PUT operation -DjangoRESTFramework
I am unable to do PUT operation in Django rest framework, I am able to GET, POST, DELETE operation. This is the error I have tried using @api_view but there also its not, I mostly refer the djangorestframework website Below is my code: serializers.py from rest_framework import serializers from snippets.models import Snippet #from django.contrib.auth.models import * class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id','title','code') Models.py from __future__ import unicode_literals from django.db import models # Create your models here. class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.CharField(max_length=100, blank=True, default='') class Meta: ordering = ('created',) Views.py from rest_framework import viewsets from rest_framework.decorators import api_view from snippets.serializers import SnippetSerializer class SnippetViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Snippet.objects.all().order_by('id') serializer_class = SnippetSerializer urls.py rom django.conf.urls import url, include from rest_framework import routers from django.contrib import admin from snippets import views router = routers.DefaultRouter() router.register(r'snippet', views.SnippetViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] -
Save date in django in desired format
I want to save date in my django model into desired format. post_date = str(request.POST['date']) I am getting date from front end is 12/21/2016 i want to save this date in my django modal is like 21-Dec-2016. How can i do it. it will be good if you can provide some sample code. Thanks in advance. -
Sending asynchronous requests via proxies with Python
I need to send 30 GET requests, parse the contents, check some data on them and if they are what I'm looking for put them into database via Django ORM. I need to do this every 5 minutes. Using python-requests sequentially with proxies takes too much time. I concluded the best way to do it is asynchronously. And as the saying goes - programmer had a problem - "I know, I will use regex!" - now he got two problems. I tried grequests, but for example doing: proxy = {"http" : "127.0.0.1:666"} rs = (grequests.get(u, proxy=proxy) for u in urls) And then: grequests.map(rs) It returns list of Nones (I assume it works ok, but my proxies suck). Most of the time only handfull of this requests will return 200. I'm confused at this point to what the correct way of doing this would be. Should I just loop it till I get it right? Maybe I should use celery? In short, what would be the most effective way to send bunch of requests every 5 minutes, get the data out and put it into the database? I'll be grateful for every insight. Thanks -
Augmented assignments in python
My editor threw up an interesting hint today in some Django code I was looking at, namely where I had status_query = Q() for status in request.GET.getlist('status'): # i.e "open", "closed" status_query = status_query | Q(status=status) (Q() being a Django query object) It recommended I use an augmented assignment in place of the last line i.e.: status_query |= Q(status=status) That's fine, looks neater and more readable. My concern is that the behaviour won't be identical as I seem to lack an understanding of how the bitwise | operator works, which I demonstrated to myself by doing the following: >>> a = 2 >>> a |= 6 >>> a 6 >>> a = 2 >>> a |= 5 >>> a 7 In the above I've no idea why one of those assignments appears to add the two numbers together and the other is an assignment. Is there a way I can deconstruct the process to work out exactly what is happening with these operators? -
Django translations mutliple .mo files
There are two sets of .po files: one set is created when ./manage.py makemessages is called, and other is custom made when one of translation scripts. After debugging, I realized that GNUTranslation class sets domain to be django, leading to load only django.mo file. Is there any way to set application to load all .mo files regardless of domain? -
How to return to Django from an Angular form?
In a Django 1.8 app I have a form that is posting using Angular.js. After the form has been submitted by Angular to Django Rest Framework I would like to move to another Django view. My question is how to move to another Django view apart from using $windows.location.href? At the moment I'm using $windows.location.href but I would like Django(meaning not Javascript/Angular) to move to another page. Here's how I do it now - for brevity here's a small part of this form in my template: <div ng-app="pacjent"> (...) <div ng-controller="NewPatientCtrl"> (...) <form name="newPatientForm" ng-submit="newPatientForm.$valid && submitNewPatientForm()" ng-init="initialize('{{user.id}}')" novalidate> {% csrf_token %} (...) </form> This form is posting all data to Django Rest Framework like this: function submitNewPatientForm(){ /* it's prime goal is to submit name,surname, age & phone to createNewPatient API */ $scope.setBusy = true; savePatient = $http({ method: 'POST', url: 'http://localhost:8000/pacjent/api/createNewPatient/', data: $scope.newPatient, }) .then(function successCallback(response){ newPatient = response.data['id']; createNewTherapyGroup(); url = patientDetailView + response.data.id + '/'; $window.location.href=url; # I DON"T WANT TO USE THIS, but I don't know how! }, function errorCallback(response){ if (response['data']['name'] && response['data']['surname']) { $scope.newPatientForm.newPatientName.$setValidity("patientExists", false); $scope.errors.newPatientName =response.data['name'][0]; } (...) Is there a way to do it differently? -
Django flaky url (randomly omits WSGIScriptAlias)
My Django site is producing URLs that intermittently omit my WSGIScriptAlias. If I simply print out {% url 'index' %} in my index.html (see my urls.py settings below) I randomly (around 50% of the time) get either: MySiteAlias/MySite which is correct, or MySite/ which is incorrect. myapp/urls.py: from django.conf.urls import url,include urlpatterns = [ url(r'^MySite/', include('mysite.urls')), ] mysite/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] and views.index basically does return render(request, 'mysite/index.html). Any ideas on how to fix this? -
django.template.exceptions.TemplateDoesNotExist exception while running python manage.py test
I am running the django application on nginx-uwsgi. The template is getting rendered if i browse the code on the browser. The error is thrown only when i run the test. The templates are present in the project/templates folder. The following is my project structure -myproject | | |-__pycache__ | | |-templates | | | |-admin | |-myapp | | |-test.py | | |-migrations | | | |-__pycache__ | | |-__pycache__ | |-static | | |-images | | |-css | | |-js This is my settings config: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Python/Django- Save csv file data with messy rows
I have a csv file with the following structure: A, 10 B, 11 C, 8 D, 12 A, 21 B, 7 D, 22 D, 15 C, 111 D, 50 A, 41 B, 32 C, 19 D, 11 I want to read the entire file, and save the data on the second column, if the row is like A, B, C, D format. I have a list: my_list = [A, B, C, D] And I check each 4 row, if it is in my_list format, then read and save to the database like: with open('csv_file.csv', 'rb') as csvfile: the_file = csv.reader(csvfile.read().splitlines()) for idx, row in enumerate(islice(zip(*[the_file]*4), 100)): my_model = Django_model() if row[0][0] == my_list[0]: if row[0][0] == my_list[0] and row[1][0] == my_list[1] and \ row[2][0] == my_list[2] and row[3][0] == my_list[3]: my_model.a_field = row[0][1] my_model.b_field = row[1][1] my_model.c_field = row[2][1] my_model.d_field = row[3][1] my_model.save() The fact is that it is working if and ONLY if the structure of the row is the same as my_list. But when it gets to the messy part (A, B, D, D, C, D) it will not read the rows properly, and therefore many rows are skipped. The question is that, how can I jump to … -
DRF - Filters in ModelSerializer
In my models an User is related with its Profile, which has Companies. In order to serialize them I want that if the user who makes the request is_staff, then the serializer must return all the companies, not only the ones s/he has through the relationship in the model. What's the proper way to...: 1) Check if the user is staff. 2) Return all the companies if user is staff or return the companies of the profile related with the user. My current code doesn't take into account if the user is staff so return just the companies related with that user: models.py class BUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=40, unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) class BProfile(models.Model): user = models.ForeignKey('BUser') company = models.ForeignKey('BCompany') groups = models.ManyToManyField(Group) class BCompany(models.Model): name = models.CharField(max_length=64) dealer = models.ForeignKey(BProfile, related_name='companies', blank=True, null=True) views.py @api_view(['GET']) def current_user_detail(request): serializer = BUserSerializerRelated(request.user) return Response(serializer.data) serializers.py class BUserSerializerRelated(serializers.ModelSerializer): bprofile_set = BProfileSerializerRelated(many=True) class Meta: model = BUser fields = ('id', 'bprofile_set', 'username', 'email', 'first_name', 'last_name') class BProfileSerializerRelated(serializers.ModelSerializer): company = CompanySerializer() groups = GroupSerializer(many=True) dealer_companies = CompanySerializer(many=True) class Meta: model = BProfile fields = ('id', 'dealer_companies', 'company', 'groups') class CompanySerializer(serializers.ModelSerializer): sites = SiteSerializer(many=True) services = ServiceSerializer(many=True) class Meta: model = … -
using rfid key to fetch django model object automatically
Am working on this app where the admin will lookup an object in the model and the object instance gets fetched automatically without cliking the models. How can I get all related data about the object from all foreign key related models and display it in the admin? -
Error while migrate postgres to django?
I am trying to migrate postgres on django , while am getting error like this , Unknown command: 'migrate' Type 'manage.py help' for usage. I am following this link .. https://docs.djangoproject.com/en/1.10/intro/tutorial02/ Can anyone help me plz.. -
Django 1.8 - Model with 2 foreign keys from the same class
I wanted a Django model with 2 foreign keys from the same table. I will want in my form to save a new match for the model Match where I need to include 3 fields: the 'home' and the 'away' teams and the date. But I get this error: File "/Users/pabloruiz/PycharmProjects/Betcomm/calendars/models.py", line 12, in <module> class Match(models.Model): File "/Users/pabloruiz/PycharmProjects/Betcomm/calendars/models.py", line 16, in Match home_team = models.ForeingKey(calendars.Team, related_name='home') AttributeError: 'module' object has no attribute 'ForeingKey' Here is my files: models.py from django.db import models class Team(models.Model): team_name = models.CharField(max_length=20) def __unicode__(self): return self.team_name class Match(models.Model): home_team = models.ForeingKey(Team, related_name='home') away_team = models.ForeingKey(Team, related_name='away') match_round = models.IntegerField() date = models.DateField() Thanks in advance! -
Deploying django project on apache
My django project mysite is located at path: /web/mysite My virtualenv testEnv is located at path: /web/testEnv All files and directories in in the above mentioned two paths are owned by www-data : www-data All directories have permission drwxr-xr-x, files have permission -rw-r--r-- and db.sqlite3 has permission -rw-rw-r--. I have added the following configuratiom in the apache default configuration file. <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /web/mysite <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /web/mysite> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> ... Some more config here ... Alias /static /web/mysite/mysite/static <Directory /web/mysite/mysite/static> Order allow,deny Allow from all </Directory> <Directory /web/mysite/mysite> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> WSGIDaemonProcess mysite python-path=/web/testEnv/lib/python2.7/site-packages WSGIProcessGroup mysite WSGIScriptAlias / /web/mysite/mysite/wsgi.py </VirtualHost> When I restart the apache server I get the following error, ImportError: No module named mysite.settings I have checked multiple tutorials with still no luck and would need some guidance on the same.