Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File upload doesn't terminate in Safari
I'm running a test server under the latest Django 2 release (Python3.6) on Mac OS X. My applications seem to work well across both Safari 11.0.2 and Chrome (build 63) except for one anoying detail. I've got this file upload form: class BulkForm(AssemblyForm): # AssemblyForm itself defines a Char field. file = forms.FileField(required=True, label='Input file') That is handled by the following view (I've reduced it to the bare minimum for this example): def formtest(request): if request.method == 'POST': form = BulkForm(request.POST, request.FILES) if form.is_valid(): upload = request.FILES['file'] return HttpResponseRedirect(reverse('submissions')) bulk = BulkForm() return render(request, 'upload.html', {'bulk_form': bulk}) And the template: ... <div class="tab-pane fade" id="bulk"> <div class="container my-4"> <form role="form" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ bulk_form.as_p }} <button type="submit" name="bulk-form" class="btn btn-primary bg-dark"> Submit </button> </form> </div> ... In Safari the upload sometimes freezes even when I try the same file: sometimes it uploads successfully, sometimes it freezes. There is a correlation between file size and its chances to get stuck. To investigate this issue, I've implemented my own upload handler: class SizeLimitedUploadedFile(uploadedfile.UploadedFile): def __init__(self, name, content_type, size, charset, content_type_extra=None): file = tempfile.NamedTemporaryFile( buffering=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, delete=False, suffix=f'.upload.{name.split(".", 1)[1]}', dir=settings.FILE_UPLOAD_TEMP_DIR ) super().__init__(file, file.name, content_type, 0, charset, content_type_extra) self.error = None def … -
Django - Modifying string representation of User object globally (outside of admin, even) for use in Model Forms
My website has many ModelForms and whenever it has a Foreign Key property to the User model, the property displayed is username. How can I change that so that the representation is, instead, the user's full name (or something else)? I am preferably looking for a global solution, which will work for all model forms from here on, but I am not discarding a fix that involves customizing each form (rather than changing the model). I am working with a userprofile extension of the user model. The fix that I've tried so far is supplanting the str method in the user class. This is the snipped I have on the model class (taken from an entry of this forum, btw). This code is in the models.py file: #CUSTOMIZES REPRESENTATION OF USER def get_full_name(self): return self.first_name + ' ' + self.last_name User.add_to_class("__str__", get_full_name) Thank you! -
customizing mezzanine admin menu
I would like to make a Page type show in the left hand menu instead of the dropdown in pages. -
How do i put the django-mptt in nested dropdown
Hello guys I am really thinking hard on this one I need help. How do I put the django-mptt in a nested dropdown. the recursetree tag when I put it in a bootstrap dropdown it comes out all jumbled up. {% load mptt_tags %} <ul> {% recursetree category_list %} <li> {{ node.name}}</a> {% if not node.is_leaf_node %} <ul class="children"> <a href="{% url 'category_detail' id=node.id %}"> {{ children | lower}}</a> </ul> {% endif %} </li> {% endrecursetree %} </ul> -
Python by Example Book: url_patterns syntax deprecated
In setting up Login and Logout url patterns, the book (which I believe uses Django 1.8) cites: from django.conf.urls import url from . import views url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'), url(r'^logout-then-login/$','django.contrib.auth.views.logout_then_login',name='logout_then_login'), where login, logout and logout_then_login have corresponding .html files in the same app template/account directory. However, on Django 1.11, these give errors of: "TypeError: view must be a callable or a list/tuple in the case of include()" which I believe is because this syntax is now deprecated for 1.10 and above). Tried: from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views url(r'^login/$', auth_views.LoginView.as_view(template_name='registration/login.html')), url(r'^logout/$', auth_views.LogoutView.as_view(template_name='registration/logged_out.html')), url(r'^logout-then-login/$', auth_views.LogoutThenLogin.as_view(template_name='logout_then_login.html')), instead, but now getting "no reverse match" errors in my main "base.html" code, at the: <a href="{% url "login" %}">Log-in</a> line in: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">Bookmarks</span> {% if request.user.is_authenticated %} <ul class="menu"> <li {% if section == "dashboard" %}class="selected"{% endif %}><a href="{% url "dashboard" %}">My dashboard</a></li> <li {% if section == "images" %}class="selected"{% endif %}><a href="#">Images</a></li> <li {% if section == "people" %}class="selected"{% endif %}><a href="#">People</a></li> </ul> {% endif %} <span class="user"> {% if … -
formset invalid django test
Can't understand what I'm doing wrong here and would appreciate some insight. been trying to figure it for a couple hours now. Test is simple. Just want to validate a formset. The form is invalid and shows errors for two of the attributes as per below. 1) 'account' is a foreignkey to another model. i have tried changing the values to match the PK for each account, i've tried changing the key to 'account_id', thinking i might have the wrong attribute. can't seem to make it work. 2) 'file' is a FileField, to which I'm passing the string of the file path, which isn't being recognized at all. I'm not sure if there's some different structure for file uploads that I am missing completely. Here is the output from formset.errors: [ { 'account': ['Select a valid choice. That choice is not one of the available choices.'], 'file': ['This field is required.'] }, { 'account': ['Select a valid choice. That choice is not one of the available choices.'], 'file': ['This field is required.'] } ] i found a handy helper function to put together the formset data here. The formset data looks like this: { 'form-INITIAL_FORMS': 0, 'form-TOTAL_FORMS': 2, 'form-1-account': 'RRSP' … -
Set the default value of a Model as superuser
I have the following abstract class: class UserStamp(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='%(app_label)s_%(class)s_updated_by', on_delete=models.CASCADE) class Meta: abstract = True The Account Model inherits from it: class Account(MetaData): pass And I have a User Model with a FK to class User(AbstractBaseUser,PermissionsMixin): account = models.ForeignKey(Account, blank=True, null=True, related_name='owner',on_delete=models.CASCADE) I have the following error: django.db.migrations.exceptions.CircularDependencyError: This can be solved by adding later the FK, but in this case I need a default value for created_by for the Account. I don't want to use pk=1 as default, because is not safe, if use permissions change or is deleted. So, I need to set the default user, as the first superadmin. Take in consideration that I use a custom user model. -
unable to save data before saving models in django
i am trying to build a single custom registration form for companies, admin and staff, when i create my superuser my 'Account type' is 'admin' , but when i try registering as a company my 'Account type' is empty. i can set a default value in my model class, but i would like to add more different types of 'Account type' in future. i also dont want to have a dropdown for the field models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, account_type=None, password=None): if not email: raise ValueError('Email address is required') user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, account_type = account_type ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, first_name, last_name, password): user = self.create_user( email, first_name = first_name, last_name = last_name, account_type = 'staff', password = password ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password): user = self.create_user( email, first_name = first_name, last_name = last_name, account_type = 'admin', password = password ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=64) last_name = … -
Method in Django to display all attributes' values belonging to a created object?
Is there a certain method in Django which allows for retrieving/displaying all attributes' values belonging to an object created via Django? In Python shell, I used the following: print(p.first_name, p.last_name, p.software_name) p is the created object with the attributes first_name, last_name, software_name. I already created several models which were applied to a database mysql. However, I would like to learn of other ways to display such information. -
Consuming A Rest API in Django
Is it possible to create make a model field that consumes a REST API as a foreign key? I have two projects. The first project has this model in models.py from django.db import models from django_countries.fields import CountryField from django.urls import reverse class Currency(models.Model): name = models.CharField(max_length = 50) country = CountryField() code = models.CharField(max_length = 3) base = models.BooleanField() class Meta: ordering = ['code'] def __str__(self): return (self.code) def get_absolute_url(self): return reverse('currency_detail', args = [str(self.id)]) I have serialized the model with the following code in serializers.py from rest_framework import serializers from currencies . models import Currency class CurrencySerializer(serializers.ModelSerializer): class Meta: model = Currency fields = ('name', 'code') I created the following views.py from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from currencies . models import Currency from . serializers import CurrencySerializer def currency_list(request): currency = Currency.objects.all() serializer = CurrencySerializer(currency, many = True) return JsonResponse(serializer.data, safe = False) and provided the following in urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^currencies/$', views.currency_list), ] The url is passing the information ok in json format. There are no authentications (I am not good enough yet). when I use … -
Django: Intervention when raising errors when creating User via social authentication
I'm setting up social authentication with the package social-auth-app-django. I have the below ValueError raised when attempting to create a user when an email isn't supplied. users.py if not email: message = "Ooops, it doesn\'t look like an email was specified. If you are signing in via one of your social media account, please ensure there is an email address associated to your account." raise ValueError(message) It wasn't really necessary originally as I would handle the form validation on the front end with standard form validation. However, when integrating social sign-ins this causes an issue. In development this is great - but essentially at this stage I would like to fling the error back to an errors template which says that they must supply an email address. I believe on platforms, such as Twitter, a user can initially register without an email address associated to the account. That's where I spotted this conflict. Essentially, social-auth-app-django isn't throwing an error before this - so how at this point, do I send the user back to a specified template which I can build to handle such errors by passing them back via the context? Looking and looking through the documentation, I can't … -
'NewsImage' object is not iterable
models.py code fragment class Article(models.Model): title = models.CharField(max_length=150, verbose_name='Title') content = models.TextField() created = models.DateTimeField(auto_now=True, verbose_name='Create Date') slug = models.SlugField(primary_key=True, max_length=250, unique=True) summary = models.TextField(blank=True, max_length=250, help_text='Meta Description') img = models.CharField(max_length=10000, blank=True, null=True, default=None) tags = models.ManyToManyField(NewsTag, default=None, blank=True) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.title def get_absolute_url(self): return reverse('article', args=[str(self.slug)]) class Meta: verbose_name = 'Article' verbose_name_plural = 'Articles' class NewsImage(models.Model): article = models.ForeignKey(Article, blank=True, null=True, default=None, on_delete=False) image = models.CharField(max_length=10000, blank=True, null=True, default=None) is_main = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.article class Meta: get_latest_by = 'id' ordering = ['id'] verbose_name = 'Article Image' verbose_name_plural = 'Articles Images' views.py code def main(request): news_articles = NewsImage.objects.filter(is_main=True, is_active=True).latest('id') products_images = ProductImage.objects.filter(is_active=True, is_main=True) return render(request, 'landing/home.html', locals()) HTML file fragment <aside> <div id="news"> <h2 class="heading">News</h2> <div style="clear: both"><br></div> {% for articles in news_articles %} <div id="articles"> <div class="article"> <a href="{{ articles.article.get_absolute_url }}"> <img src="{{ articles.image }}"> <div style="clear: both"></div> <span>{{ articles.article.title }}</span><div style="clear: both"></div> </a> <em>{{ articles.article.created }}</em> <div style="clear: both"><br></div> </div> {% endfor %} </div> <a href="" title="View More Articles"> <div id="btn"> <span>View More</span> </div> </a> </div> </aside> Trying to render html page gives error: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0 Exception Type: … -
How to apply upvote functionality with corresponding Model in Template?
I am developing a quora like app in Django but facing two problem.I want, in Question DetailView if user have not upvoted the answer then it will show the option of upvote and the total vote. Models.py https://paste.ubuntu.com/26333884/ {% extends 'base.html' %} {% block title %} {{ question.title }} {% endblock %} {% block body %} <h3><i>{{ question.title }}</i></h3> {{ question.description }} {% for answer in question.answer_set.all %} <br> <div> <p>{{ answer.answer_text }} <span style="font-size: 15px">by [{{ answer.user }}]</span></p> <form method="post" action="{% url 'answer:detail' question.id %}"> {% csrf_token %} <input type="hidden" name="type" value="vote"> <input type="hidden" name="answer_id" value="{{ answer.id }}"> {% for upvote in answer.upvote_set.all %} {% if upvote.user == request.user %} <input type="submit" class="btn btn-sm btn-warning" value="Downvote|{{ answer.upvote_set.all.count }}"> {% else %} {% if forloop.counter == 1 %} <input type="submit" class="btn btn-success" value="Upvote|{{ answer.upvote_set.all.count }}"> {% endif %} {% endif %} {% empty %} <input type="submit" class="btn btn-sm btn-success" value="Upvote|{{ 0 }}"> {% endfor %} </form> {% endfor %} {% endblock %} Template: https://paste.ubuntu.com/26334093/ from django.contrib.auth.models import User from django.db import models from django.shortcuts import reverse # Create your models here. class Question(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=200, blank=True, null=True) description = models.TextField() pub_date = models.DateTimeField() def __str__(self): return … -
Use django web app through Moodle
... I'm trying to access to my web app Django through Moodle, I tried: External Tool (LTI) External DataBase URL I'm looking for the simplest way ... the simplest is the URL, but it's poor in security. The main idea is to access to my Django web with the same Profile that the user have in Moodle. Some ideas?? Thank's for your time!!! -
No User matches the given query on django celery task
On my local, it is able to get the tasks and User model but when I have it in prod, rabbitMQ keeps giving me this error No User matches the given query, which is very weird. I suppose maybe I am missing django imports? but I am not sure. Here is what I have in the task. from celery import Celery sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) import django django.setup() from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User @app.task(name="get_photos") def get_photos(user_id, some_other_id, user_token): person = get_object_or_404(User, pk=user_id) #where user is the id The user Id does exists. I checked in the database. I checked type user_id it is an int. This task is getting called from an api. The api endpoint looks like this class UserProfileAPIView(APIView): """ Get username and return user profile """ # @cache_response(key_func='calculate_cache_key') def get(self, request, username): user = get_object_or_404(User, username=username) get_photos.apply_async((user.id, some_other_id, some_token), serializer='json') #also tried passing the user object. Didnt have errors but didn't process the task either. -
slug Django filed do we need this?
i am beginning with learn Django and get this data related "slug": A short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. For example, in a typical blog entry URL: https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit (spring) is the slug. why do we need this and how to use? -
Django rest ModelViewSet many-to-many create
I have my model relationships as following: A Reader will have a Wishlist and a Wishlist will have many Books: class Reader(models.Model): user = models.OneToOneField(User) ... # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) ... # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) # Record the date whenever a new book is added, it will be helpful for showing new arrivals when_added = models.DateTimeField(auto_now_add=True, blank=True, null= True) reader = models.ManyToManyField('Reader', related_name='wishlist') My serializers: class ReaderSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Reader #fields = '__all__' #depth = 1 fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library') def update(self, instance, validated_data): ... instance.which_library = validated_data.get('which_library', instance.which_library) instance.save() return instance def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.set_password(user_data['password']) user.save() reader = Reader.objects.create(user=user, **validated_data) return reader class BookSerializer(serializers.ModelSerializer): wishlist = ReaderSerializer(many=True, read_only=True) class Meta: model = Book fields = '__all__' I can already perform CRUD operations with Reader, I want to now add books to a specific Reader's wishlist. My view: class ReaderViewSet(viewsets.ModelViewSet): serializer_class = ReaderSerializer def get_queryset(self): readers = Reader.objects.filter(which_library=self.kwargs.get('library_id')) return readers @detail_route(methods=['post']) def wishlist(self): return Response('OK') … -
Trigger model method on creation or field change
Assume, that I have this model in django: class Example(models.Model): name = models.CharField(max_length=100) number = models.IntegerField(unique=True) x = models.FloatField(null=True) y = models.FloatField(null=True) z = models.FloatField(null=True) v = models.FloatField(null=True) def get_z(self): z = x / y self.z = z self.save() def get_v(self): v = z * x self.v = v self.save() When I create an object with admin panel then I provide only name, number, x and y fields. I need to z and v field calculate automatically on object creation or whenever any of fields changes they value. For now it's working via making: z_value = property(get_z) and putting z_value in list_display in admin panel, then when I go there, values are saved. -
Django foreign key with different model field values
I want to create a foreign key relationship in a model, where it actually provides a select dropdown for the model form based on another field value of the model. Normally dropdown shows the values of __str__ methods return value. I want to keep this also since it used in other places. For example, consider two models Order and Item. Item has a field called item_code and item_name. __str__ will return item_name. Order model will have foreign key to Item model. But I want it provides the item_code field values in the dropdown for item selection. How can I achieve this without changing general foreign key behavior? -
Django Database create_or_update error
So the definition for the pcaps table is : class Pcaps(models.Model): uuid = models.CharField(max_length=50, unique=True) filename = models.CharField(max_length=200, default='') datetime = models.DateTimeField(default=datetime.now, blank=True) filehash = models.ForeignKey(Malwares) systemuuid = models.ForeignKey(ClonedSystem) the definition for the malware table is: class Malwares(models.Model): name = models.CharField(max_length=100) filehash = models.CharField(max_length=100, unique=True) the code from the views file is: Pcaps.objects.update_or_create(filename=pcapname, filehash=filehash, systemuuid=uuid) the malware value is instantiated at: Malwares.objects.update_or_create(name=name, filehash=malwarehash) the error I am getting is: invalid literal for int() with base 10: 'ed01ebfbc9eb5bbea545af4d01bf5f1071661840480439c6e5babe8e080e41aa' (ed01... being the filehash value) What error am I making here? -
Django admin set and user view permission
I need to add to my django application the view permission. I need that some users have the permission to see all values inserted in some models but do not have the permission of adding/changing/deleting them. In accordance to django docs I've added "default_permissions" expression to my model meta information, for example: class Mymodel(models.Model): name = models.TextField(verbose_name=u"Name") class Meta: default_permissions = ('add', 'change', 'delete', 'view') Then I've changed my group permission and added it to some users. The problem is that when these users go to the view page they receive an 403 error. Do I have to change my "changelist_view" function? def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['model_title'] = Campaign._meta.verbose_name_plural return super(MymodelAdmin, self).changelist_view(request, extra_context=extra_context) -
django-admin starproject can't find Module django is installed with subprocess.run
I'm running a script to install the virtual environment and then install all the dependencies through subprocess.run. Everything goes great until I have to run django-admin startproject mysite. Somehow, I get Traceback (most recent call last): File "/Users/myuser/.virtualenvs/mysite/bin/django-admin.py", line 2, in <module> from django.core import management ModuleNotFoundError: No module named 'django' To make things even more strange, if you directly on the command line run pip unistall djangoand then pip install django==1.11it works, however the user will have to do that manually, which is not what I was going for. Things I checked so far: which python resulting /Users/myuser/.virtualenvs/mysite/bin/python which pipresulting /Users/myuser/.virtualenvs/mysite/bin/pip which django-admin resulting /Users/myuser/.virtualenvs/mysite/bin/django-admin I opened a shell and imported django and got the module -
Django aggregation multiple filters
I have a Django project that allows users to create their own Projects and add multiple Skills to each Project. I am trying to write a view that will allow me to display the name of each Skill as well as the Count of that Skill for all of that particular user Profile's Projects that are published. For example, if a user has three projects where they've added the Skill "HTML" I'd like to show HTML (3) on their Profile, and so on. Below is my current code which mostly works however it displays the count for that Skill from ALL user projects and not the specific user whose profile is being viewed. Models: #accounts/models.py class Profile(models.Model): #... skills = models.ManyToManyField('skills.skill') #projects/models.py class Project(models.Model): user = models.ForeignKey(User) #... published = models.BooleanField(default=False) skills = models.ManyToManyField('skills.skill') #... #skills/models.py class Skill(models.Model): name = models.CharField(max_length=100) Views: #accounts/views.py def profile(request, username): user = get_object_or_404(User, username=username) skill_counts = Skill.objects.annotate(num_projects=Count('project')).filter(project__user_id=user.id).order_by('-num_projects')[:10] return render(request, 'accounts/profile.html', { 'user': user, 'skill_counts': skill_counts, }) Template: #accounts/templates/accounts/profile.html {% for skill in skill_counts %} <div class="skill-container"> <div class="label-skill">{{ skill.name }}</div> <div class="label-skill-count"> {{skill.project_set.count}}</div> </div> {% endfor %} Any help here would be much appreciated. Thanks in advance. -
Set Django session variables through channels (http_session)
According to the Django channel docs, You get access to a user’s normal Django session using the http_session decorator - that gives you a message.http_session attribute that behaves just like request.session. You can go one further and use http_session_user which will provide a message.user attribute as well as the session attribute. Is there anyway I can set a session variable like so? if 'username' not in message.http_session: message.http_session['username'] = 'temp' -
Issue loading admin.site.urls after changing the settings folder
I re-organized Django,the following way: config - settings - base.py - local.py urls.py wsgi.py In base.py/local.py: ROOT_URLCONF = 'config.urls' WSGI_APPLICATION = 'config.wsgi.application' In manage.py I changed: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") In wsgi.py I changed: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") I have the following error on runserver: \django\contrib\admin\sites.py", line 269, in get_urls path('%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)), AttributeError: 'AccountAdmin' object has no attribute 'urls' It is related to this line: path('admin/', admin.site.urls), # Django 2.0 syntax If I comment that line I get the following error: django\contrib\admin\sites.py", line 79, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'AccountAdmin' object has no attribute 'model The app admin is in installed app, I don't know what is creating this issue.