Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve " django.db.utils.OperationalError: FATAL: password authentication failed for user "Oeloun-pc" " in Pycharm Windows?
Below is my screenshot of PyCharm including settings.py and pg_hba.conf file. PyCharm with pg_hba.conf screen -
Conditional if print dates in wrong date rows in table in django
I want to print some messages in those dates which were shifted from previous dates. For that I have two Models one for storing both previous dates and new dates in the same sit_date field. This model is: class Sitting(models.Model): sit_date = models.DateField(blank=False,unique=True) cut_off_date = models.DateField(null=True, blank=True) ballot_date = models.DateField(null=True, blank=True) sess_no = models.ForeignKey(Session, on_delete=models.CASCADE) genre = TreeForeignKey('Genre', null=True, blank=True, db_index=True) Another model for creating shift dates using the sit_date of above model. When I created shift dates this dates are stored in the sit_date field of Sitting model. Here is my second model: class Shiftdate(models.Model): shift_date = models.DateField(blank=False,unique=True) sit_date = models.ForeignKey(Sitting, on_delete=models.CASCADE) shift_cut_off_date = models.DateField(null=True, blank=True) shift_ballot_date = models.DateField(null=True, blank=True) sess_no = models.ForeignKey(Session, on_delete=models.CASCADE) genre = TreeForeignKey('Genre', null=True, blank=True, db_index=True) After that when render sit_date in the template, I want to check which sit_dates are equal to the sit_dates of Shiftdate model. If found there should be a message print on the shift dates rows in the table. For that so far I get following code in my template: {% for sitting in c.sittings %} {% for shiftdate in sitting.shiftdate_set.all %} {% if sittings.sit_date == shiftdate.sit_date %} <p>Firstly it was scheduled on {{sitting.shift_date}}</p> {% endif %} {% endfor %} … -
Why do I get Django error "Models aren't loaded yet." when I'm running a non-standalone Django application?
I have a Django 1.8.2 project with multiple Django applications. Application A contains a model that looks like this: class MyClassA(models.Model): name = models.CharField(max_length=50, null=False, blank=False, ) created_ts = models.DateTimeField(default=datetime.utcnow, editable=False) Application B contains a model that looks like this: class MyClassB(models.Model): name = models.CharField(max_length=50, null=False, blank=False, ) my_class_a = models.ForeignKey(MyClassA, related_name="MyClassB_MyClassA") When I run manage.py test, it works fine. Then I add the following method to MyClassA: def my_method(self): return self.MyClassB_MyClassA.get() Now, when I run manage.py test, I get the following error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Why? How do I make this work? This Django documentation says that explicitly calling django.setup() is required if I am running a "standalone application". But this is not a standalone application. It is being run through manage.py. And I see the same error when I run the Django webserver. -
Upload and rename two different files in two different folders using django?
I could upload two different files in the same folder using django. But I have to upload it to two different folders and also rename the files I uploaded as target.{file_extension} and probe.{file_extension}.I have no idea as I am a beginner to django.Could anyone please help me with my issue. My codes are: In django model.py dirname = datetime.now().strftime('%Y.%m.%d.%H.%M.%S') class Document(models.Model): docfile = models.FileField(upload_to=dirname) In views.py def test(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() else: form = DocumentForm() # An empty, unbound form documents = Document.objects.all() return render( request, 'personal/basic.html', {'documents': documents, 'form': form} ) And in my basic.html <form action="/simulation/" method="post" enctype="multipart/form-data" single> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} <input type="submit" value="Upload" name = "file1"/></p> </form> -
django.db.utils.OperationalError: no such table: auth_user
After I install Django-userena,there is an error my django version :1.9.5 I just install django-userena step by step ,but when i migrate it ,an error happend and I don't how to solve it ,plz help me thanks! Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle emit_post_migrate_signal(self.verbosity, self.interactive, connection.alias) File "C:\Python27\lib\site-packages\django\core\management\sql.py", line 50, in emit_post_migrate_signal using=db) File "C:\Python27\lib\site-packages\django\dispatch\dispatcher.py", line 192, in send response = receiver(signal=self, sender=sender, **named) File "C:\Python27\lib\site-packages\guardian\management\__init__.py", line 33, in create_anonymous_user User.objects.get(**lookup) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 381, in get num = len(clone) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 240, in __len__ self._fetch_all() File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 52, in __iter__ results = compiler.execute_sql() File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 848, in execute_sql cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in … -
What's difference between property and fields of meta in django form?
Curious about their difference. Example : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm GENDER_CHOICES = ( ('M', '남'), ('F', '여'), ) class MyUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) birth = forms.DateField(widget=forms.SelectDateWidget( years=range(1970, 2015)), required=True) gender = forms.ChoiceField(choices=GENDER_CHOICES, initial='M') class Meta: model = User fields = ('username', 'birth', 'email', 'gender', 'password1', 'password2') def save(self, commit=True): user = super(MyUserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.birthday = self.cleaned_data['birth'] if commit: user.save() return user It defines email, birth, gender as properties of form, and it also has fields in Class Meta. I want to clearly understand their difference. Thanks in advance. -
How can I use get_next_by_FOO() in django?
I am building blog website and trying to put next and prev buttons for next post and previous post respectively. In the official document, it explains get_next_by_FOO(**kwargs) and where FOO is the name of the field. This returns the next and previous object with respect to the date field. So my models.py and views.py are following. models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) class Meta: ordering = ["-timestamp", "-updated"] views.py def post_detail(request, id=None): instance = get_object_or_404(Post, id=id) the_next = instance.get_next_by_title() context ={ "title": instance.title, "instance": instance, "the_next" : the_next, } return render(request, "post_detail.html", context) Do I misunderstand its concept?? If I do, how can I deal with it? Thanks in advance! -
Creating a proxy for .gifs on Django
I want to create a simple page that will take a simple gif page, like this monthy python gif and put it into my django app. I have a simple views code that works for images, but it doesn't work for gifs: def gif(request): import urllib2 url='https://media.giphy.com/media/UFzjusdrC1EOc/giphy.gif' req = urllib2.Request(url) response = urllib2.urlopen(req) return HttpResponse(response.read(), "image/png") I was wondering if anyone knows a way to create a proxy for gifs on Django. -
django get_queryset get() returns more than one object error
For these models: class Product(models.Model): code = models.IntegerField() class Failure1(models.Model): FAILURE_CHOICES = ( ('SC', 'Screen'), ('BA', 'Battery'), ('BX', 'Box'), # etc, with 10+ choices ) name = models.CharField(max_length=2, choices=FAILURE_CHOICES) class Failure2(models.Model): FAILURE_CHOICES = ( ('SZ', 'Blah'), ('BB', 'Basdasd'), ('BD', 'etc'), # etc, with 10+ choices ) name = models.CharField(max_length=2, choices=FAILURE_CHOICES) class Market(models.Model): MARKET_CHOICES = ( ('ED', 'Education'), ('CO', 'Commercial'), # etc, with 10 choices ) product = models.ForeignKey(Product) market = models.CharField(max_length=2,choices=MARKET_CHOICES) failure1 = models.ManyToManyField(Failure1, blank=True) failure2 = models.ManyToManyField(Failure2, blank=True) class Failure_MarketManager(models.Manager): def get_queryset(self): return super(Failure_MarketManager, self).get_queryset().filter(Q(failure2__name__isnull=False) | Q(failure1__name__isnull=False)) class Failure_Market(Market): class Meta: proxy = True objects = Failure_MarketManager() What I'm after is an admin changelist that shows only those Markets with any Failures (from either the Failure1 or Failure2 list). With the proxy model above, if there is more than one Failure, I get a 'get() returns more than one object' error. If I change it to get_queryset().exclude(Q(failure2__name__isnull=True) | Q(failure1__name__isnull=True)) I get zero results - why is this ? If I change it to get_queryset().filter(~Q(failure2__name__isnull=False) | ~Q(failure1__name__isnull=False)) it works - why does this work but the filter Q doesn't ? -
Python - Post File to Django With Extra Data
I'm trying to have my django rest framework app accept file uploads. The uploads should be accompanied by additional data that is descriptive of the file and is necessary for post-processing. Uploading the file seems to work fine, however, I can't seem to get the django app to access the other data. For example, I have the file more_info.html which I am trying to upload to my app: import requests url = "http://www.example.com/fileupload" files = {'file':open('more_info.html','rb') data = {'brand':'my brand','type':'html','level':'dev'} headers = {'Content-type': 'multipart/form-data', 'Content-Disposition': 'attachment; filename="more_info.html"'} r = requests.post(url,files=files,data=,headers=headers) In my Django view I am trying to view my POST data with the following: def post(self, request): print(request.POST) print(request.FILEs) Both print statements are returning: {u'file': <InMemoryUploadedFile: more_info.html (multipart/form-data)>} How can I access the rest of the data in the request POST? -
Match a repeating pattern in python without grouping
match a repeating regex I have a regular expression to match a hex pattern and a uuid pattern as: HEX_PATTERN = '[0-9a-f]{32}' UUID_PATTERN = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' so to match either a HEX_PATTERN or a UUID_PATTERN was easy enough; I just create the following ID_PATTERN = UUID_HEX_PATTERN + '|' + UUID_PATTERN and add this to url.py url(r'^sites/(?P<org_id>%s)/maps$' % ID_PATTERN, get_org) now I have a situation where I want to match a string that's a combination of two UUID or HEX, for instance 15a5e2e6-b453-491a-841d-6154503f8125.dc1cc37d-d7d0-48eb-9d8f-f8064bb00ce0 This felt easy enough, and I created another pattern with the combination COMB_PATTERN = '(' + ID_PATTERN + ')[/.]{1}(' + ID_PATTERN +')' and changed the urls.py as url(r'^sites/(?P<org_id>%s)/maps$' % COMB_PATTERN, get_org) But this isn't seem to be working. When django resolves all the urls it appears as: {org_id}[.]{1}{var}) Notice the trailing bracket at the end, and more or less broken path. I have also tried grouping the ID_PATTERN, but that didn't work either. Checkout my other question here: Django url with regex pattern resolves with a trailing bracket Is there a way to avoid running into this? I mean matching 15a5e2e6-b453-491a-841d-6154503f8125.dc1cc37d-d7d0-48eb-9d8f-f8064bb00ce0 without grouping them. I have a hunch named pattern doesn't support grouping. -
ImportError: /usr/local/lib/python2.7/lib-dynload/_io.so: undefined symbol: _PyCodec_LookupTextEncoding
When I used command : pip freeze it shows message error follow: Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in <module> from pip import main File "/usr/local/lib/python2.7/site-packages/pip/__init__.py", line in <module> from pip.utils import get_installed_distributions, get_prog File "/usr/local/lib/python2.7/site-packages/pip/utils/__init__.py", line 6, in <module> import io File "/usr/local/lib/python2.7/io.py", line 51, in <module> import _io ImportError: /usr/local/lib/python2.7/lib-dynload/_io.so: undefined symbol: _PyCodec_LookupTextEncoding which pip: /usr/local/bin/pip which python: /usr/local/bin/python I do not know why it's in error ! so I hope anybody can help me to resolve problem ! thank you. -
Django Celery Periodic Task not running (Heroku)?
I have a Django application that I've deployed with Heroku. I'm trying to user celery to create a periodic task every minute. However, when I observe the logs for the worker using the following command: heroku logs -t -p worker I don't see my task being executed. Perhaps there is a step I'm missing? This is my configuration below... Procfile web: gunicorn activiist.wsgi --log-file - worker: celery worker --app=trending.tasks.app Tasks.py import celery app = celery.Celery('activiist') import os from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) os.environ['DJANGO_SETTINGS_MODULE'] = 'activiist.settings' from trending.views import * @periodic_task(run_every=crontab()) def add(): getarticles(30) One thing to add. When I run the task using the python shell and the "delay()" command, the task does indeed run (it shows in the logs) -- but it only runs once and only when executed. -
Django Foreign key on abstract model or GenericForeignKey
here is my (simplified) model: class Node(models.Model): name = models.CharField(max_length=256) parents = models.ManyToManyField('self', through='Share', blank=True, related_name="%(app_label)s_%(class)s_parents", related_query_name="%(app_label)s_%(class)ss_parents",) children = models.ManyToManyField('self', through='Share', blank=True, related_name="%(app_label)s_%(class)s_children", related_query_name="%(app_label)s_%(class)ss_children",) class Meta: abstract = True class Individual(Node): rank = models.IntegerField(blank=True, null=True) other_groups = models.CharField(max_length=256, blank=True, null=True) class Company(Node): pass class Media(Node): pass class Share(models.Model): share = models.FloatField(null=True) child = models.ForeignKey('Node', related_name='child') parent = models.ForeignKey('Node', related_name='parent') My goal here is to implement a kind of graph : 3 types of nodes, Individual, Company and Media, inheriting from a single abstract class Node. 1 type of link, Share, between any kind of Node I'm lost regarding what should be done here, on the one hand regarding the two ManyToMany relationships in the abstract class referring to the abstract class itself (when, in practice, it will be Individuals, Companies and Medias), on the other hand regarding the intermediate table Share that references two ForeignKeys to an abstract class (in practice Individuals, Companies and Medias). -
Python Django Download Model as Excel File
I have database with some data and I want to download it as an excel file. In other words, how can I programmatically convert my model to excel file when I hit download button on my app. -
Django Wagtail Dashboard Blank After Upgrade to 1.6
Just updated Wagtail in my Django project to version 1.6. Now when I login to admin I get a blank screen, no errors. My Django version is 1.10. The front-end works fine; I can browse all the pages with no errors. I can even login to /django-admin just fine. Any idea why this is? Thank you. -
Dynamic ModelForms on a page and Accessing unsaved models in multi page form wizard
I want to be able to press a button to add Models to a temporary, or unsaved collection of objects of a certain Model, to populate the a field for the foreign key of an object on the next page of the form wizard, (of which I want the same behavior of being able to dynamically add/remove submit multiple instances of a ModelForm before ✔ok'ing the whole thing. Is this possible? How do I populate some temporary list of Tasks, save them, and load them on the next page? -
Populate ModelChoice
I have a multi-step CRUD submission form using the django-forms app. It has four steps. In step 3, one of the forms has a foreign-key relationship with a model that would have been created, but not saved to the database, in one of the earlier steps. How do I populate my forms with object they have created, when I want to save all of the models only at the end of the form wizard? -
Including the same blocks in several pages in Django
On my website, blog posts appear in multiple places across the site. I want to create a template like blog_posts.html that given the list of blog posts (as an argument to render) creates the block with these posts, formatted and processed. There are several disconnected pages to which I want to display blog_posts. Thus, I can not say that blog_posts extend any of them. I wonder if there is a way to insert whatever template processed to arbitrary page? If yes, how to I pass variables (which may be instances of the classes) to the blog_posts template? -
Django best design for a form with dynamic number of input fields
I am creating a page to handle the product selection for an end-user for an Event. An Event can consist of multiple products (Gold, Silver, Bronze, etc.) Each product has a Name, Description, and price. These products can only be associated to a single event. When the user arrives to the product selection page, I would like them to be able to select the quantity of each product that they would like. For instance it would be OK for the user to select 5 of the Bronze product package and 2 of the Gold product package. I am running into the issue where each input field has the same ID & Name, and thus only the contents of the last field actually makes it into the request.POST data. What would be the appropriate changes I need to make to follow a proven design pattern where I can create an InvoiceLineItem entry? Models.py class Product(models.Model): event = models.ForeignKey(Event) product_name = models.CharField('Name', max_length=100, null=False, blank=False) description = models.CharField('Description', max_length=400, null=False, blank=False) price = models.DecimalField('Price', max_digits=8, decimal_places=2, default=0.0) def __str__(self): return self.event.event_name + "-" + self.product_name class Invoice(models.Model): user = models.ForeignKey(User) tax = models.DecimalField('Tax', max_digits=2, decimal_places=2, default=0.0) total_price = models.DecimalField('Total', max_digits=8, decimal_places=2, default=0.0) … -
How to generate a static Django JavaScript translation catalog
Doing translation in JavaScript in Django apps is covered in the documentation quite well. However, the built-in Django way is to load a JS file in a . Of course, they suggest to cache this, but one either needs to use etags or another mechanism and it will normally add at least one more request to the page load. However, most decent websites already have a build system for preparing static files, i.e. using gulp - for compiling SCSS, sprites and whatnot. This is the perfect place to build a JS translation catalog, concatenate it with the rest of the JS and make 1 single bundled JS file. There doesn't seem to be way to generate a static JS file from the current *.mo files. Reading through the Django code, it seems that the JavaScriptCatalog view is responsible for generating that JS code and it's not easily reusable for that purpose either. TL;DR Is there an easy way to generate a static .js file with the current translation catalog in a fashion similar to using the built-in JavaScriptCatalog? -
Authorization header not being set
I'm trying to create an admin panel using ng-admin and data from Django-based REST API but I can't get through the authorization stage. After setting "WSGIPassAuthorization On" I was able to confirm that I indeed have access to the data: Yet, following the FAQ from ng-admin documentation leads to The code from the documentation that I'm reffering to is: myApp.config(function(RestangularProvider) { var login = 'admin', password = 'mypassword', token = window.btoa(login + ':' + password); RestangularProvider.setDefaultHeaders({'Authorization': 'Basic ' + token}); }); I'd be very thankful for any help. -
How to find out which attributes can I access in a template and how?
How to find out which attributes and their names can I access in Django templates? For example I have a telephone field in my Form. I'm using django-phonenumber-field to modify the telephone field - divide to prefix, which is a select and char field. Now I want to access those two parts separately in template. In html: it is generated by: {{ user_creation_form.telephone }} I don't know how to access for example only the first tag - select which represents a prefix of the number. I've tried telephone.0 and telephone.prefix. Is there a way how to solve this kind of situation? -
Remove fields of a HyperlinkedModelSerializer's ForeignKey based on the base request parameters
At the moment i have: class PlayerSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Player def __init__(self, *args, **kwargs): super(PlayerSerializer, self).__init__(*args, **kwargs) self.is_full = self.context['request'].query_params.get('full', False) if not self.is_full: base_fields = ['nation', 'club', 'slug', 'common_name', 'image', 'position', 'quality', 'overall_rating', 'card_att_1', 'card_att_2', 'card_att_3', 'card_att_4', 'card_att_5', 'card_att_6'] for field in self.fields: if field not in base_fields: self.fields.pop(field) self.fields['nation'] = NationSerializer(is_full=self.is_full) self.fields['league'] = LeagueSerializer(is_full=self.is_full) self.fields['club'] = ClubSerializer(is_full=self.is_full) Which works fine, but the ClubSerializer has class ClubSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() league = LeagueSerializer() and i want that LeagueSerializer to have the fields based on the value of the requests query params. Would it just be a case of not passing it as a kwarg and doing the self.is_full = self.context['request'].query_params.get('full', False) check on every Serializer individually? -
My Django CSS is hosted on Google Drive and only shows up on the Chrome browser. Is that normal?
This link is in the header of my base.html: <link rel="stylesheet" href="https://googledrive.com/host/0B343XFIY55_lTUxJWk5YMEVzT1E"> The stylesheet only works when the website is accessed through Chrome. The web page appears without any styling whatsoever on Firefox and IE. Does Drive hosted CSS only work on Chrome? Is there something I'm doing wrong?