Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to put a ForeignKey field in User (but not SuperUser)
I would like to put a ForeignKey field in User (but not SuperUser). I'm using a custom user but I'm stuck... That's what I did in the app I called accounts: admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import TeamMasterCreationForm, TeamMasterChangeForm from .models import TeamMaster class TeamMasterAdmin(UserAdmin): add_form = TeamMasterCreationForm form = TeamMasterChangeForm model = TeamMaster list_display = ['username', 'email', 'team', ] admin.site.register(TeamMaster, TeamMasterAdmin) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import AbstractUser class TeamMasterCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = AbstractUser fields = ('username', 'email', 'team', ) class TeamMasterChangeForm(UserChangeForm): class Meta: model = AbstractUser fields = ('username', 'email', 'team', ) models.py from django.db import models from django.contrib.auth.models import AbstractUser from skeleton.models import Team # Create your models here. class TeamMaster(AbstractUser): team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True) -
No module named 'dj_database_url' while deploying Django app on Heroku
I have a problem while deploying my Django app on Heroku after the command : heroku run python manage.py migrate I get the following error text : Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/foodtasker/settings.py", line 145, in <module> import dj_database_url ModuleNotFoundError: No module named 'dj_database_url' When I run pip freeze it appears that dj_database_url already exists. My pip freeze gives : authy==2.2.3 certifi==2018.11.29 chardet==3.0.4 defusedxml==0.5.0 dj-database-url==0.5.0 Django==1.10 django-bootstrap3==7.0.1 django-braces==1.13.0 django-extensions==2.1.4 django-oauth-toolkit==1.0.0 django-oauth2-provider==0.2.6.1 django-rest-framework-social-oauth2==1.0.7 djangorestframework==3.9.0 gunicorn==19.6.0 idna==2.8 oauthlib==2.1.0 phonenumbers==8.10.2 Pillow==3.3.0 psycopg2==2.7.4 PyJWT==1.7.1 python-dotenv==0.10.1 python-social==0.1 python-social-auth==0.3.6 python3-openid==3.1.0 pytz==2018.7 requests==2.21.0 requests-oauthlib==1.0.0 shortuuid==0.5.0 simplejson==3.16.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==2.0.0 urllib3==1.24.1 whitenoise==3.2.1 For the current state I don't figure … -
HTML file not loading properly in django
I am trying to integrate my django app with a admin dashboard from github . I can see after my successfull log in the app get directed to dashboard but only the HTML part is loading i can't see any fancy things getting added to my dashboard. It should have been looking like the one screenshot given in github link. I am not a regular frontend developer so it's getting hard for me figure out where the mistake is. Dashboard.html <!doctype html> <html lang="en"> <head> {% load staticfiles %} <meta charset="utf-8" /> <link rel="icon" type="image/png" href="assets/img/favicon.ico"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title>Light Bootstrap Dashboard by Creative Tim</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' /> <meta name="viewport" content="width=device-width" /> <!-- Bootstrap core CSS --> <!--<link href="css/bootstrap.min.css" rel="stylesheet" />--> <link rel='stylesheet' href="{% static 'css/bootstrap.min.css' %}" type='text/css' /> <!-- Animation library for notifications --> <!--<link href="assets/css/animate.min.css" rel="stylesheet"/>--> <link rel='stylesheet' href="{% static 'css/animate.min.css' %}" type='text/css' /> <!-- Light Bootstrap Table core CSS --> <!--<link href="assets/css/light-bootstrap-dashboard.css?v=1.4.0" rel="stylesheet"/>--> <link rel='stylesheet' href="{% static 'css/animate.min.css' %}" type='text/css' /> <!-- CSS for Demo Purpose, don't include it in your project --> <!--<link href="assets/css/demo.css" rel="stylesheet" />--> <link rel='stylesheet' href="{% static 'css/demo.css' %}" type='text/css' /> <!-- Fonts and icons --> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" … -
Create a signal for when a model is created
I have checked django docs on built in signals for this (https://docs.djangoproject.com/en/2.1/ref/signals).I have 2 models: Member and Tithe. Every member has a tithe record, I want a tithe record to be created whenever a member is created. -
How to change language of months in "SelectDateWidget" django
I am using widget SelectDateWidget, and i am trying to change the name of months form english to portuguese, i already tried this: https://docs.djangoproject.com/en/2.1/topics/i18n/ is not working forms.py class RegisterForm2(forms.Form): gender = forms.ChoiceField(label="Género", choices = UserRegister.gender_choices, required=True) birthdate = forms.DateField(widget = forms.SelectDateWidget, localize=True) class meta: model = UserRegister fields = ['gender', 'birthdate'] -
Django2.0 multiselectfield
I'm using a multi select library to render checkbox fields in my template and then store them in the database. I was able to do this correctly, but the data is only loaded in this format check box, when exposing the contents of these check boxes as strings, what is shown are "None" and not the contents of the marked check box. How do I collect the data from this check box or to show it correctly? Is there any other way to do this more easily? models.py n_dentes = ( ('18', '18'), ('17', '17'), ('16', '16'), ('15', '15'), ('14', '14'), ('13', '13'), ('12', '12'), ('11', '11'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('48', '48'), ('47', '47'), ('46', '46'), ('45', '45'), ('44', '44'), ('43', '43'), ('42', '42'), ('41', '41'), ('31', '31'), ('32', '32'), ('33', '33'), ('34', '34'), ('35', '35'), ('36', '36'), ('37', '37'), ('38', '38'), ) class pregao(models.Model): tipo = models.CharField(_('Tipo de serviço'), max_length=100, default=' ') dente = MultiSelectField(_('Dente'), choices=n_dentes, default=' ', max_length=100) template.html {% extends 'baseR.html' %} {% load static %} {% block title %} Novo pregão - SMILE 3D {% endblock %} {% block tamanho %} 2500px {% … -
What is a decent practice for running django `makemigrations` outside of a container-only dev environment
I raise a container with my Django-based App and another container with PostgreSQL, linked to each other network-wise, using docker-compose. If I run the makemigrations outside of a bash session inside my application docker container (linked to the PostgreSQL container), like this: python manage.py makemigrations myapp I get the following exception: django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known Which makes sense: I don't have any instance (and configuration) of PostgreSQL outside of the container execution context. From what I understand from past experience with other languages, and also other posts like this one it would be desirable for me to run makemigrations and commit it. Which would be the best approach to create and commit the migration files: Should I try to expose the PostgreSQL container and change the settings.py DATABASE to be able to run the makemigrations command from a local bash session? Should I copy the makemigrations result executed from inside the container, into my repository and then commit it? Should I not worry about not commiting the migrations, and instead make them and run them with a docker-entrypoint.sh approach (example)? Any other option? -
How to pass request object from one view to another?
Is there a way to pass request object from one view to another? Or do I have to dissect the request into individual parts or use request.__dict__ and pass those? Currenlty, because the request cannot be serialized, the below code: def explorer(request): collect_activities_init(request) return render(request, 'explorer/explorer.html') def collect_activities_init(request): task = collect_activities.delay(request) return JsonResponse({'status_url': reverse('explorer:collect_activities_status', kwargs={'task_id': task.id})}) @celery.task(bind=True) def collect_activities(self, request): api = StravaApi() code = request.GET.get('code', '') # extract code from redirect URL query string Will give: WSGIRequest: GET '/explorer/?state=&code=3ba4hgh5ad99ea3cf8e52d8&scope='> is not JSON serializable But I need to have the request data from the first function in the last one, because its code extracts some data from the request. -
Heroku shows Application Error for my Django app
I've deployed my Django app to Heroku. However, I get the Application Error and found something weird in the log of Heroku: "ModuleNotFoundError: No module named 'django_site'". Can anyone tell me what's causing the errors based on my Heroku logs? Here is the requirements.txt file: dj-database-url==0.5.0 Django==2.1.4 django-heroku==0.3.1 gunicorn==19.9.0 mysqlclient==1.3.14 numpy==1.15.4 psycopg2==2.7.6.1 pytz==2018.7 whitenoise==4.1.2 I've put Heroku's log in this gist. -
how to save foreign keys using django-rest-framework
I'm new to Django and I'm trying to save Unit and current_user foreign keys in the database based pk obtained but every time I try doing so but run into two types of error serializers.is_valid() raises an exception error or the serializer returns "Invalid data. Expected a dictionary, but got Unit." I have tried a very very ugly way of bypassing serializers by getting rid but i get ee8452a4-2a82-4804-a010-cf2f5a41e006 must be an instance of SavedUnit.unit.I have also tried saving the foreign key directly using SavedUnit.objects.create() without luck model.py class SavedUnit(models.Model): """ Saving units for later models relationship with units and users """ id = models.UUIDField(primary_key=True, default=hex_uuid, editable=False) unit = models.ForeignKey(Unit, on_delete=models.CASCADE) user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='user') published_at = models.DateTimeField(auto_now_add=True) serializers.py class SavedSerializer(serializers.ModelSerializer): unit = UnitSerializer() class Meta: model = SavedUnit fields = [ 'id', 'unit' ] views.py class SavedUnitView(APIView): """ Query all the unites saved """ @staticmethod def get_unit(request, pk): try: return Unit.objects.get(pk=pk) except Unit.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) @staticmethod def post(request, pk): if request.user.is_authenticated: unit = get_object_or_404(Unit, id=pk) serializers = SavedSerializer(data=unit) if serializers.is_valid(raise_exception=True): created = SavedUnit.objects.get_or_create( user=request.user, unit=unit) return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_401_UNAUTHORIZED) def get(self, request): units = SavedUnit.objects.filter(user=self.request.user.id) try: serializers = SavedSerializer(units, many=True) return Response(serializers.data, status=status.HTTP_200_OK) except Unit.DoesNotExist: return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
Django ModelForm in Modal on Home Page
I have a form that is rendering on its own template page 'build-project-custom.html' in a Django Application. I'm trying to repeat the form as a pop-up modal on the home page. I keep getting the error: Parameter "field" should contain a valid Django BoundField. I don't think I quite understand how ModelForm's work in the views or how they are populated in another class based view. I basically want a user to be able to submit this form on a modal on the home page. Help is greatly appreciated. I'm rather new to Python and Django so a simple explanation would be greatly appreciated. buildproject/models.py class CustomProjectBuildRequest(models.Model): CUSTOM_PROJECT_CONTACT_METHOD = ( ('Email', 'Email'), ('Call', 'Call'), ('Text', 'Text'), ) first_name = models.CharField(max_length=100, null=False, verbose_name='First Name') last_name = models.CharField(max_length=100, null=False, verbose_name='Last Name') email = models.EmailField(max_length=255, unique=False, verbose_name='Email') phone_number = PhoneNumberField(null=False, blank=False, verbose_name='Phone') created_timestamp = models.DateTimeField(auto_now_add=True, verbose_name='Requested') updated_timestamp = models.DateTimeField(auto_now=True, verbose_name='Updated') project_name = models.CharField(max_length=100, verbose_name='Project Name') project_description = models.TextField(null=False, verbose_name='Description') preferred_contact_method = models.CharField(max_length=512, choices=CUSTOM_PROJECT_CONTACT_METHOD, verbose_name='Preferred Contact Method') # Admin database comments for each project request created customer_contacted = models.DateTimeField(null=True, blank=True, verbose_name='Customer Contacted') customer_comments = models.TextField(max_length=512, null=True, blank=True, verbose_name='Admin Comments') buildproject/forms.py class CustomProjectBuildRequest(forms.ModelForm): class Meta: model = CustomProjectBuildRequest fields = ['first_name', 'last_name', 'email', 'phone_number', 'project_name', … -
why celery task is created but not received
I am using celery with Django, the tasks are defined in tasks.py. The execution is done in views.py using task.delay(). I have a total of 32 different tasks. All the tasks are created well (meaning all the task IDs are created), the problem is that the first task is not received unless I restart celery on my localhost. Occasionally, the second task is not received as well. I don't know what could be wrong, any suggestion is appreciated! Thanks a lot -
Mysql Multiple Join Perfromance with Django Rest Framework
I've been struggling with a problem which i believe every one does at some point. I've a small database of 150k products for now. (Increasing as i'm writing this.) I'm using DRF for the api and been struggling with the categories performance in which i've much products. I.E I've a category called Dresses which have 34633 products. How my Database is designed is i've Couple of relations under it. Product have Categories, Attributes, Color, Sizes, Related Products M2M Queries Count Query 809.83 ms SELECT COUNT(*) FROM (SELECT DISTINCT `catalog_products`.`id` AS Col1 FROM `catalog_products` INNER JOIN `catalog_products_category` ON (`catalog_products`.`id` = `catalog_products_category`.`products_id`) WHERE (`catalog_products`.`deleted` = 0 AND `catalog_products`.`in_stock` = 1 AND `catalog_products_category`.`categories_id` = 183)) subquery Result Query 2139.52 ms SELECT DISTINCT `catalog_products`.`id`, `catalog_products`.`sku`, `catalog_products`.`title`, `catalog_products`.`old_price`, `catalog_products`.`price`, `catalog_products`.`sale`, `catalog_products`.`original_categories`, `catalog_products`.`original_conv_color`, `catalog_products`.`original_sizes` FROM `catalog_products` INNER JOIN `catalog_products_category` ON (`catalog_products`.`id` = `catalog_products_category`.`products_id`) WHERE (`catalog_products`.`deleted` = 0 AND `catalog_products`.`in_stock` = 1 AND `catalog_products_category`.`categories_id` = 183) ORDER BY `catalog_products`.`title` ASC LIMIT 48 as you can see time is so much for a query but here's the tricky part when i apply filters I.E i select color filter and size time start to decrease. Queries with filters applied Count Query 264.63 ms SELECT COUNT(*) FROM (SELECT DISTINCT `catalog_products`.`id` … -
How to manually write the form in template when using forms.py
I try to manually write the form design in the template because what i get from {{ form.as_p }} looks like shit. I got a model the refrence the user and another model. Like a connection model for making many to one, with one extra field. So this is my models, except excluding user model. class UserGroup(models.Model): nickname = models.CharField(max_length=55) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) group = models.ForeignKey('group.Group', on_delete=models.CASCADE) And the Group model class Group(models.Model): name = models.CharField(max_length=250) location = models.ForeignKey('Location', on_delete=models.SET_NULL, null=True, blank=False) active = models.BooleanField(default=True) The Forms.py looks like this class UserGroups(forms.ModelForm): class Meta: model = UserGroup fields = ('nickname', 'group') Also the view ofc: @method_decorator(login_required, name='dispatch') class UserGroup(generic.CreateView): form_class = UserGroups template_name = 'users/user_group.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': self.form_class}) Now when I use the {{ form.as_p }} in the template. It gets really ugly. The worst part is that since the Group is several. It creates a Select-Option dropdown list. I don't what this. I want to loop through all Groups and have a nickname input for each. So the user can decide which Group they want to add a nickname to. This is as far as I get for ding this. It … -
Password Generator with hiding password field Django
i am using User in-built model of django. I want to create password for user like 'test@123' for everyone. without showing password field in template -
How to count visitors in Django
i'm developing blog with Python - Django framework, i wanna create section of popular posts, how can i use django-hitcount ? INSTALLED_APPS = [ 'home', 'bootstrap3', 'froala_editor', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hitcount' ] -
SQLDecodeError at /admin/
I am using django with mongodb and everything else is working good except when i log into my admin using superuser it gives SQLDecodeError at /admin/. The above exception (Unrecognized pipeline stage name: '$addFields' mongod --version shows db version v3.6.3. djongo==1.2.31, pymongo==3.7.2, sqlparse==0.2.4 -
Nested Relations in Django
I am following the url: https://www.django-rest-framework.org/api-guide/relations/#nested-relationships This is my model: class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ('album', 'order') ordering = ['order'] def __unicode__(self): return '%d: %s' % (self.order, self.title) This is my serializer: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title', 'duration') class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') I am expecting result like this : { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ... ], } But i am not getting the tracks: { "album_name": "The Grey Album", "artist": "Danger Mouse", "tracks": [] } -
How to render 2 fields where you can add/remove permissions to user like in the admin interface
I'm currently in progress of creating some custom permissions, and I want to create a interface like the django admin one, where you have 2 boxes with available permissions and current permissions and you can add/remove specific permissions. I can handle rendering the HTML myself but how would i do this in Python? -
Django formset: why use management form inside template ?
I am reading Django docs and don’t quite understand the comment below about formsets. Why do I need to be aware to use the management form inside the management template in this example ? Using a formset in views and templates Using a formset inside a view is as easy as using a regular Form class. The only thing you will want to be aware of is making sure to use the management form inside the template. Let’s look at a sample view: from django.forms import formset_factory from django.shortcuts import render from myapp.forms import ArticleForm def manage_articles(request): ArticleFormSet = formset_factory(ArticleForm) if request.method == 'POST': formset = ArticleFormSet(request.POST, request.FILES) if formset.is_valid(): # do something with the formset.cleaned_data pass else: formset = ArticleFormSet() return render(request, 'manage_articles.html', {'formset': formset}) # manage_articles.html <form method="post"> {{ formset.management_form }} <table> {% for form in formset %} {{ form }} {% endfor %} </table> </form> -
recover variable direct from function in ListView using url pattern Django
i have a listview class PackageDashboardView(ListView): model = Package template_name = "packages/dashboard.html" def get_queryset(self): sort = self.kwargs.get("sort", None) default_order_by = "title" if sort == 'date': default_order_by = "-started" queryset = Package.objects.all(). order_by(default_order_by, 'version__name', 'seasons').select_related('title', 'version').defer('title__metadata', 'validation', 'translations', 'diff_fields') return queryset url.py url(r'^packages/sort:(?P<sort>\w+)$', packages.PackageDashboardView.as_view(), name="package_dashboard"), template.html <a href="/packages/sort:date"><div class="controller type">by Date</div></a> <a href="/packages/sort:title"><div class="controller type">by Title</div></a> i want to pass variable sort direct in my function get_queryset without passing with self.kwargs.get("sort", None) -
Customizing Django admin import form to include a drop-down bar
I'm using the Django import-export library to add an Import option to populate the database for one of my models (Sample). The model contains fields that should be matched with import file columns, as well as a ForeignKey to another model, which I want to be able to select from a drop-down bar on the import page for all imported Samples. I have tried customising the import form to include it by overriding the import_action following this answer. This is my model in core/models.py: class Sample(models.Model): study = models.ForeignKey(Study, ...) sample_ID = models.CharField(...) sample_source = models.CharField(...) brain_region = models.CharField(...) RIN = models.CharField(...) diagnosis = models.CharField(...) sex = models.CharField(...) age_at_death = models.IntegerField(...) ApoE = models.CharField(...) flowcell = models.CharField(...) PMI = models.CharField(...) And here is how I override the import_action method in core/admin.py: class SampleImportForm(ImportForm): study = forms.ModelChoiceField(queryset=None) def __init__(self, choice_model, import_formats, *args, **kwargs): super(SampleImportForm, self).__init__(import_formats, *args, **kwargs) self.fields['study'].queryset = choice_model.objects.all() class SampleAdmin(ImportExportModelAdmin): resource_class = SampleResource def import_action(self, request, *args, **kwargs): super().import_action(request, *args, **kwargs) form = SampleImportForm(Study, self.get_import_formats(), request.POST or None, request.FILES or None) However, when I try to access the admin page to import Samples, I get the following error: AttributeError: 'NoneType' object has no attribute 'has_header', which I am struggling … -
How do create a dynamic urlconf for each subdomains?
I've been looking on the internet on how to create a dynamic URL patterns for each subdomains. e.g. domainA.com has / for HomeView.as_view() about/ for AboutView.as_view() contact/ for ContactVIew.as_view() domainB.com has / for HomeView.as_view() menu/ for MenuView.as_view() order/ for OrderVIew.as_view() A lot on the internet recommended to create a separate files like "domain_a.urls" and "domain_b.urls" and swap it using the "process_request" in a Middleware like this: https://docs.djangoproject.com/en/2.1/topics/http/urls/ at the moment, i'm planning to store the "urls" in database and generate/cache it and load it during middleware. however, the issue is that, request.urlconf only takes in 'path.to.urls'. other than creating a tmp file as a solution for it, can it be done without writing a file? -
django send uploaded files by users to cloudflare cdn
I just want every file uploaded by users to be automatically sent to cloudflare cdn. I was looking at django-cloudflare-push, but it doesn't mention media files uploaded by users, just static files like css or js. Once those files has been sent to cloudflare cdn I need a way to call their url from this cdn -
How to check the presence of column in queryset (Django ORM)
I want to check if given field is SELECTed in given queryset. Assuming there is Queryset.has() method, this should run without AssertionError: qs = Author.objects.all() assert not qs.has('articles_count') qs = qs.annotate(articles_count=Count('articles')) assert qs.has('articles_count') qs = qs.values('pk') assert not qs.has('articles_count') (assume model Author has no field articles_count by default)