Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get all parameters and their values in a request in Django
I have a get request being sent to my Django project with a list of parameters. GET /site/login? _name=bill&_last_name=Smith&_favorite_food=wings I need to get each parameter and it's value. What would be the best way to do this? I know that in Django you can do print(request.data) but I need the parameters. -
creation of a middleware to display the messages
my goal is the creation of a middleware to allow messages to be displayed the application works in my views but as soon as I put it alone there is a problem I will put the simplify version models.py class MarketingMessage(models.Model): message = models.CharField(max_length=150) middleware.py class DisplayMarketing(MiddlewareMixin): def process_request(self,request): try: request.session['marketing_message']=MarketingMessage.objects.all()[0].message except: request.session['marketing_message']=False sitting.py MIDDLEWARE = [ ... 'marketing.middleware.DisplayMarketing', ] -
Django - django-fernet-fields
Within my Django Project - I am trying to read database records where some fields are encrypted using the django-fernet-fields When I try to read these fields - I cannot get the unencrypted values returned. Instead I get 'memory at' values like below.... [{'id': 6, 'enable': <memory at 0x10775ae88>, 'config': <memory at 0x10775af48>, 'rotation_name': 'rotation1', 'username': 'mr_test'}] The documentation suggested they would be automatically decrypted - any ideas, how I turn these 'memory at' values into the unencrypted values that I am looking for? Thanks -
Django-filter Select Which Attribute to Filter and Which Comparison Operator
Hi I am working with the Django-filter package and I am trying to create custom filter logic so that the user can select Which attribute from the model that they would like to filter on The comparison operator for the queryset "<",">",">=",""<=","=" A number or another attribute to compare from 1. (logically determined based on selection option 1.) Below is my views.py file. #views.py from django_filters.views import FilterView from django.contrib.auth.mixins import LoginRequiredMixin from django_tables2 import SingleTableMixin from django_tables2.paginators import LazyPaginator from .tables import StockTable from .models import StockModel from .filters import CustomFilter class FilteredPersonListView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = StockTable model = StockModel template_name = "bootstrap_template.html" filterset_class = CustomFilter def get_queryset(self): get_data = super().get_queryset() return get_data def get_table_kwargs(self): return {"template_name": "django_tables2/bootstrap4.html"} Below is my tables.py file #tables.py from .models import StockModel import django_tables2 as tables class StockTable(tables.Table): class Meta: model = StockModel template_name = "django_tables2/bootstrap.html" fields = ("ticker","price", "volume","relative_volume") Below is my models.py file. #models.py from django.db import models class StockModel(models.Model): id = models.AutoField(primary_key=True) ticker = models.CharField(max_length=20) price = models.FloatField(default=False) volume = models.FloatField(default=False) relative_volume = models.FloatField(default=False) class Meta: db_table = 'tabledata' Below is what I have so far for my filters.py file. I figure most of the logic will live in … -
Grouping time values using Pandas Groupby
so I have an object containing filtered data from a Django database. The data contains a list of time values in the form of: YYYY-MM-DD HH:MM:SS and I'm trying to group each second to its corresponding minute and each minute to its corresponding hour. Then I need to pass this grouping to the front end of my website that uses Javascript. So far I have code that does the grouping, though it's not exactly what I want, the code and output are seen below: # Makes pd dataframe of database object, sets dateTime as index so we can easily extract hour, min, sec later queryToDataFrame = pd.DataFrame(filterTable.values()[1:],columns=filterTable.values()[0]).set_index('dateTime') hours = queryToDataFrame.index.hour # extracts hours from dataframe minutes = queryToDataFrame.index.minute seconds = queryToDataFrame.index.second timepd = pd.DataFrame({'hours':hours, 'minutes':minutes, 'seconds':seconds}) # puts time values into new dataframe for easier processing groupVar = timepd.groupby([timepd.hours, timepd.minutes]).apply(print) # groups minutes to hours and seconds to mins Output | | hours | minutes | seconds| |- | ----- | ------- | ------ | |0 | 20 | 52| 10| |1 |20 | 52 | 30 |2| 20| 52| 35 | | hours| minutes| seconds| |-| -------| --------| --------| |3 |20 |53 |0 |4 |20 |53 |5 |5 |20 … -
How can I create tables in my database(postgresql) for corresponding checkboxes?
I am building a music streaming application and the user register page has 'Name' and 'Genres' as the columns to be answered by the user. 'Genres' have 5 options which I have given using checkbox. I need help in adding them to my database and also fetching the data back to my database. -
File owner when having a non-root user
I'm setting up a Django project with a Dockerfile and I'm wondering about the correct ownership when having a non-root user. My Dockerfile looks like this: FROM python:3.7-slim ENV DIR=/data ENV USER=files RUN groupadd --gid 1000 -r ${USER} \ && useradd --uid 1000 --no-log-init -r -g ${USER} ${USER} WORKDIR ${DIR} COPY poetry.lock pyproject.toml ${DIR}/ RUN poetry install --no-interaction --no-ansi --no-root ADD . ${DIR} RUN chown -R ${USER}:${USER} ${DIR} USER ${USER} There are two things that I'm not sure if they're needed, but I've seen them in a few articles. Could someone please elaborate why/if I'd want them. --gid 1000 and --uid 1000 RUN chown -R ${USER}:${USER} ${DIR} -
Django Unitest Register Class Based View
I have searched a lot. I have Read a lot of posts on stack, but couldn't find an answer. Is there possibility to make a test class, to test Register Class Based View? Tried to find an answer but without results. My form: class RegisterForm(UserCreationForm): class Meta: model = User fields = UserCreationForm.Meta.fields + ('username', 'password1', 'password2', 'email') def clean_username(self): username = self.cleaned_data.get("username") if User.objects.filter(username=username).exists(): raise forms.ValidationError("User with that name already exist") return username def clean_email(self): email = self.cleaned_data.get("email") if User.objects.filter(email=email).exists(): raise forms.ValidationError("Acount with that Email already exist") My view: class Register(FormView): template_name = 'profile/register.html' form_class = RegisterForm redirect_authenticated_user = True success_url = reverse_lazy('landing-page') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) accepted_terms = AcceptTerms() context['register_form'] = context.get('register_form') context['accepted_terms'] = accepted_terms return context def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) messages.info(self.request, "account created") return super(Register, self).form_valid(form) def form_invalid(self, form): messages.error(self.request, form.errors) return super(Register, self).form_invalid(form) and the test: CREATE_USER_URL = '/register/' def create_user(*args, **kwargs): ''' Help function to create user by query ''' return get_user_model().objects.create_user(**kwargs) class TestProfile(TestCase): def setUp(self): self.client = Client() self.factory = RequestFactory() def test_user_register(self): ''' test user register ''' payload ={'username': 'test', 'password1':'testin1234', 'password2':'testin1234', 'email': 'jan@test.pl', } response = self.client.post(CREATE_USER_URL, payload) self.assertEqual(response.status_code, 200) print('First … -
unreachable db container in a multi-container application - django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
All existing answers didn't solve this problem. I'm running two containers on a Linux machine using docker-compose. the db is up before the app (django). the db is accessible from "outer space" port... see pycharm data source connection snapshot. so, I think that the only reasonable suspect is the docker network. I think I had a similar problem when was trying to use docker containers to run word-press with it's db. regarding the username I have changed all to my userid since the service was generating the db directory with systemd-coredump user. (base) [liran@localhost ~]$ cat /etc/passwd ... systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin liran:x:1000:1000::/home/liran:/bin/bash ... Dockerfile FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8000 docker-compose.yml version: '3.7' services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:/app depends_on: - db user: 1000:1000 db: image: mysql:5.7.22 hostname: 'db' restart: always environment: MYSQL_DATABASE: admin MYSQL_USER: root MYSQL_PASSWORD: root MYSQL_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/mysql ports: - 33066:3306 user: 1000:1000 settings.py """ Django settings for pythonMS2 project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings … -
Why is dramatiq detecting my PC as 32 bits?
I'm trying to run django-dramatiq --watch, but it returns a RuntimeError: Watching for source changes is not supported on win32. django-dramatiq version: dramatiq version: Both my Python installation and my system are 64 bits, so I don't understand the issue -
Mac m1, rtree 0.9.7, spatialindex 1.9.3, symbol not found
() isikkaplan@iamhere# python3 manage.py loadfixtures -s=testing fixture fixtures/knock/0_ct.json -v3 Traceback (most recent call last): File "/Users/isikkaplan/Desktop/code/uplift/-/--/manage.py", line 21, in <module> main() File "/Users/isikkaplan/Desktop/code/uplift/-/--/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/alphashape/__init__.py", line 6, in <module> from .alphashape import alphashape File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/alphashape/alphashape.py", line 15, in <module> import geopandas File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/geopandas/__init__.py", line 1, in <module> from geopandas._config import options # noqa File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/geopandas/_config.py", line 126, in <module> default_value=_default_use_pygeos(), File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/geopandas/_config.py", line 112, in _default_use_pygeos import geopandas._compat as compat File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/geopandas/_compat.py", line 202, in <module> import rtree # noqa File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/rtree/__init__.py", line 9, in <module> from .index import Rtree, Index # noqa File "/opt/homebrew/Caskroom/miniforge/base/envs/--/lib/python3.9/site-packages/rtree/index.py", line 6, in <module> from . import core File … -
Slack SocialAccount Error bad_redirect_uri django-allauth
Hi I am getting the following response as a callback from my call to the slack API: Code: unknown, Error: Error retrieving access token: b'{"ok":false,"error":"bad_redirect_uri"}' I have specified the redirect_uri in my call and it matches the entry in the slack app settings. Any idea on how to solve/debug this? -
Django missing staticfiles manifest entry in dependency
I'm working with a django project (let's call it django-project) and a single abstracted dependency (let's call it django-dependency). That dependency contains some static files which are also manifested in its Manifest.in. django-dependency is installed in the environment and the files are there, manage findstatic django-dependency/js/some-file.js successfully finds that file in the environment. django-project works fine when DEBUG is True and without changes to the STATICFILES_STORAGE. However when saving an object in the admin panel with DEBUG=False, I get error 500 with message: Missing staticfiles manifest entry for 'django-dependecy/js/some-file.js'. manage.py collectstatic works with the default STATICFILES_STORAGE. The same happens When I change STATICFILES_STORAGE to django.contrib.staticfiles.storage.ManifestStaticFilesStorage. I'm unable to manage.py collectstatic and even manage.py findstatic (I receive the same error as above). When STATICFILES_STORAGE is default I can do findstatic however as mentioned the app breaks when saving some objects (django-dependency is an admin widget). django-dependency works fine (the functionality is as expected) when django-project is able to run. django-project's staticfile configuration: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'files', 'public', 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'files', 'dist')] Should I configure somehow django-dependency's staticfiles? Manifest.in includes already the needed static files? I have really no idea. This is how the files in django-dependency … -
Inheriting html code does not work properly
I'm new to Django and I have a question about this part of extending a component from the base.html. Let's say I want to use% extends in another html page, it doesn't load for me Look enter image description here this is my directory project In my base.html on container I have this: {% block content %} {% endblock content %} And in next page, home.html I have this {% extends 'base.html' %} {% block content %} html code {% endblock content %} I uploaded to use templates / base.html but the same result I do not receive errors or etc. What other information would you need? -
Override save() method in model to prepopulate it with current user Django
So I know what to do in view to prepopulate model with the current user name. But how (if it is possible at all) do I override save() method in model to prepopulate it with the current user id or current user name? As far as I know there's no way i can get request.user from model variables. Here's my model. Thank you in advance! class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, verbose_name='url', unique=True) author = models.ForeignKey(User, max_length=100, on_delete=models.CASCADE, default='1') content = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name='created at') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) views = models.IntegerField(default=0, verbose_name='views') category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='posts') tags = models.ManyToManyField(Tag, blank=True, related_name='posts') def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.slug: self.slug = slugify(self.title) super().save() def get_absolute_url(self): return reverse('post', kwargs={'slug': self.slug}) -
Python + Trying to reduce I/O operation to store Data in Table
Sample Data: sales_counts = [ { "sale_id": 1001 }, { "sale_id": 1002 }, { "sale_id": 1001 }, .... ] for sale in sales_counts: Order.objects.get_or_create(sales_number=sale['sale_id'], sale_type='online') For a Small Number of SalesCount, it is fine to have one by one iteration. But for a large number of sales counts, performance will be too bad and time-consuming. In the above example: sale_id would differ and the rest of the column will be the same. How can we reduce the number of iteration and data storing calls to DB. -
In Django How to set up dependent dropdown lists
I am attempting to set up dependent dropdown lists in a Django 3.1 site. The lists are populated via another app (Django-Machina) DB tables. I attempted to adapt the example here. However I am new to Django and Python and so far, I am not able to get this to work. My files are as follows: models.py from django.contrib.auth.models import AbstractUser from django.db import models from machina.core.db.models import get_model from django.db.models import Q Forum = get_model("forum", "Forum") class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) business_location_state = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft":1}) business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2)))) views.py from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm from .models import CustomUser from django.shortcuts import render from machina.core.db.models import get_model from django.db.models import Q Forum = get_model("forum", "Forum") class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def load_counties(request): parent_id = request.GET.get('business_location_state') counties = Forum.objects.filter(parent_id=parent_id).order_by('name') return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties}) accounts/urls.py # accounts/urls.py from django.urls import path from .views import SignUpView from . import views urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('ajax/load-counties/', views.load_counties, name='ajax_load_counties'), # ajax to load counties ] forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class … -
Filter two related models in django-filter with output in template file
I have two models in my django app that are related. models.py class security_incident(models.Model): asset = models.CharField(max_length=200) # security_incident has one asset actor = models.CharField(max_length=200) #security_incident has one actor action = models.CharField(max_length=200) # one action can have several attacks attributes = models.CharField(max_length=9, choices=CIA_CATEGORIES, default=C) # up to two attributes def __str__(self): return self.asset class attack(models.Model): action = models.ForeignKey(security_incident, on_delete=models.CASCADE) # one action can have several attacks attack_name = models.CharField(max_length=200) defense_mechanism = models.CharField(max_length=200) # attack_name can only have one defense_mechanism def __str__(self): return self.attack_name I am trying to filter these models with this django-filter: filters.py class SecIncFilter(django_filters.FilterSet): asset = django_filters.CharFilter(lookup_expr='icontains', distinct=True, label='Search for security incidents, related attacks and defense mechanisms to an asset') attributes = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple(), choices=CIA_CATEGORIES, label='Choose categories') class Meta: model = security_incident fields = ['asset','attributes'] def __init__(self, *args, **kwargs): super(SecIncFilter, self).__init__(*args, **kwargs) # at sturtup user doen't push Submit button, and QueryDict (in data) is empty if self.data == {}: self.queryset = self.queryset.none() This is then beeing rendered after clicking search into this template: generate_tree.html <div class="row"> <div class="card card-body"> <div class="col-md-12"> <h5>Search for related security incidents</h5> <form method="get"> <div class="well"> <div class="form-group col-sm-8 col-md-6"> {{ filter.form.asset.label_tag }} {% render_field filter.form.asset class="form-control" %} </div> <div class="form-group col-sm-8 col-md-12"> {{ … -
Cowardly refusing to install hooks with `core.hooksPath` set
i tried to run this command but it always show this error, i can't fix it with anyway. Help me, please! (venv)<...>pre-commit install [ERROR] Cowardly refusing to install hooks with core.hooksPath set. hint: git config --unset-all core.hooksPath -
Can Django admin url be on a swagger file using drf-yasg?
I am deploying a Django API on Google Endpoint. Google endpoint needs a documentatin generated with openapi2.0 to set all endpoint. If an url is not defined on the yaml file generated by openapi (here by drf-yasg) the endpoint can not be reached even if it is available. Thing is, it would be very very very useful for me to access my django admin zone on my api but when I generate my yaml file it skips my admin url. here is my url, basic: urlpatterns = [ # back path('', include('api.urls')), path('', include(spectacular_url)), path('admin/', admin.site.urls), ] Do you know how to do this ? Thanks -
Using Prefetch related on so many nested foreign keys for performance
I am trying to reduce the queries count from 14 to more less for a Custom Manager model. Initially I set the manager function like: def for_display(self): return self.select_related("customer",).prefetch_related( "lines", Prefetch( "lines__pooja_slot", queryset=TemplePoojaSlots.objects.select_related( "pooja", ).prefetch_related( Prefetch( "pooja", queryset=TemplePooja.objects.select_related( "pooja", ).prefetch_related( Prefetch( "deity", queryset=TemplePooja.objects.select_related( "deity", ), ), ), ), ), ), Prefetch("lines__user_profile"), Prefetch( "lines__temple", queryset=Temple.objects.select_related(), ), Prefetch( "lines__donation", queryset=DonationOrder.objects.select_related("donation_event"), ), ) This one had 14 queries running. I was able to reduce the number to 9 by doing so: def for_display(self): return self.select_related("customer",).prefetch_related( Prefetch( "lines", queryset=CheckoutLine.objects.select_related( "user_profile", "temple", "donation", "donation__donation_event", "pooja_slot__pooja", "pooja_slot__pooja__pooja", "pooja_slot__pooja__deity__deity", ), ) ) Is there any issue on going through multiple foreign keys like "pooja_slot__pooja__deity__deity" on the select related? Also, I see a N+1 query issue still on this. This is for displaying a cart item. When I add items one by one to cart, the query gets increased by 2 more for each. What should I do to control that ? -
Unable to lunch json file on index.html
views.py from django.shortcuts import render from django.http import HttpResponse import json booksData = open( r'C:\Users\Dhiraj Subedi\Desktop\pool1\books.json').read() data = json.loads(booksData) def index(request): context = {'books': data} return render(request, 'books\index.html', context) index.html <html> <head> <title></title> </head> <body> {% for book in books %} <p>{{book.title }} </p> <img src="{{book.url}}" width="200px"> {% endfor %} </body> </html> I am not able to lunch a JSON data on the index.html file and the image is not shown but its icon is seen and Books text is display there is no any Book text -
Can I make a class based view with 2 serializer classes DjangoREST
So while working on a recent project I found that I needed to query the database through 2 models, basically I need to know if it is possible to have 2 serializer_classes in my view (fyi I kinda need to use class based views only). Can anyone tell me how to do that? -
How to generate .exe file from django web?
Can anyone tell me how to generate .exe from the django project ? I tried pyinstaller and py2exe but im not able to get proper working exe .Does anyone know how to do that,I'm stuck there from past few days.Help me guyz. -
TypeError: NoneType object is not callable on GeoDjango
Although I have read many similar articles about PointField and 'NoneType' object error, I can't figure out how this field should be automatically save according to the latitude and longitude variables I received from the user. Here is my model: from django.db import models from django.contrib.gis.db import models from django.contrib.gis.geos import Point class Firm(models.Model): FirmName = models.CharField(max_length=50) address = models.CharField(max_length=1000, null=True, blank=True) FirmAddress = models.PointField(null=True, blank = True, geography=True, default=Point(0.0, 0.0)) lat = models.FloatField(null=True, blank=True) lng = models.FloatField(null=True, blank=True) Logo = models.ImageField(null=True, blank=True) @property def save(self, *args, **kwargs): self.FirmAddress = Point(self.lng, self.lat) super(Firm, self).save(*args, **kwargs) On the Django shell, I type from firm.models import Firm command first and then Firm.objects.create(FirmName="QWERTY", address="temp", lat=24, lng=54, Logo='logo.jpg') command. Here is the error I got at the end: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Deniz\Desktop\PROJECT\fenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Deniz\Desktop\PROJECT\fenv\lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) TypeError: 'NoneType' object is not callable But when I look at my database, I see that a value of type geography-point has been added to the FirmAddress column. When I remove the FirmAddress feature and update the model, I don't get any errors and everything works fine. …