Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show differente QuerySet in a ModelMultipleChoice depending in previously selected option in another ModelMultipleChoice
Iḿ trying to build a simple Django webApp that stores documents in the server and it makes a relationship between the document and a project. Here are my models: class Project(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete='models.CASCADE', related_name='project_members') project_members = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=20, blank=False, null=False, unique=True) def __str__(self): return str(self.name) class Document(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) path = models.FileField(upload_to='documents/') name = models.CharField(max_length=50) folders = models.ManyToManyField(Folder) projects = models.ManyToManyField(Project) def __str__(self): return str(self.name) Here is the code of the form: class RemoveFileProject(forms.Form): project_name = forms.ModelMultipleChoiceField(queryset=Project.objects.none()) document_name = forms.ModelMultipleChoiceField(queryset=Document.objects.none(), widget=FilteredSelectMultiple("Documentos", is_stacked=False)) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(RemoveFileProject, self).__init__(*args, **kwargs) if user: proyectos = Project.objects.filter(project_members=user) print(proyectos) self.fields['project_name'] = forms.ModelMultipleChoiceField(queryset=proyectos) docs = Document.objects.filter(projects=proyectos).select_related() self.fields['document_name'] = forms.ModelMultipleChoiceField(queryset=docs, widget=FilteredSelectMultiple("Documentos", is_stacked=False)) Now I have 2 problems: I'm receiving a ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. I understand that this is because proyectos is a QuerySet and they behave in unique ways. I want to only show the documents that belong to each project, so If I choose the project "proyect 1", the second ModelMultipleChoiceFied should only display the documents that are related to "project 1". Thanks in Advance -
User uploaded list of IDs in django form
I have a model Member class Member(models.Model): mbr_id = models.BigIntegerField(primary_key=True) I would like to use a form so that the user can type in a list of IDs that the user wants to search for. Then my form view will query the database and then redirect to a new page called members.html that displays a table of the selected members. I can do the form posting, but I cannot figure out how to pass the list of members to the MemberListView so that it only displays the members in the user's list. -
Displaying Graph to the user
I want to show a graph(using matplotlib) to the user. In which Django diretory should I place my code? I tried placing the code in personal directory and defined the attribute in views.py, but not working. -
Custom queryset with 2 ForeignKeys to the same Object
I have a model that have 2 ForeignKeys to the same Model: class Note(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='sender_note', on_delete=models.CASCADE) receiver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='reciever_note', on_delete=models.CASCADE) status = models.BooleanField(blank=True, null=True) action = models.CharField(choices=NOTE_CHOICES, max_length=5, blank=True, null=True) There are situation, when the reciever an the sender are the same user, but in the majority of cases are different users. I created a custom queryset, where I use a RawQueryset: qs_str = 'SELECT N.id, N.status,N.action, U.email AS email FROM notes_note AS N LEFT JOIN users_user AS U on N.sender_id=U.id WHERE action IN %s AND status IS NOT TRUE AND U.is_staff=%s' qs = Note.objects.raw(qs_str, [action, user_is_staff]) I need to get: both receiver and sender (to get attributes from them especially email) check if sender is staff or not -
Django order by primary key does not work
I have a model as below: class Photos(models.Model): id = models.IntegerField(primary_key=True, default=1) name = models.CharField(max_length=500) size = models.IntegerField() path = models.CharField(max_length=500) date = models.DateField(default=datetime.now) def __str__(self): return self.date.strftime('%Y-%m-%d') class Meta: verbose_name_plural = "Photos" I want to retrieve the last primary key from the database (postgresql) as below: try: last_inserted = Photos.objects.order_by('-id')[0] print(last_inserted) except IndexError: print("No data in the database") but instead of a primary key I always get a date from the date column which is really strange! printing the last_inserted gives me '2018-09-04'. As a test I change the 'id' column to lang (does not exists in table) gives below error message: Cannot resolve keyword 'lang' into field. Choices are: date, id, name, path, size in the above message why date is coming first then id and so on ..! please help! -
New server Public IP for new instance
I am running a Django app with Nginx on Ubuntu. Just recently I was able to clone my instance image and add both instances to my Load Balancer. What I noticed was that in the Fabfile.py for both instances they share the same server public ip under 'hosts' and 'db'. Now I think that I should add my new IP addresses to this list. But what I am wondering is if there is anywhere else that I am missing out updating the servers IP addresses. -
Uploading images to mongodb using djongo with Django
I am using django 2.1 - mongodb v 4.0 for my project. I need to upload images, i use jdongo for conection. settings.py: INSTALLED_APPS = [ 'books', ...] DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'my_proj', } } STATIC_URL = '/static/' MEDIA_URL = '/books/static/media/images/' models.py: from django.db import models from django.urls import reverse # Create your models here. class Book(models.Model): name = models.CharField(max_length=200) pages = models.IntegerField() image = models.ImageField(upload_to ='my_proj/images',default = 'no-img.jpg') def __srt__(self): return self.name def fet_absolute_url(self): return reverse('book_edit',kwargs= {'pk':self.pk}) views.py: from django.http import HttpResponse from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from books.models import Book # Create your views here. class BookList(ListView): model = Book class BookView(DetailView): model = Book class BookCreate(CreateView): model = Book fields = ['name','pages','image'] success_url = reverse_lazy('book_list') class BookUpdate(UpdateView): model = Book fields = ['name','pages','image'] success_url = reverse_lazy('book_list') class BookDelete(DeleteView): model = Book success_url = reverse_lazy('book_list') And templates, book_list.html: {% for book in object_list %} <tr> <td>{{ book.name }}</td> <td>{{ book.pages }}</td> <td>{{ book.image }}</td> <td><a href="{% url "book_view" book.id %}">view</a></td> <td><a href="{% url "book_edit" book.id %}">edit</a></td> <td><a href="{% url "book_delete" book.id %}">delete</a></td> </tr> {% endfor %} book_detail.html: <h1>Book Details</h1> <h2>Nane: {{ object.name }}</h2> Pages: … -
Django template control flow?
How can I achieve something like this in django template ? django template pseudo code: {% for key, value in dictionary %} {% if key == 'some text' %} <a href ='url/value'></a> in python i would do the .format() thing and update string like this for key, val in dict: if key == 'some_key': 'this is the {}'.format(val) but how can I achieve this in template ? Thank you -
Django DateField with only month and year
I post this because I could not find an answer/example that satisfied me and I solved it a way I haven't read in there. Maybe it can be useful or can be discussed. Basically, my app displays formsets where users can create objects. Once validated, the formset is displayed again and user can add new objects. Specifying a day is not relevant. I first started to use some javascript to do it, then played with Django custom model (to subclass models.DateField). I could not succeed to do it with the later (my post updated linked to this one) As I have deadlines, I did it with simple ChoiceField storing objects as Integers and then, use a @property method to build a proper date out of those user inputs. This way I avoided to deep dive in Django steam pipes and even got rid of a datepicker! But thanks to the @property, I can still keep the convenience of formatting dates in Django templates and make date calculation etc... models.py : class MyModel(models.Model): YEAR_CHOICES = [(y,y) for y in range(1968, datetime.date.today().year+1)] MONTH_CHOICE = [(m,m) for m in range(1,13)] start_year = models.IntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year,) start_month = models.IntegerField(choices=MONTH_CHOICE, default=datetime.datetime.now().month,) end_year = models.IntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year,) end_month … -
Disable Sentry reporting when using djangos `manage.py shell` via heroku
I am using sentry to report errors ocurring in my django app that is hosted on heroku. Is there a way to disable sentry error reporting when using a command like heroku run python manage.py shell -
Email is None for some cases while using microsoft graph api
I know I can fetch the details using url GET https://graph.microsoft.com/v1.0/users/ . When I use my personal outlook mail, it actually says [{'displayName': 'vineeth sagar', 'surname': 'sagar', 'givenName': 'vineeth', 'userPrincipalName': 'MYACTUALEMAIL REMOVED FOR PRIVACY', 'businessPhones': [], 'jobTitle': None, 'mail': None, 'mobilePhone': None, 'officeLocation': None, 'preferredLanguage': None}] My email is indeed correct but why was it given in userPrinciplName. Also when trying to While I tried it with a couple of other accounts, which were actually registered with office 365(Mine was not),I get the mail with their actual email. Why is this not consistent? What mistake have I done? I registered my mobile number while registering my personal email. So why is my mobile field also None. I am using OAuth for the first time, but I know that there is nothing wrong with Oauth because every other functionality I want works(Like sending mails,fetching mails) etc. English is not my first language, so please forgive me if I have made some mistakes. If you want any clarifications please ask me. -
django custom authentication backend returns None
I am doing this web application in django where i have my custom user model (as I wanted the Email field to be required) as well as a custom user authentication backend. I have stored user passwords in plaintext as the authentication does not wholly depend on the user password but also on the one time password. The problem I am facing is with the custom user authentication backend. It is returning None every time. I have made necessary additions in the settings file. I am giving the necessary codes below. I'd be really thankful for the help! backends.py from django.contrib.auth import get_user_model User = get_user_model() class CustomAuth(object): def authenticate(self, email=None, reg_pass=None, otp=None, passed_password=None): if reg_pass and otp and passed_password: try: user = User.objects.get(username=email) pwd_should_be = [] for i in range(4): pwd_should_be.append((int(reg_pass[i]) + int(otp)) % 10) print("password should be------------", pwd_should_be) if pwd_should_be == passed_password: return user else: return "authenticate_fail" except User.DoesNotExist: return "None" def get_user(self, user_id): try: u=User.objects.get(pk=user_id) return u # return User.objects.get(pk=user_id) except User.DoesNotExist: return "None" views.py reg_pass = request.session['reg_pass'] otp = request.session['otp'] user = request.session['username'] email = request.session['email'] user = CustomAuth.authenticate(email, reg_pass, otp, passed_password) print("The user whi is trynna login is--------", user) if user is not None: return … -
serializer in Django how to substitute null with empty string ""
I have a model with ImageField type below: class Attendance(models.Model): face_image = models.ImageField(, blank=True, null=True, storage=MediaStorage()) A serializer that is based on the model class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields = ('id','face_image') However if the imagefield is null, it shows like this Its now showing like this in the json { "id": 1, "face_image": null } It will show an output for face_image (ImageField) as null if it is None. What I would like is to substitute null to be an empty string like this "" -
many to many relationship in django database model
we have three two tables and one intermediary table as shown in below diagram below is the code we are using to create models class Roles(models.Model): """ A class that stores all the types of roles that are available to the user """ role_id = models.CharField(max_length=200, blank=False,primary_key=True) role_name = models.CharField(max_length=200) class Meta: db_table = 'roles' managed = False class User(AbstractBaseUser): # class ChannelUser(models.Model): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. """ user_id = models.CharField(max_length=200, blank=False,primary_key=True) user_email = models.EmailField(max_length=200, blank=False, unique=True) roles=models.ManyToManyField( Roles, through='UserRole', # through_fields=('user_id', 'role_id'), ) USERNAME_FIELD = 'user_email' class Meta: db_table = 'user' managed = False class UserRole(models.Model): """ A class that stores user ids and role ids """ user = models.ForeignKey(User, on_delete=models.PROTECT, db_column='user_id') role = models.ForeignKey(Roles, on_delete=models.PROTECT, db_column='role_id') timestamp = models.DateTimeField(default=timezone.now) class Meta: db_table = 'user_roles' managed = False We are trying to fetch all the Roles associated with User, but it gives None for roles. I am not sure, what we are doing wrong here. can somebody please point it out. -
Django -Help displaying content in nested for loop
I have a Requisition which may have multiple lines. So to implement this I included a unique_together constraint on two fields on the RequisitionLine model which one of the fields is a FK to Requisition . So naturally to pull all the lines of a requisition I would query the RequisitionLine table where the FK = the id of the Requisition model, then iterate over all the sequences to grab all the lines. My goal is to display the header number with the lines of that requisition under the header in the template but am struggling to accomplish this. I have tried to iterate over the queryset but the code i am posting below is my most recent attempt trying pass lists to the template which is also not working. Right now each header is showing all the lines. Any help would be appreciated. Models.py class Requisition(models.Model): username = models.ForeignKey( 'users.CustomUser', on_delete=models.CASCADE, related_name='req_user') signature = models.CharField(max_length=10, blank=True, null=True) class RequisitionLine(models.Model): parent_req = models.ForeignKey('Requisition', on_delete=models.CASCADE, related_name='par_req_line' ) sequence = models.PositiveIntegerField() item_code = models.ForeignKey( 'items.ItemMaster', on_delete=models.CASCADE, related_name='req_item', blank=True, null=True) description = models.CharField(max_length=50, blank=True) extra_information = models.TextField(blank=True) quantity = models.PositiveIntegerField(blank=True, default=0,null=True) price = models.DecimalField(max_digits=19, decimal_places=2, blank=True, default=0.00,null=True) purchase_order = models.CharField(max_length=9, blank=True,null=True) po_line = … -
Could not install packages due to an EnvironmentError: [Errno 13] Permission denied
I am trying to install django-widget-tweaks but I am getting this error; Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/widget_tweaks' Consider using the --user option or check the permissions. This is the free account at the moment. Is it because the account type or I am missing something else? Besides this, I have completed the installation with Python3.7 but this error shows that it tries to use Python2.7. Why is that so? -
How to import from project level package in Django without conflicting with app level module with same name?
I have a Django project with the following structure: mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py utils.py utils/ __init__.py filters.py In my utils/filters.py file I have a class MyFilter. From polls/admin.py, however, when I try to run from utils.filters import MyFilter, I get ImportError: No module named filters. How can I import my custom filter inside the polls app without renaming the polls/utils.py module or the utils package? -
Django: filter queryset by multiple ID
My query is quite simple, I have a model Vendor in my Django REST app. What I want is to use a get response with a few ID and get back all the respective models with these ID. The GET url pattern could be something like this: r'^api/vendors?id=1,2,3'. What I'm thinking of right now is to use ListAPIView, and in the list method filter my queryset with all the id in the url. But I'm not sure exactly how to achieve this (filtering queryset with a list of id, I'm very new to both Python and Django), so if anyone can provide any advice on this it would be greatly appreciated. -
extends: conditional templates in django
Is it possible to have a conditional extends? Like I have is: {% extends "main/base.html" %} {% load custom_tags %} {% load static %} but I want the template main/base to be conditional like: {% if request.path == '/page/lawyer/' %} {% extends "base_lawyer.html" %} {% else %} {% extends "base.html" %} {% endif %} -
django fill form field automatically from context data
I have a form attached to a DetailedView and its working fine when saved. I would like the form field(position) to be prepopulated with the value coming from the slug of the detailed view(e.g jobs/human-resource-manager). The Model of the form field has a Foreignkey to the JobPost model. Need help. Part of my view looks like this class JobsDetailView(DetailView): model = JobPost template_name = 'job_post-detail.html' def get_context_data(self, **kwargs): context = super(JobsDetailView, self).get_context_data(**kwargs) context['position'] = JobPost.objects.order_by('position') context['job_app_form'] = JobsForm() return context foms.py from django import forms from job_post.models import JobsApplied class JobsForm(forms.ModelForm): class Meta: model = JobsApplied fields = '__all__' def form_valid(self, form): form.instance.customuser = self.request.user return super().form_valid(form) -
How to use django-summernote in templates
I have setup django-summernote on my project and everything is great, it works very good on admin , but i want to use it on my templates. Note : in django-summernote documentation they only explain how to use it if you have forms.py file but I dont my main urls.py : urlpatterns = [ path('games/', include('core.urls', namespace='core')), path('summernote/', include('django_summernote.urls')), ] my app(name=core) urls.py : from django.urls import path from . import views app_name = 'core' urlpatterns = [ path('new/', views.GameCreate.as_view(), name='game_new'), path('<int:pk>/edit/', views.GameUpdate.as_view(), name='game_edit'), ] my views.py : class GameCreate(LoginRequiredMixin, CreateView): model = Game template_name = 'core/game_new.html' fields = '__all__' redirect_field_name = 'home' class GameUpdate(LoginRequiredMixin, UpdateView): model = Game template_name = 'core/game_edit.html' fields = '__all__' my template file "game_new.html" : {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %} Add New Game {% endblock %} {% block main %} <section class="main-section"> <div class="container"> <h1>New Game</h1> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input type='submit' value="Save" /> </form> </div> </section> {% endblock %} my template file "game_edit.html": {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %} Game Info {% endblock %} {% block main %} <section class="main-section"></section> <div class="container"> <h1>Edit Game Info</h1> … -
How to upload list of files contained in a folder (updated)?
I know how to upload file basically when serve a view to post files to upload. My task is that to upload files dynamically and empty folder when upload finish. Maybe with middleware, or celery task, i dont know... This files contains is use to populate my database. And i want to check update after with the reference of files uploaded. Take and look wath i want to do: That's my models.py: from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) I have folder in my project directory Example: MyDjangoProject: | | | MydjangoAPP: | | Myfolder: | | file1.txt filen.txt I need a help I use python 3.6 and django 2.1 -
How does Django add these attributes: ( tag, choice_label and id_for_label ) in RadioSelect's radio
In the documentation, I saw codes like this: {% for radio in myform.beatles %} <label for="{{ radio.id_for_label }}"> {{ radio.choice_label }} <span class="radio">{{ radio.tag }}</span> </label> {% endfor %} picture But I can't find related definition for these attributes in the source code. Thanks for your help : ) -
django-pyodbc-azure 2.1.0.0 not supporting Django 2.1.0
We are trying to connect Django-2.1 with MS SQL Server 2012. We were looking for modules to use for this and stumbled across django-pyodbc-azure. We pip installed it and while restarting the app, we got this following error message: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000006140CB2BF8> Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\core\management\comma nds\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Program Files\Python36\lib\site-packages\django\core\management\__ini t__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24 , in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", li ne 112, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in impor t_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\models.p y", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Program Files\Python36\lib\site-packages\django\contrib\auth\base_use r.py", line 47, … -
Django: "argument of type 'int' is not iterable" in oracle/base.py in _rowfactory
I'm trying to connect my Django app to Oracle DB but making a query results in exception: TypeError: argument of type 'int' is not iterable Exception Location: /opt/isep/venv/lib/python3.4/site-packages/django/db/backends/oracle/base.py in _rowfactory, line 560 def _rowfactory(row, cursor): # Cast numeric values as the appropriate Python type based upon the # cursor description, and convert strings to unicode. casted = [] for value, desc in zip(row, cursor.description): if value is not None and desc[1] is Database.NUMBER: precision = desc[4] or 0 scale = desc[5] or 0 if scale == -127: if precision == 0: # NUMBER column: decimal-precision floating point # This will normally be an integer from a sequence, # but it could be a decimal value. if '.' in value: value = decimal.Decimal(value) else: value = int(value) else: # FLOAT column: binary-precision floating point. # This comes from FloatField columns. value = float(value) elif precision > 0: # NUMBER(p,s) column: decimal-precision fixed point. # This comes from IntField and DecimalField columns. if scale == 0: value = int(value) else: value = decimal.Decimal(value) elif '.' in value: # No type information. This normally comes from a # mathematical expression in the SELECT list. Guess int # or Decimal based on whether it …