Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset union appears not to be working when combined with .annotate()
I have the following queryset photos = Photo.objects.all() I filter out two queries. a = photos.filter(gallery__name='NGL') b = photos.filter(gallery__name='NGA') I add them together, and they form one new, bigger queryset. c = a | b Indeed, the length of a+b equals c. a.count() + b.count() == c.count() >>> true So far so good. Yet, if I introduce a .annotate(), the | no longer seems to work. one = photos.annotate(c=Count('label').exclude(c__lte=4) two = photos.filter(painting=True) all = one | two one.count() + two.count() == all.count() >>> False How do I combined querysets, even when .annotate() is being used? Note that query one and two both work as intended in isolation, only when combining them using | does it seem to go wrong. -
Limiting one appointment per user
I'm trying to make it so users are only able to schedule one appointment. Here I am modifying the save method. What I am trying to figure out is how to see if that user already has an appointment. def save(self, *args, **kwargs): if Appointment.objects.filter(owner=user_pk).exists() and not self.pk: # if you'll not check for self.pk # then error will also raised in update of exists model raise ValidationError('You have already scheduled an appointment.') return super(Appointment, self).save(*args, **kwargs) In my views.py I already have something that will raise an error if an appointment with that user already exists. But i'm thinking this is not enough and that there should be something at the model level. appointments = Appointment.objects.filter(owner=request.user) if appointments.exists(): raise PermissionDenied('You have already scheduled an appointment.') -
AttributeError: 'module' object has no attribute 'lru_cache' while installing Django 2
I'm using ubuntu and I got python 2.7 and python 3.4.3 installed on my OS. I'm trying to install Django 2 and it does not supports python 3, I get this error while trying to install it using pip install -U Django or pip install Django --upgrade: Traceback (most recent call last): File "", line 17, in File "/tmp/pip_build_alex/Django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 17, in File "/tmp/pip_build_alex/Django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' I've read this question and another one, only to see that answers are offering OP to install a lower version of django!, but that's not a real answer to such question. I tried alias python=python3 to set python 3 as default python but failed to get a working solution. How can I install Django 2 in a OS with 2 versions of python without getting this … -
Django - could not parse the remainder: '[loop.index] [duplicate]
This question already has an answer here: Django - iterate number in for loop of a template 2 answers Both name and data are lists being returned from a view template: {% for row in data %} <table class="table"> <tr> <td>{{% name[loop.index] %}}</td> </tr> {% for league in row %} <tr> <td>{{ league.name }}</td> </tr> {% endfor %} </table> {% endfor %} Exception: Django Version: 1.11.7 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '% name[loop.index] %' from '% name[loop.index] %' any help would be appreciated -
Exited with exit code 3 on running heroku local
I tried to use the heroku command line tool following the tutorial on https://devcenter.heroku.com/articles/heroku-local It exited with exit code 3. $ heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Starting gunicorn 19.4.5 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Listening at: http://0.0.0.0:5000 (13114) 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Using worker: sync 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13119] [INFO] Booting worker with pid: 13119 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13119] [ERROR] Exception in worker process: 01:53:43 web.1 | Traceback (most recent call last): 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker 01:53:43 web.1 | worker.init_process() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process 01:53:43 web.1 | self.load_wsgi() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi 01:53:43 web.1 | self.wsgi = self.app.wsgi() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi 01:53:43 web.1 | self.callable = self.load() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load 01:53:43 web.1 | return self.load_wsgiapp() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 01:53:43 web.1 | return util.import_app(self.app_uri) 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 366, in import_app 01:53:43 web.1 | __import__(module) 01:53:43 web.1 | File "/home/palak/python-getting-started/gettingstarted/wsgi.py", … -
Highcharts Data Parsing List of lists
I'm using Django and I am trying to parse the data I am putting into my template to load into high charts. This is the first I'm using High Charts and I was unable to locate a way of parsing it this way. Right now my data is presented like [["Date", "Product1", "Product2"],["Dec 28 2017", 2, 2], ["Dec 29 2017", 2, 2]] How do I make a column chart where the bars are under each day. Thanks -
Does Django automatically detect the end user's timezone?
I am building an application in Django which allows the end-user to retrieve information which is sensitive to the time of day (12 am to 12 am) on a given day. I store this information in my database as an integer representing the seconds since midnight in 30-minute increments. I was looking at Django's timezone documentation: https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/ and found myself confused on whether or Django automatically uses the end-users time, or if I must collect this information and account for it in my views. Any information would be helpful! Thanks. -
Get parameter value in template
I have such url pattern: url(r'^drinks/(?P<drink_name>\D+)/',TemplateView.as_view(template_name='drinks/index. html'),name="drink") How can I get access to drink_name parameter value in template. -
Django foreign key name on select
I'm working with 2 models each one in a different Django application: App products class Product(models.Model): name = models.CharField(max_length=256) price = models.FloatField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) def __unicode__(self): return self.name App warehouses class Warehouse(models.Model): name = models.CharField(max_length=256) def __unicode__(self): return self.name The probles is that in the admin site, when I want to create a product and I need to select a warehouse, in the select list I only see: Warehouse object Warehouse object Warehouse object What I have to do to see warehouse name? -
How To Upload Image From Admin Side In Pycharm (Django)
In Models.py, from django.db import models class Question(models.Model): question_text = models.CharField(max_length= 100) pub_date = models.DateTimeField('Date Is Published') image = models.ImageField(upload_to="Question_Image", blank=True) def __str__(self): return self.question_text class Choice(models.Model): choice_text = models.CharField(max_length= 200) votes = models.IntegerField(default= 0) question = models.ForeignKey(Question, on_delete= models.CASCADE) def __str__(self): return self.choice_text In settings.py, i added MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mysite/media') In mysite/urls.py, from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls', namespace= "polls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In index.html, {% extends 'polls/base.html' %} {% block main_content %} {% if latest_questions %} <ul> {% for question in latest_questions %} <li><a href={% url 'polls:detail' question.id %}> <b>{{question.question_text}}</b> <img src="{{question.question_text.image.url}}"> </a> </li> {% endfor %} </ul> {% else %} <p> You have no questions. Please add some.</p> {% endif %} {% endblock %} but there seems to be no uploading of image which was what i wanted to add to poll app created from 'my first django app' videos on youtube. Please help. -
google cloud sotrage download file with encoded path included
I am using Google Cloud Storage API to manage my files. and when I download a file from link created. it downloads path together like this. movie%2F316029%2Fko%2FThe.Passion.Of.the.Christ.2004.DVDRip.XviD.AC3.CD2-CiPA.smi instend The.Passion.Of.the.Christ.2004.DVDRip.XviD.AC3.CD2-CiPA.smi is there have a way that fixes or turn off encoding path problem? I am using python3.5.2 Django 2.0 with Google Cloud Library. -
How to set User in request.user in Django
How i can set my own user in request.user or request.session.user my own models: class User(Document): id = fields.IntField(primary_key=True) username = fields.StringField(required=True) email = fields.EmailField() .... @property def is_authenticated(self): return False I set this in my view user = User.objects.get(email=email) request.session.user = user but didn't work. -
Is it ok to use the anaconda distribution for web development?
I started learning Python working on projects involving data and following tutorials advising to install the anaconda bundle, to take advantage of the other libraries coming with it. So did I and I got confortable with it, I liked the way it manages environments. During the last months, I have been teaching myself web development with django, flask, continuing to use the anaconda python. But most of the time I install the dependencies I need with pip install though (inside the conda environment). I've never seen any tutorials or podcasts mentioning the conda environment as an option for developing web apps so I start to get worried. Is it for a good reason? Everywhere its the combination of pip and virtualenv that prevail. And virtualenv isn't compatible with anaconda that has its own env management system. My newbie question is: Will I run into problems later (dependencies management in production or deployment maybe?) using the anaconda distribution to develop my web apps? -
Django Email Confirmation activation view not working
I am trying to set up an email confirmation for my django application. This is the activation URL: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate'), and this is the activate view: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = get_user_model().objects.get(pk=uid) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.email_confirmed = True user.save() login(request, user) return redirect('profile') else: return render(request, 'email/invalid_token.html') This is the error I am getting: TypeError at /activate/MzQ/4se-cb054dd0a60fb9f85110/ activate() got an unexpected keyword argument 'uidb64' Any help would be appreciated. -
How to re-sort search results in-place without having to re-send a request in django?
Here is the scenario: I have a search page, with some form elements providing multiple filter conditions (something like 'advanced search'), and probably a nested ListView to display the search results in-place. What I would like to achieve: Whenever the user changes some filter conditions, the result list below responds in-place (taking another request for this could be accepted); When the user changes the sorting option, the results change their ordering immediately, without sending another request, either synchronous or by ajax. From the server side it would be as simple as changing the order_by attribute of a QuerySet, but I would like it in a front-end way. So I wonder if it is possible to achieve that. It seems to me that the filtered QuerySet could be somehow kept at the client side. Is it possible by pure Django using some mechanism like session? Or will it have to take some front-end frameworks such as AngularJS or Vue.js? Or is it not even possible (If so, is there any approach taking the minimal extra network payload?) -
Why does Django server crash in PyCharm professional?
I am working in PyCharm professional version and I am not able to run Django server from PyCharm, though I can start it from cmd. After starting the server from cmd, everything works fine, I can reach my urls and get a response. When I am trying to do the same from Pycharm, first I get a windows error ("Python has stopped working. A problem caused the program to stop working correctly. Please close the program.) When I click "Close the program", it does not close, and I can see the following in error in PyCharm: Process finished with exit code -1073741819 (0xC0000005) I am using the following versions: Python version: 3.6.1 Django version: 1.9.13 I have already tried Tools | Run manage.py Task | runserver , which gives the same result. I have found a way to make this error disappear in PyCharm: When I go to Run | Edit Configurations | and check "No reload", then the server starts normally and I can access it through the browser. Does anyone have a hint on why this is happening? What is the purpose of "No reload"? Thank you for the answer! -
no changes detected when running makemigrations
After dropping every single relation in my database, and deleting everything inside workoutcal/migrations, I tried to run python manage.py makemigrations. This is what happened: (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py makemigrations No changes detected How is this possible? The database is empty. There is nothing inside the migrations folder. Are there other things I should delete? -
Different behaviour of Django's django.utils.crypto.salted_hmac depending on uwsgi run manually or via service
Experiencing hard to understand for me behaviour. I feed salted_hmac function with predefined arguments - key_salt, value and without providing secret_key. When I run this via django command, I get some key inside salted_hmac function: key = hashlib.sha1(key_salt + secret).digest(). Same key I get, when running this from a django view run on runserver or from a the same django view while being run on uWSGI, which has been launched directly from terminal. On the other hand, when I run uWSGI via a service - the key in salted_hmac function differs. The only difference between those runs is a way it's run, I use exactly the same .ini file with uWSGI configuration. My guess would be that secret keys differ between running this function from terminal / from service, but when I print secret_key inside salted_hmac function - it's the same key... Moreover if I hardcode secret_key param when calling salted_hmac function - I get the same key generated in salted_hmac, regardless of it's run directly from terminal or from a view on uWSGI run from a service... -
after Model and many to many fields saved signal django
i have models like class Genre(models.Model): name = models.CharField(max_length=50) class Cast(models.Model): name = models.CharField(max_length=120, null=False, blank=False) class movie: name = models.CharField(max_length=120, null=False, blank=False) genre = models.ManyToManyField(Genre) cast = models.ManyToManyField(Cast, null=True, blank=True) i want to send notification to clients after a movie saved so i used post_save signal and because of my m2m relationships it didn't work and after that i used m2m_changed and now everytime i make a change on movie genres or movie cast they will be notified! i want them to be notified just for the first time the movie submits and i need the genres too! i mean the problem with the post_save signal was, it happens before genre and cast objects submit so i didn't have access to them -
Upload Percentage of AWS S3 file in django
I am uploading an whole folder using the following code: views.py: s3 = session.resource('s3') bucket = s3.Bucket('sudo-study-name') for subdir, dirs, files in os.walk(path): for file in files: full_path = os.path.join(subdir, file) with open(full_path, 'rb') as data: full_path = full_path.replace('\\','/') bucket.put_object(Key=full_path[len(path) + 1:], Body=data) print(full_path) Is it possible to know the amount of upload that has happened and show it in an progress bar on my html templates in Django project? Please note: This upload happens after a post. -
Django: Custom Metaclass Inheriting From And Extending `ModelBase`
I am trying to do some metaclass hocus-pocus. I want my own Metaclass to inherit from ModelBase and then I want to add additional logic by extending its __new__ method. However I think there is something strange happening with the MRO/inheritance order. Here is the basic situation: from django.db.models import Model, ModelBase class CustomMetaclass(ModelBase): def __new__(cls, name, bases, attrs): # As I am trying to extend `ModelBase`, I was expecting this # call to `super` to give me the return value from here: # https://github.com/django/django/blob/master/django/db/models/base.py#L300 # And that I would be able to access everyhing in `_meta` with # `clsobj._meta`. But actually this object is # `MyAbstractModel` and has no `_meta` property so I'm pretty # sure `__new__` isn't being called on `ModelBase` at all at # this point. clsobj = super().__new__(cls, name, bases, attrs) # Now, I want to have access to the _meta property setup by # ModelBase so I can dispatch on the data in there. For # example, let's do something with the field definitions. for field in clsobj._meta.get_fields(): do_stuff_with_fields() class MyAbstractModel(metaclass=CustomMetaclass): """This model is abstract because I only want the custom metaclass logic to apply to those models of my choosing and I don't want … -
Serve static HTML in Django
I’m pretty new to Django so forgive me if this is something I shouldn’t even consider, but I’d like my app to be able to link to a large number of static HTML pages (enough that creating URL paths to each one would be unreasonable) and there would constantly be more being uploaded (by me via FTP). I’ve got this working on the the development server by adding the path to those HTML files to my STATICFILES_DIRS [] but that doesn’t seem to work when I push my code to production. I tried setting up a STATIC_ROOT and running collectstatic but that didn’t help, and I’m also worried that even if I got that working, I would have to run collectstatic each time I uploaded new files. So my question is, is this even reasonable? Should I just avoid hosting these static HTML files alongside my project and leave them where they are now, on a separate server under a separate domain? The only reason I wanted to host them together initially is because along with the static HTML files, there is an SQL LITE database that my Django app displays data from (this is the whole purpose of my … -
You are trying to add a non-nullable field... when makemigrations
Here's what's happened: I created the following models: class Workout(models.Model): datetime = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) lifts = fields.LiftsField() cardio = JSONField() def __str__(self): return str(self.datetime)+" "+self.user.email __repr__ = __str__ class Activity(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name __repr__ = __str__ class CardioActivity(Activity): pass class LiftActivity(Activity): pass I ran makemigrations and migrate workoutcal/migrations/0002_activity_cardioactivity_liftactivity_workout.py - Create model Activity - Create model Workout - Create model CardioActivity - Create model LiftActivity 0002_activity_cardioactivity_liftactivity_workout.py class Migration(migrations.Migration): dependencies = [ ('workoutcal', '0001_initial'), ] operations = [ migrations.CreateModel( name='Activity', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Workout', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('datetime', models.DateTimeField()), ('lifts', workoutcal.fields.LiftsField()), ('cardio', django.contrib.postgres.fields.jsonb.JSONField()), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='CardioActivity', fields=[ ('activity_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='workoutcal.Activity')), ], bases=('workoutcal.activity',), ), migrations.CreateModel( name='LiftActivity', fields=[ ('activity_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='workoutcal.Activity')), ], bases=('workoutcal.activity',), ), ] Then I turned the Activity class into a meta class: class Activity(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name __repr__ = __str__ class Meta: abstract = True And tried to makemigrations again: (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py makemigrations You are trying to add a non-nullable field 'id' to cardioactivity without a default; we can't do … -
Django 1.11 static files not loading
<link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link href= "{% static 'css/grayscale.min.css' %}" rel="stylesheet"> Setting.py STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(file)) STATIC_ROOT = os.path.join(PROJECT_DIR,'static') TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) There are static files in my directory, I have tried every possible solution. -
How to prevent abstract model class from being included in migrations
I've made two very simple models with the help of an abstract model: class Activity(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name __repr__ = __str__ class CardioActivity(Activity): pass class LiftActivity(Activity): pass The Activity model is just an abstract model that is not intended to be used for anything, only to save me writing the same stuff twice. But when I makemigrations, it creates a database table for it: (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py makemigrations Migrations for 'workoutcal': workoutcal/migrations/0002_activity_cardioactivity_liftactivity_workout.py - Create model Activity ### HERE - Create model Workout - Create model CardioActivity - Create model LiftActivity It seems suboptimal to create a table that is never going to be used by me. Is there a standard way of preventing this from happening?