Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin custom foreign key select box
I want to customize Django admin select box and show thumbnail in the select box next to the image title I have a class called Image and another class called News, that has a foreign key to the Image. Note: I use Django jet as admin template. class Image(models.Model): alternate = models.CharField( verbose_name=_('Alternate'), max_length=255, null=True, blank=True ) title = models.CharField( verbose_name=_('Title'), max_length=255, null=True, blank=True ) artist = models.ManyToManyField( 'Artist', verbose_name=_('Artist'), blank=True ) image = models.ImageField() def __str__(self): return "({}) {}".format(self.pk, self.title) class Meta: verbose_name = _('Image Attachment') verbose_name_plural = _('Image Attachments') @staticmethod def autocomplete_search_fields(): return 'title', class News(BaseModel): title = models.CharField( verbose_name=_('Title'), max_length=255, null=True, blank=True ) summery = RichTextField( verbose_name=_('Summery'), null=True, blank=True, ) main_image = models.ForeignKey( Image, verbose_name=_('Main Image'), on_delete=models.SET_NULL, null=True, blank=True, related_name='images' ) Now I want to show the thumbnail of the image in choices in Django admin when I want to add news. Now my select box look like this -
Custom filter in Django admin for calculated fields
# models.py class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=50) created_time = models.DateTimeField(auto_now=False, auto_now_add=True) writer = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') # admin.py @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(AuthorAdmin, self).get_queryset(request) return qs.annotate(books_count=Count('books')) def books_count(self, inst): return inst.books_count list_display = ['author', 'books_count'] Now I have two columns in admin: Author and Books count. I need to add DateFieldListFilter, but for a calculated field (not for model field). For example, to have a possibility show created books count by each author for last_week, last_month, last_year, etc. -
Trouble Installing React as an App within Django
I am using this tutorial to install React for the front with an API built in Django. https://sweetcode.io/how-use-djang-react-ap/ My repository for this projects so far is here: https://github.com/AlexMercedCoder/DjangoReactCRM I am at the point in the tutorial where you install react by running "npm run dev" This is the error I get and no tinkering with the relative file page seems to fix it: > webpack --mode development ./frontend/src/components/index.jsx --output ./frontend/static/frontend/main.js Insufficient number of arguments or no entry found. Alternatively, run 'webpack(-cli) --help' for usage info. Hash: 097c83a63f327afef15a Version: webpack 4.39.3 Time: 80ms Built at: 09/07/2019 4:16:05 PM ERROR in Entry module not found: Error: Can't resolve './frontend/src/components/index.jsx' in 'C:\Users\alexm\projects\DjangoReactCRM\drcrm' npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! drcrm@1.0.0 dev: `webpack --mode development ./frontend/src/components/index.jsx --output ./frontend/static/frontend/main.js` npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the drcrm@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\alexm\AppData\Roaming\npm-cache\_logs\2019-09- 07T20_16_05_497Z-debug.log -
How to use Django-import-export ImportForm and ConfirmImportForm outside admin
I want to use django-import-export's forms to implement the import feature for regular users, so it needs to be outside the admin section. So far, all the implementations I have found are about a) extending the feature inside the admin or b) reimplementing the default views outside the admin. But since the default forms work perfectly I would like to subclass them as part of my project (outside admin) without reimplementing the whole view's logic, if such thing is even possible. So far I tried (foolishly, I'm afraid) to subclass the import_export.admin.ImportMixin as a class view to import a model Period with resource PeriodResource: # staging/views.py from django.views import generic from import_export.forms import ImportForm, ConfirmImportForm from import_export.admin import ImportMixin from .models import Period from .admin import PeriodResource class PeriodImportView(ImportMixin, generic.View): template_name = 'period/import.html' resource_class = PeriodResource def get_import_form(self): return ImportForm def get_confirm_import_form(self): return ConfirmImportForm def get_form_kwargs(self, form, *args, **kwargs): # pass on `author` to the kwargs for the custom confirm form if isinstance(form, ImportForm): if form.is_valid(): company = form.cleaned_data['company'] kwargs.update({'company': company.id}) return kwargs and then just show the forms in the template: # staging/templates/period/import.html {{ import_form }} {{ confirm_import_form }} and my urls.py looks like this: # staging/urls.py from django.urls … -
How start background periodic task with django-background-tasks
I want to create periodic task for check values in my SQLite file. I tried to create repeating task with django-background-tasks but it doesn't work. It works fine when I used python manage.py process_tasks in cmd. How start this task with start django and without use this command? I develop my web app on Windows 10. urls.py from django.contrib import admin from django.urls import path, include from client import tasks as task urlpatterns = [ path('admin/', admin.site.urls), path('', include('client.urls')), path('account/', include('account.urls')), ] task.check_groups(repeat=10, repeat_until=None) tasks.py from background_task import background from django.utils import timezone from client.models import StudyGroup, Account @background() def check_groups(): check_active_groups() check_inactive_groups() -
How to convert Django source installation to package like installation
OS : CentOS, Redhat New to Django and python, we basically built a monitoring tool using python and Django framework. Below is the project folder structure. |-- Makefile |-- monitor-pycodes `-- web |-- content |-- __init__.py |-- manage.py |-- monitor_templ | |-- __init__.py | |-- templates | |-- templatetags | |-- urls.py | `-- views.py |-- packmonitor.wsgi |-- settings.py `-- urls.py Didnt mentioned the certain folders content to simplify the view. We used Makefile to copy our codes to system folders as below All python codes in "monitor-pycodes" --> /usr/lib/python2.7/site-packages/packmonitor/ and compile it Django templates in "web" --> /var/www/packmonitor for web UI. scritps such as packmontior & packmonitord to --> /usr/bin When run make install inside the project directory, above copying process take place and application started. My employer doesnt want this tool to be install from source. How to convert this install from source to package installation ? Thanks, Mohan -
how to fix "unorderable types: NoneType() > float()" error in django
im trying to generate a pdf of a list of employees, everything was alright until i tried to make a rowspan that groupe all the employees that are in the same department, and then i got an error, form the view i send a 3 dimensional array, employees infos inside a list of departments i tried to get the size of the group from the view and send it in l2.6 and i tried to get it from l1|length <table style="border: 1px solid black;"> <tr style="border: 1px solid black;"> <th style="border: 1px solid black;"> Service</th> <th style="border: 1px solid black;"> Nom et prenom</th> <th style="border: 1px solid black;width: 160px;"> Conge 1</th> <th style="border: 1px solid black;width: 160px;"> Conge 2</th> <th style="border: 1px solid black;width: 160px;"> Conge 3</th> <th style="border: 1px solid black;width: 160px;"> Conge 4</th> <th style="border: 1px solid black;width: 180px;""> Total</th> </tr> {% for l1 in liste %} {% for l2 in l1 reversed %} <tr> {% if l2.6 != 0%} <td rowspan="{{l1|length}}" style="border: 1px solid black" > {{ l2.0 }} </td> {% endif %} <td style="border: 1px solid black" > {{ l2.0 }} </td> <td style="border: 1px solid black;"> {{ l2.1 }} </td> <td style="border: 1px solid black;"> … -
Docker django runs only if I specify the command
I am new to docker and I was trying to create an Image for my django application. I have created the image using the following Dockerfile FROM python:3.6-slim-buster WORKDIR /app COPY . /app RUN pip install -r Requirements.txt EXPOSE 8000 ENTRYPOINT ["python", "manage.py"] CMD ["runserver", '0.0.0.0:8000'] The problem is, when I run the image using docker run -p 8000:8000 I am unable to access the app in my localhost:8000 But if I run the container using the command docker run -p 8000:8000 runserver 0.0.0.0:8000 I can see my app in localhost:8000 -
How to update two models in one form in django?
Okay, so first of all the situation is not quite easy as in the title. So I want to create form which can create object based on Cycle model and update only one field in Post model (field in question is 'cycle_title'). What is more its isn't only one post where this post have to be updated but there are several of it (all post's titles are saved in Cycle.post). views class CycleCreateView(LoginRequiredMixin, BSModalCreateView): template_name = 'blog/cycle_form.html' form_class = CycleForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(user=self.request.user) return kwargs def form_valid(self, form, **kwargs): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): reverse_user = self.request.user return reverse('profile', kwargs={'username': reverse_user}) forms class CycleForm(BSModalForm): def __init__(self, *args, user=None, **kwargs): super().__init__(*args, **kwargs) if user is not None: self.fields['posts'].queryset = Post.objects.filter(author=user) class Meta: model = Cycle fields = ['title', 'description', 'posts'] widgets = { 'posts': forms.CheckboxSelectMultiple(), } models class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = MDTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) cycle_title = models.CharField(max_length=100, default='') class Cycle(models.Model): title = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) posts = models.ManyToManyField(Post) I was thinking about a solution like this: for i in form.cleaned_data['posts']: post = Post.objects.get(title=form.cleaned_data['title'][i]) post.cycle_title = form.cleaned_data['title'] … -
Import error somehow connected with app_labels
Django==2.2.3 Python 3.7 I get this error: from yandex.models import YandexGoals ImportError: cannot import name 'YandexGoals' from 'yandex.models' (/home/michael/PycharmProjects/ads1/ads_manager/yandex/models.py) When I stop in my IDE at the event of the exception (namely, I stop at any exception) and evaluate the expression "from yandex.models import YandexGoals", I get this: RuntimeError: Model class yandex_campaigns.models.YandexCampaignCommonTemplate doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Well, the message differs. Let's investigate what we have: INSTALLED_APPS = [ ... 'yandex', 'yandex_campaigns', ] yandex.apps.py class YandexConfig(AppConfig): name = 'yandex' yandex_campaigns.apps.py class YandexCampaignsConfig(AppConfig): name = 'yandex_campaigns' To the best ob my ability, I can't see any flaw here. Could you give me a kick? -
An elegant way to send multiple url query string from different UI
I have a table page. It has page size selector, search input and pagination links at the end. When changing page size it should refresh whole page with new page size; When press enter in search input, it will submit the search string and refresh page; Based on the count of search results and page size, it will adjust pagination links. When clicking pagination link, it will refresh page, but we need to keep the current page_size and current search string and show them after refreshing page. This is a part of a Django project. Usually, I would put them together into a form, then every time the submit can carry them and send to backend. But I feel like, the page_size on the top, the pagination links on the bottom, I don't want to put a form to expand so far. Or, without a form(that's what I am doing now), I can write javascript for onChange event of selector, then it can get current search string and then refresh page (no need to save current page link as page_size going to change); then another javascript for pagination link to get current page_size and search string then send. In the … -
How can I trigger a function when a user registers in django?
I took over a django web app and am still relatively new to django. I want to trigger a function whenever a new user registers on the website. But there is no code in the project to process the user registration. It all seems to happen under the hood. So I don't know where could put such a function call. The web app uses django.contrib.auth. Additionally: How can I trigger a function when an account is activated? -
Tackling Dynamic Models/Data with Django
I'm about to start working on a Django project where my data is not going to be very structured, and am having some trouble on deciding how to approach storing it. The basic premise of my project is to create a database manager that abstracts away the SQL bits away from the user. Basically a user will create fields, and define their type. Then users will have the option to populate these fields with rows of data. For example, a user could create two fields: first would be name and the user could set it to be a text field, followed by age, and have that be an integer field. This would essentially create two columns: name and age. Up to this point I can visualize what my schema structure should look like. However, when it comes to having the user enter rows of data that correlates with these columns, I am not sure how to approach storage with this regard. Furthermore, I want users to have the option to add additional columns at any point. Any ideas on how I should tackle this problem? -
How to fix migration when upgrading from django-ldapdb 0.9.0 to django-ldapdb 1.3.0 (in debian buster)?
I ran into an issue when upgrading my web application from django-ldapdb 0.9.0 to 1.3.0 (because it is packaged in Debian Buster). It creates migrations that fail. It seems that django-ldapd enforce dn as a primary key for the models (see here, but I don't want to hack django-ldapdb nor can I avoid migrations in my app ), so I tried removing the existing primary key in the model, but that didn't work... Here is an example of one of the models creating buggy migrations (worked fine in 0.9.0) : class LdapServiceUserGroup(ldapdb.models.Model): """ Class for representing an LDAP userservice entry. Un group user de service coté ldap. Dans userservicegroupdn (voir dans settings_local.py) """ # LDAP meta-data base_dn = LDAP['base_userservicegroup_dn'] object_classes = ['groupOfNames'] # attributes name = ldapdb.models.fields.CharField( db_column='cn', max_length=200, ) members = ldapdb.models.fields.ListField( db_column='member', blank=True ) def __str__(self): return self.name So when running makemigrations it creates a migrations which set dn as a primary key. And then : File "/usr/lib/python3/dist-packages/MySQLdb/connections.py", line 292, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server ver sion for the right syntax to use near ')' at line 1") (full error … -
If statement in django template
I have a if statement to test if the categorie of the file is audio and I want to show the html audio tag if it is true. I tried to remove the if statement juste to test the audio tag and it is working just fine. {% if medias.categorie_media == "Audio" %} <audio controls src="{{medias.fichier_media.url}}">Votre navigateur ne supporte pas la lecture audio, veuillez télécharger le fichier.</audio> {% endif %} The output is when it is an audio file it show nothing. I inspected the code in the browser and the audio line is not showing. -
Django Audio Player
I am working on a django music app and I have a model called Song. class Song(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) ... audiotrack = models.FileField(upload_to=upload_image_path) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name='track_likes') It gets passed in the template as an object list. def list_view(request): songs = Song.objects.all() context = { 'tracks_list' : songs } return render(request,"musica/list.html",context) In the template, I for-loop through the objects and link them to the audio player. <audio id="player" src="{{ object.audiotrack.url }}"></audio> <button onclick="document.getElementById('player').play()"></button> And this is the problem. The buttons remain the same, and play always one and the same track. I have a like button already for the songs, which is a ManyToMany Field. class TrackLikeToggle(RedirectView): def get_redirect_url(self,*args,**kwargs): id = self.kwargs.get("id") obj = get_object_or_404(Song,id=id) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) return url_ Do I need to make something similar for the play button? A OneToOne Field called playing which toggles the audio player? But how is this going to work in the template, considering the player link: <button onclick="document.getElementById('player').play()"></button> Thank you for any suggestions -
Adding dropdown to bootstrap3 nav bar
I'm working with bootstrap3 and django. I want to update my navbar to add a dropdown list of links in my navbar on the right . My bootstrap code: Toggle navigation Bob and Company <li> <a class="dropdown"> {# <button class="dropbtn">Dropdown#} {# <i class="fa fa-caret-down"></i>#} {# </button>#} <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </a> </li> {# <li>#} {# <a href="#">About</a>#} {# </li>#} </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> so far I'm getting the screenshot. How can i fix this to get this working? -
Integration of mongoengine with django
I'm using Mongoengine for a Django project first of all I have installed it with pip install mongoengine In the project structure, I found that I'm using mongoengine 0.18.2 and pymongo 3.9.0 which are the latest versions for this moment but when I run the project I got the following error ImportError: cannot import name 'connection' from 'mongoengine' The error is raised for the following line on settings.py from mongoengine import * -
Django bulk_upsert saves queries to memory causing memory errors
For our Django web server we have quite limited resources which means we have to be careful with the amount of memory we use. One part of our web server is a crom job (using celery and rabbitmq) that parses a ~130MB csv file into our postgres database. The csv file is saved to disk and then read using the csv module from python, reading row by row. Because the csv file is basically a feed, we use the bulk_upsert from the custom postgres manager from django-postgres-extra to upsert our data and override existing entries. Recently we started experiencing memory errors and we eventually found out they were caused by Django. Running mem_top() showed us that Django was storing massive upsert queries(INSERT ... ON CONFLICT DO) including their metadata, in memory. Each bulk_upsert of 15000 rows would add 40MB memory used by python, leading to a total of 1GB memory used when the job would finish. Apparently Django does not release the query from memory after it's finished. Running the crom job without the upsert call would lead to a max memory usage of 80MB, of which 60MB is default for celery. We tried running gc.collect() and django.db.reset_queries() but the … -
How to fix 'CreateView is missing a QuerySet'
I'm trying to get a django app to manage accounts and users. Admin user can access the django admin site and do whatever the want for managing user. Simple user which have rights on users can add / modify users through forms but not access django admin site. Im' tryning to add a CreateView for simple user to adding users, but i keep getting this error : 'CreateView is missing a QuerySet' Is it cause I extend AbstractBase User ? Can someone explain me what are those queryset and how to fix my code ? Thanks you The code : ` #admin.py class UserCreationForm(forms.ModelForm): password = forms.CharField(label='Mot de passe', widget=forms.PasswordInput) password_confirm = forms.CharField(label='Confirmation du mot de passe', widget=forms.PasswordInput) class Meta: model = UserProfile fields = ('first_name', 'last_name', 'email', 'perm_on_user', 'perm_on_news', 'is_admin',) def clean_password_confirm(self): # Check that the two password entries match password = self.cleaned_data.get("password") password_confirm = self.cleaned_data.get("password_confirm") if password and password_confirm and password != password_confirm: raise forms.ValidationError("Les mots de passes ne correcpondent pas") return password def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user class UserModificationForm(forms.ModelForm): password = forms.CharField(label='Mot de passe', widget=forms.PasswordInput) password_confirm = forms.CharField(label='Confirmation du mot de passe', … -
Use of regroup built-in template tag
I'm trying to regroup some data in a table using regroup. This is the model that I use: class EnographiaeVillages(models.Model): id_region = models.IntegerField() region = models.CharField(max_length=100) id_sub_region = models.IntegerField() sub_region = models.CharField(max_length=100) id_sub_region3d = models.IntegerField() sub_region3d = models.CharField(max_length=100) nom = models.CharField(max_length=100) def __str__(self): return self.nom class Meta: ordering = ['nom'] Following this indications I've use this: {% regroup villages_subregion by sub_region3d as subregion %} <table> {% for sub_region3d in subregion %} <tbody> <tr> <th>{{ sub_region3d.grouper }}</th> <td> <ol> {% for village in sub_region3d.list %} <li class="my-0">{{ village.nom }}</li> {% endfor %} </ol> </td> </tr> </tbody> {% endfor %} </table> villages_subregion cames from a context_processors: def villages_for_subregion(rerquest): villages_list = EnographiaeVillages.objects.all() villages_counter = villages_list.count() context = { 'villages_subregion': villages_list, 'villages_counter': villages_counter, } return context What I would like to see is this: sub_region3d 1 nom 1A1 nom 1B1 nom 2B1 nom 3B1 nom 1c1 nom 2C1 sub_region3d 2 nom 1B2 nom 2B2 nom 1c2 nom 2C2 nom 1D2 but I see this: sub_region3d 1 nom 1A1 sub_region3d 1 nom 1B1 nom 2B1 nom 3B1 sub_region3d 2 nom 1B2 nom 2B2 sub_region3d 1 nom 1c1 nom 2C1 sub_region3d 2 nom 1C2 nom 2C2 sub_region3d 2 nom 1D2 The table results illegible with a … -
Django Template - Select Value From List
I have a Django template that has a and I want to add the selected value to my view that is a post request to the database. When I have a normal char field I just do: name='Studyplan-Name' for example. But I can't do in the selecter name='Studyplan-Parent_Assignment'. How do I do this? @login_required def skapa_studieplan(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') parent_assignment = request.POST.get('Studyplan-Parent_Assignment') studyplan = Studyplan(name=name, description=description, parent_assignment=parent_assignment) studyplan.save() return redirect('allaStudieplaner') <h6>Välj en Uppgift att plugga inför</h6> <select class="browser-default custom-select"> <option selected, name="Studyplan-Parent_Assignment">Välj Uppgift</option> {% for x in Assignments %} <option value="1">{{ x.name }}</option> {% endfor %} </select> <hr> -
Image disappears after some hours
I have build a simple website using django framework,with a blog section to allow staff to write articles and upload an image. unfortunately after a few hours the articles and images will disappear,but when I check on aws s3 bucket,the images are still there. I have checked on my code and it is okay,the saved functionality is working well. I expect to have the content on the blog to be there permanently lest deleted from the back end. -
How to set environmental variables properly Gitlab CI/CD and Docker
I am new to Docker and CI/CD with Gitlab CI/CD. I have .env file in the root directory of my Django project which contains my environmental variable e.g SECRET_KEY=198191891. The .env file is included in .gitignore. I have set up these variables in Gitlab settings for CI/CD. However, the environment variables set in Gitlab CI/CD settings seem to be unavailable Also, how should the Gitlab CI/CD automation process create a user and DB to connect to and run the tests? When creating the DB and user for the DB on my local machine, I logged into the container docker exec -it <postgres_container_name> /bin/sh and created Postgres user and DB. Here are my relevant files. docker-compose.yml version: "3" services: postgres: image: postgres ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ web: build: . command: /usr/local/bin/gunicorn writer.wsgi:application -w 2 -b :8000 environment: DEBUG: ${DEBUG} DB_HOST: ${DB_HOST} DB_NAME: ${DB_NAME} DB_USER: ${DB_USER} DB_PORT: ${DB_PORT} DB_PASSWORD: ${DB_PASSWORD} SENDGRID_API_KEY: ${SENDGRID_API_KEY} AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID} AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY} AWS_STORAGE_BUCKET_NAME: ${AWS_STORAGE_BUCKET_NAME} depends_on: - postgres - redis expose: - "8000" volumes: - .:/writer-api redis: image: "redis:alpine" celery: build: . command: celery -A writer worker -l info volumes: - .:/writer-api depends_on: - postgres - redis celery-beat: build: . command: celery -A writer beat -l info … -
Virtualenv intersection (python, django)
When I did the command: mkdir djangoproject cd djangoproject/ python3 -m venv myvenv source myvenv/bin/activate echo Django~=2.0.6 > requirements.txt pip install -r requirements.txt django-admin startproject projectname . python manage.py runserver I see the error at localhost: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/ I did not create urls for "catalog" (used "catalog" in previous project) I think that the issue deals with intersection of venvs. (I deleted previous project, but the error stayed) How can I fix it?