Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tagging a friend in Django
Trying to build a tagging system in django, where upon writing a friend's name in a post or a comment, a notification would be generated. Friendship and notification systems are already in place and working. Any ideas how to start. -
url resolvers inside if statements Django
Just wondering what the correct syntax is for checking if the current path is equal to some url: {% if request.path == url "app_namespace:route_name" %} Above doesn't work - but hoping someone knows a way or method for doing this lookup... -
Django-2.0 app can't find PostgreSQL database
I would like to use a PostgreSQL database in my Django application, but unfortunately I'm running into some difficulties. When running python3 manage.py makemigrations, the result is: django.db.utils.OperationalError: FATAL: database "/var/lib/postgresql/10/main/djangopgsql" does not exist After reentering the postgre shell, I tried to create the database djangopgsql, but the return was ERROR: database "djangopgsql" already exists In my settings.py file, I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'djangopgsql', 'USER': 'djangopgsqluser', 'PASSWORD': '*************', 'HOST': 'localhost', 'PORT': '', } } In the postgres shell, I ran show data_directory, which returned: /var/lib/postgresql/10/main I tried entering this address in with the NAME in DATABASES above to no avail. -
Django Rest Framework Filtering Not working
I want to return Videos where is_thumbnail=True on a GET call. However, all of my testing with filters have been returning all Videos objects. Model: class Videos(models.Model): """This class represents the Videos model.""" uid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) is_thumbnail = models.BooleanField(default=False) file_name = models.CharField(unique=True, max_length=64) file_path = models.CharField(unique=True, max_length=256) file_created_time = models.DateTimeField() owner = models.ForeignKey('auth.User', related_name='videos', on_delete=models.CASCADE) created_time = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.file_name) view: class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This class handles the http GET, PUT and DELETE requests.""" serializer_class = VideosSerializer permission_classes = (permissions.IsAuthenticated, IsOwner) lookup_field = 'uid' def get_queryset(self): return Videos.objects.filter(is_thumbnail=True) -
Django - Issue with wrong query string in model filter
I need to run query in my view.py My current code is as follows : q = Owner.objects.filter(name__contains='Maximus') this code is working fine. I have to prepare query string name__contains='Maximus' based on multiple columns values. For that I am preparing a queryString but this is throwing error. queryString = "" queryString += "name__contains="+"'"+ownerName+"'" This query string when I put in filter q = Owner.objects.filter(queryString) [and in debug its value is like 'name__contains=\'Maximus\''] this is not working. Please suggest how to resolve it. -
django-two-factor-auth can't access admin site
I am using django-two-factor-auth for a webapp. I cannot access the admin page. I know I am entering the correct credentials. When I input incorrect credentials, I get an appropriate error message. When I input the correct credentials, the page simply reloads with this URL: http://localhost:8080/account/login/?next=/inveskore/ These are my settings related to two_factor: LOGIN_URL = 'two_factor:login' LOGIN_REDIRECT_URL = '/inveskore' TWO_FACTOR_SMS_GATEWAY = 'two_factor.gateways.twilio.gateway.Twilio' This is the associated URL path: path('admin/', admin.site.urls), According to this, it results from the admin user not having 2FA set. So, how do you set 2FA for the admin user if you can't access the site? -
invalid django form makes is_valid method always return false
My django form is invalid and so the .is_valid method never returns true. As a result, I am getting an "Expected HttpResponse but received None" type of error because my code never executes what is within the if-condition. I am wondering how to make my form valid. I am new to django so I am probably missing something obvious. Here is my code: views.py template_name1 = 'multiplication/detail.html' template_name2 = 'multiplication/multiplied.html' class myForm(forms.Form): quantity1 = forms.IntegerField(required=False) quantity2 = forms.IntegerField(required=False) form = myForm() def get(request): return render(request,template_name1,{'form': form} ) def multiply_two_integers(x,y): return x*y def post(request): if (form.is_valid()): x = request.POST.get('quantity1') y = request.POST.get('quantity2') product = multiply_two_integers(x, y) return render(request, template_name2, {'form': form, 'product': product }) template_name1 <h1>Multiplication Function</h1> <form action = "{% url 'multiplication:post' %}" method = "post"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value ="Multiply"> <!--<button type="submit"> Multiply </button>--> <h1>{{product}}</h1> </form> template_name2 <h1>{{product}}</h1> urls/multiplication from django.urls import path from multiplication import views app_name = 'multiplication' urlpatterns = [ # /multiplication/ path('', views.get, name = 'get'), path('multiplied', views.post, name='post') ] -
How to change value of choice field in Django shell?
I have started django in about a month ago and I am having problem in it. I had created a model which is one to one linked with User model This is my models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) options = (('individual','Individual'), ('institute',"An institute"), ) userAs = models.CharField(max_length=100,choices=options) def __str__(self): return self.user.username class Meta: ordering = ["user"] @receiver(post_save,sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserInfo.objects.create(user=instance) and I want to change value of userAs from shell and I am unable to do it. This is what I tried: In [10]: us = User.objects.get(username="foo") In [11]: us.userinfo.userAs Out[11]: 'individual' In [12]: type(us.userinfo.userAs) Out[12]: str In [13]: us.userinfo.userAs = 'institute' In [14]: us.save() In [15]: us.userinfo.userAs Out[15]: 'institute' In [16]: us = User.objects.get(username="steve04") In [17]: us.userinfo.userAs Out[17]: 'individual' but I am unable to change it. Thank you so so much for your help. -
How to get currently selected choice from CharField in Django?
I'm trying to get the currently selected choice from the CharField and use it in str method like this: class Foo(models.Model): measurement_value = models.FloatField(max_length=200) CHOICES = (('a', 'Alpha'), ('b', 'Beta')) choice = models.CharField(max_length=5, choices=CHOICES, default='a') def __str__(self): """String representation for the foo object.""" return str(self.measurement_value) + " " + self.choice -
django Wagtail embed-videos not showing up
I am trying to make a page filled with thumbnails, and every thumbnail redirects you a page with videos added by the client himself. My models.py page : class HomePage(Page): body = RichTextField(blank=True) main_vid = EmbedVideoField( verbose_name="Video", null=True, blank=True, ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), FieldPanel('main_vid'), ] class HomePageGallery(Page): vid_image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True ) content_panels = Page.content_panels + [ ImageChooserPanel('vid_image'), InlinePanel('video', label='video'), ] class VideoBasedModel(models.Model): page = ParentalKey(HomePageGallery, on_delete=models.PROTECT, related_name='video') video = EmbedVideoField( verbose_name="Video", null=True, blank=True, ) I have a HomePageGallery page, which works fine, but when I click on it, the videos I added don't show up. My home_page_gallery.html {% extends "base.html" %} {% load static wagtailcore_tags wagtailimages_tags embed_video_tags %} <link rel="stylesheet" href="{% static 'home/css/main.css' %}"> {% block title %}Ion Matei | Servicii Photo, Video{% endblock %} {% block content %} <div class="lists"> {% for vid in self.video.all %} <div class="welcome-video"> {% video vid '800x600' %} </div> {% endfor %} </div> {% endblock %} -
How do I know I'm using the sublime text 3 virtualenv for Django development?
Up to this point, I've been using text editor and the terminal in Linux mint to edit and run my Django-2.0 code, but I'd like to switch to using Sublime Text 3 instead (is this advisable?). I have a virtualenv already setup from the terminal previously, and would like to use this, as it has a number of packages already installed. In attempt to get things set up, I installed the virtualenv package through sublime, then I enabled the build system (Python + Virtualenv through the Tools -> Build System menu), set the address of the already created environment folder with Virtualenv: Add directory and executed with Ctrl+B. I'm not sure how to tell whether I'm successfully using the virtualenv though. How can I check this/what am I missing? -
Django - Creating links to files outside of App and on a different drive
I'm creating a menu of file links that reside outside the app and on a different shared drive. I do not want to re-upload the files using Django. I want to keep accessing the files in the shared drive. I'm new to Django and development, so I don't know how to tell Django to access the shared drive for a particular file. These are my questions: Do I need to set something up in the STATIC ROOT and STATIC URL even if I'm not planning to upload any files through my app? I just want to create a link in my template and for the file to open up when the user clicks on it. What syntax should I use to access another drive? If you could write it or send me a link to a piece of documentation that covers this subject, I would greatly appreciate it. I've been looking for information on this, but haven't found a clear answer. -
Django ModelForm with ManyToManyField showing all possible objects
I need your help with this. I tried to find the solution for a couple of days, but no luck so far. Here is the set up: There can be several projects, tasks and people can be assigned to projects, a person can be assigned to several tasks, and the same task can be assigned to different people. No problems so far... When I try to show a form for a specific task (which is assigned to 1 project), it shows all people from all projects, but I need to see people only from the project associated with the selected task. Thank you very much in advance! class Project(models.Model): project_name = models.CharField(max_length=50) def __str__(self): return self.project_name class Person(models.Model): person_name = models.CharField('Person Name',max_length=50) project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.person_name class Task(models.Model): task_name = models.CharField('Task Name',max_length=50) project = models.ForeignKey(Project, on_delete=models.CASCADE) people = models.ManyToManyField(Person) def __str__(self): return self.task_name class TaskForm(forms.ModelForm): class Meta: model = Task fields = ('task_name','people',) -
Using filters on Django 2.0
Please help to find the reason of error. Have two objects which ones returning from my view : def managment_users_form(request): users = User.objects.all() usersinfo = usersinfo_model.objects.all() count_objects = users.count() if request.user.is_authenticated: username = request.user.username context = { 'users': users, 'usersinfo': usersinfo, 'count_objects': count_objects, } return render(request, 'users.html', context) else: return redirect('login_form') And on my template I want to make for cycle from first one and filter by id in cycle another one. First is working well, but second one I'm getting error when try to use filter. Teamplate {% for user in users %} <div class=""> <h4 class="m-b-5">{{ user.first_name }} {{ user.last_name }}</h4> <p class="text-muted">{{ useremp|user_info_filter:user.id }} <span></p> </div> {% endfor %} filter from django import template register = template.Library() @register.filter(name='user_info_filter') def user_info_filter(useremp, id): return useremp.filter(user_id=id) Please help to understand the mistake. Error is : "Invalid filter: 'user_info_filter'" -
How to return 400 error for unique_together constraint violation?
I am using Django-Rest-Framework and have a model with the following constraint: unique_together = ("title", "owner") When that error is encountered the server sends a 500 response to the client, but I want to return a 400 error and detail of the constraint, so I can show it to the user. Here is the serializer code: def create(self, validated_data): title = validated_data.pop('title') try: poll = Poll.objects.create(title=title, slug=slugify(title), **validated_data) p = Poll.objects.get(id=poll.id) [p.tags.add(tag) for tag in validated_data['tags']] return poll Is it possible to raise the error there? -
django-admin.py not running
I'll add another django-admin.py question, as none of the other questions seem to cover my issue: I've installed django via pip: $ pip install django My pip and Python versions are: $ pip -V pip 9.0.1 from /usr/lib/python2.7/dist-packages (python 2.7) Specifically, python is version 2.7.14. At this point I expected to run $ django-admin startproject myTestProject which would then create my project folders in the current directory. However, this returns Cannot find installed version of python-django or python3-django This confuses me, since when I ran $ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin Further, I checked where the file django-admin.py is located: $ find -iname "django-admin.py" ./.local/bin/django-admin.py ./.local/lib/python2.7/site-packages/django/bin/django-admin.py So it seems like django-admin.py is in my PATH. Why then can I not run it? (extra info: I do have python 3.6.3 installed, too. But I don't think this version has anything to do with pip or django.) -
Good practice for doing a Django media backup
Is there any good practice for doing a Django media backup? I know there are tools like https://github.com/django-dbbackup/django-dbbackup but I can't make it work with management.call_command("mediabackup") when using options, I want to specify the generated tar file name, so I can upload it to a remote storage. I actually opened an issue about that https://github.com/django-dbbackup/django-dbbackup/issues/278 So, I'm looking for a way of doing my own backup. It looks like making a compressed version of the media folder is just what's necessary, but I'm not sure (mediarestore seems to to some stuff on the background) so I'm looking for good practices or example. -
Strange behavior of super() in Django Model
I use django 1.8.8, django-rest-framework 3.3.0 and python 2.7.12 on ubuntu gnome 16.04. I have a django model MyModel. In that model I override the save method in the following way: def save(*args, **kwargs): ... super(MyModel, self).save(*args, **kwargs) ... The problem that I found is that sometimes super is called as a usual function and after its call the next line is executed. But sometimes it is call itself recursively and we go to the first line of the function. When it is called from unit tests as self.client.post(...) the behavior is recursive. When it is called from unit tests as MyModel.save() the behavoiur is normal. Also I found that when it is called from client there are empty args and kwargs. But when it is called as MyModel.save() there are the following kwargs: kwargs = {'using': 'default', 'force_insert': True} I modified my code: def save(*args, **kwargs): ... kwargs.update({'using': 'default', 'force_insert': True}) super(MyModel, self).save(*args, **kwargs) ... But this don't change the recursive behavior. It would be great if someone tell me how to fix that. -
Correct setup of django redis celery and celery beats
I have being trying to setup django + celery + redis + celery_beats but it is giving me trouble. The documentation is quite straightforward, but when I run the scripts, nothing logs to any terminal, as if no tasks where being run. I have only one task, all that it does is printing and logging something. This is my folder structure: - aenima - criptoball - celery_aenima - __init__.py - celery_setup.py - tasks.py celery_setup.py looks like this: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aenima.settings') app = Celery('criptoball.celery_aenima') app.conf.broker_url = 'redis://localhost:6379/0' # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() app.conf.timezone = 'UTC' @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and tasks.py looks like this: from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta from criptoball.celery_aenima.celery_setup import app import logging from django_celery_beat.models import PeriodicTask, IntervalSchedule cada_10_seg = IntervalSchedule.objects.create(every=10, period=IntervalSchedule.SECONDS) actualizar_candles = PeriodicTask.objects.create(interval=cada_10_seg, name='actualizar_candles', task='celery_aenima.tasks.actualizar_candles', expires=datetime.utcnow()+timedelta(seconds=30)) @app.task def actualize_candles(x, … -
Django Rest Framework - self.request.user in model method
I have a model: User is the django User model from django.contrib.auth.models # drink/models.py class Drink(models.Model): name = models.CharField(max_length=32) bartender = models.ForeignKey('bartender.Bartender') # bartender/models.py class Bartender(models.Model): name = models.CharField(max_length=64) owner = models.ForeignKey(User) # property/models.py class Rating(models.Model): bartender = models.ForeignKey('bartender.Bartender') owner = models.ForeignKey(User) I use django rest framework and would like a serializer Field as such: # bartender/serializers.py class BartenderSerializer(serializers.ModelSerializer): rating = serializers.IntegerField(source='get_rating', read_only=True) class Meta: model = Bartender fields = [] My Viewset is class BartenderViewset(viewsets.ModelViewSet): queryset = Bartender.objects.all() serializer_class = BartenderSerializer how do I add a model method to my Bartender model, such that it returns the Rating object for whatever User is making the call. I tried this modification to my Bartender class: # bartender/models.py class Bartender(models.Model): name = models.CharField(max_length=64) owner = models.ForeignKey(User) def get_rating(self): return Rating.objects.get(bartender=self.id, owner=self.request.user) However self has no request. Therefore, I would like to know how to implement this so it is callable via drf viewsets. -
Django. Get field and subtract automatically
I want to realize something that looks like a client balance field. So: class Product(models.Model): name = models.CharField(max_length) price = models.PositiveIntegerField() class Client(models.Model): name = models.CharField(max_length) balance = models.DecimalField() class Order(models.Model): client = models.ForeignKey(Client) product = models.ForeignKey(Product) price = models.ForeignKey(Product) model is above i need to write query that takes orders total price and subtract from client balance field automatically.Is it possible? Thnaks -
python convert timezone issue
I have Jalaali date and time as Iran timezone,what I want to do is convert them to Gregorian date and UTC time respectively and separately and then create a Django datetime object to save it in my model ,everything works fine but when I try to save it , it saves previous value for them (before converting with astimezone), but if remove the tzinfo from datetime object the save problem goes away this is my code: import datetime import pytz gregorian_dict = {'gy':2018,'gm':2,'gd':3} time_list = [9,0,0] gregorian_date_iran_time = pytz.timezone('Iran').localize(datetime.datetime(gregorian_dict['gy'], gregorian_dict['gm'], gregorian_dict['gd'],time_list[0],time_list[1],time_list[2])) gregorian_date_utc_time = gregorian_date_iran_time.astimezone(pytz.utc) so far everything is Okey and the output is desired, but when i try to save it the value for gregorian_date_iran_time is save instead eventhough the prints is desired values suggestion = Suggest() suggestion.request = online_request suggestion.teacher = teacher suggestion.session_length = length print(gregorian_date_utc_time) # 2018-02-03 05:30:00+00:00 suggestion.date = gregorian_date_utc_time print(suggestion.date) # 2018-02-03 05:30:00+00:00 suggestion.save() but when i do this,i get correct result after save gregorian_date_utc_time = gregorian_date_utc_time.replace(tzinfo=None) I dont know if I am making a dumy mistake or forget something what is the solution for this? -
How do I test logging in using Django Rest + JWT
question here. I'm having trouble testing my login feature using DRF + JWT. It all works OK outside of test environment, I can login as an admin using exact same method and I get my token back. from django.test import TestCase from django.contrib.auth.models import User from rest_framework.test import RequestsClient TEST_USER = { 'username': 'test1', 'email': 'test@test.com', 'password': 'qwe123qwe', } BASE_URL = 'http://testserver/' API_LOGIN = 'http://testserver/' + 'api-token-auth/' class TestAuthentication(TestCase): def setUp(self): User.objects.create(**TEST_USER) self.requests = RequestsClient() def test_user_can_login(self): user = User.objects.first() self.assertEqual(User.objects.count(), 1) response = self.requests.post(API_LOGIN, TEST_USER) print(response.content) the output is: b'{"non_field_errors":["Unable to log in with provided credentials."]}' .. ---------------------------------------------------------------------- Ran 2 tests in 0.018s I would really like to include login/logout in my tests as it is base of my project. If I can provide any more information that would help you help me please comment, I will be watching this thread until it is solved, I have nothing better to do :) -
any idea on how to resolve this PYTHONHOME
```Could not find platform independent libraries Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' Current thread 0x00007fe39e395700 (most recent call first): ``` -
Django: How to filter related objects based on different criteria?
I'm working on a 'workflow management website' where different workflows with different steps can be tracked. A workflow is defined by a number of steps with a given order. A 'Job' realizes the workflow and 'Tasks' realize the steps. class Workflow(models.Model): name = models.CharField(_('Name'),max_length = 100, unique = True) class Step(models.Model): workflow = models.ForeignKey( Workflow, on_delete=models.CASCADE, ) name = models.CharField(_('Name'), max_length = 100) order = models.SmallIntegerField(_('Reihenfolge')) class Job(models.Model): workflow = models.ForeignKey( Workflow, on_delete=models.CASCADE, ) def current_task(self): # first task without finished date my_tasks = self.task_set\ .filter(finished__isnull=True)\ .order_by('step__order') if my_tasks.exists(): return my_tasks.first() return False class Task(models.Model): job = models.ForeignKey( Job, on_delete=models.CASCADE, ) step = models.ForeignKey( 'Step', on_delete=models.CASCADE, ) assigned_to = models.ForeignKey( User, on_delete=models.CASCADE, ) The current task of a workflow is the 'first' task without a 'finished' date (ordering is given by task.step.order). If there is no such task, the job is finished. My question is how to filter current tasks for a number of jobs. For example I want to filter Jobs where the current task is assigned_to some user. So far I used a for-loop and checked job.current_task().assigned_to for each job, but this obviously is a pretty slow/dumb way of doing that. Is there a more efficient way? I …