Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if the logged in user is present in groups in class based views(viewsets.ModelViewSet)?
I have a class based view class JobViewSet(viewsets.ModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer permission_classes = (IsAuthenticated,) I have 2 group of users(implemented using django.contrib.auth.models Group), 'company' and 'customer'. On each view, I have to check if the user belongs to a certain group. Is it possible to do it using custom permission_classes. Thank you. -
How to connect to local network database from docker container
I'm trying to connect to an express database on sql server accesible throughout 192.168.0.130:1433 on local network from Docker Django container. I'm on a Mac and from local host i have ping $ ping 192.168.0.130 64 bytes from 192.168.0.130: icmp_seq=0 ttl=128 time=5.796 ms 64 bytes from 192.168.0.130: icmp_seq=1 ttl=128 time=2.234 ms But inside docker container get timeout error. docker-compose.yml: version: '3.7' services: ... django: container_name: djangonoguero_django_ctnr build: context: . dockerfile: Dockerfile-django restart: unless-stopped env_file: ./project/project/settings/.env command: python manage.py runserver 0.0.0.0:8000 volumes: - ./project:/djangonoguero depends_on: - postgres ports: - 8000:8000 networks: - djangonoguero-ntwk networks: djangonoguero-ntwk: driver: bridge Anybody could help me please ? Thanks in advance. -
sort django queryset using a temporary field which is not listed in model
My model is as follows: class People(models.Model): name = models.charfield(max_length = 200) surname = models.charfield(max_length = 200) In my function: people_list = People.objects.all() for each in people_list: if some_conditions: each.level = 1 else: each.level = 2 I need to sort the people_list using level variable I've added. I get FieldError when trying to do people_list = people_list.order_by('level') -
How do I get Sentry reference ID in html template using sentry-sdk?
Since the raven is deprecated I need an alternative way to display Sentry reference ID in my html template. The previous version looks like this from the example: <p>You've encountered an error, oh noes!</p> {% if request.sentry.id %} <p> If you need assistance, you may reference this error as <strong>{{ request.sentry.id }}</strong>. </p> {% endif %} How do I do this now? I tried to use sentry_sdk.capture_exception() or sentry_sdk.last_event_id() method. The first one returns None in my template, the second one looks like it's now what I am looking for. -
error can not Creating a Docker Container with django project
i trying to creating container for django project so but an error show with SECRET KEY in settings.py file when i run docker command docker run --publish 8000:8000 python-django error with SECRET_KEY show that i am unable to build docker container settings.py file ... # UPDATE secret key load_dotenv(find_dotenv()) SECRET_KEY = os.environ['SECRET_KEY'] .... -
Using token only in POST and not in GET http request (Django DRF) + not caching
I'm using authentification with Django (DRF), and it's working. But, I would like to use the Token only with POST request and not GET requests. Is it possible ? My code : Settings : # REST API "rest_framework", "rest_framework.authtoken", and : REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_AUTHENTICATION_CLASSES": ( # "rest_framework.authentication.BasicAuthentication", # "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ), } If I add this line, or not, it's the same : class BlaBlaViewSet(APIView): #permission_classes = (IsAuthenticated,) So, how can I do that in the "post" function and not in "put" function, please ? Have a nice day :) F. -
Fetch API to update JSON data
This is JSON data I am getting from APIs working through Python. I am appending all the username data to one JSON file, if existing user is changing their revenue value in front end now how to update their values using Python script? montly_details:[ { "user name":"John", "revenue":"90", "expenses":"30", "profits":"60" } { "username":"kite", "revenue":"120", "expenses":"60", "profits":"60" } { "username":"noel", "revenue":"150", "expenses":"70", "profits":"80" } { "username":"victor", "revenue":"180", "expenses":"30", "profits":"150" } ] -
How to store data from xml to database and than to see it on web?
Sorry for my question but i am begginer in it and this is my first project. i am solving the issue of how to store data from xml file to database and than see it on web page.I would like to use django as web builder and sql as database. But my xml file is store on my local pc and need to see this data on the web page. What is the best way how can I do it? When you image the situation, i own gym and it is self-service it mean I have terminal outside and every client use your own card for entrance, it is recorded in xml on my local pc and I need that every client will be able to see it thru web page where, when was in gym etc...but when i deploy my web "django" page to server how can i do it that web will takes data from xml file and storage it into databse on server?? Thank you for yours responses. -
Django 4 template check if user is authenticated using async view
Is there any way to check if a user is authenticated in the Django template using async view? I am having the errors SynchronousOnlyOperation when I do {% if user.is_authenticated %} in my template. I know there is the option DJANGO_ALLOW_ASYNC_UNSAFE but the doc says it's not safe. So I am wondering if there is a safer method. -
How do i do a temperature conversion in Django with radio buttons?
I'm working with API using python(Django) but I need help with converting the temperatures from Celsius to Fahrenheit and vice versa with a radio button. -
Django DeleteView Redirect to Second Previous Page
I have my generic deleteview. The user can visit here from the generic updateview, because only button is there. I like to redirect the user to previous page after deletion but the previous page is the updateview and it'll be gone with the deletion. Is there any way to send the user to second previous page after deletion ? class ActionDeleteView(generic.DeleteView): # action-deleteview model = models.Action template_name = 'crm/action_delete.html' def get_success_url(self): # for the message message = f'{self.get_object()} is deleted successfully!' messages.success(self.request, message) previous = self.request.META.get('HTTP_REFERER') print('***************** previous: ', previous) return reverse_lazy('action-listview') NOTE: The print(previous) in the code returns the updateview -
Reset Heroku DB now some of my schemas aren't migrating
New to heroku - I had some major problems with a migration from my local django app to Heroku prod so decided to destroy my heroku db with heroku pg:reset - this all seemed to go to plan, I then ran heroku run python manage.py migrate to attempt to recreate my schemas. The following were migrated: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount But none of my models.py tables went up - eg the following crucial schema was not migrated: class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) cafe_image_url = models.CharField(max_length=200, null=False) # class Meta: # # managed = False def __str__(self): return self.cafe_name Installed Apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'testingland', 'rest_framework', 'bootstrap_modal_forms', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'widget_tweaks', ] Any advice? -
what is initial steps to run project which was already developed code. how to do for first time
i have old code which is on live , my manager gave code in zip file. which is developed python 2.7 and Django 1.11 i downloaded and created environment. when i started install requirement.txt file errors were come. ERROR: No matching distribution found for alabaster==0.7.10 (from -r fedDjango/SAML_val/Samlvalidate/requeriments.txt (line 1)) d:\pro - portal\portal\venv\lib\site-packages\pip_vendor\urllib3\util\ssl_.py:139: InsecurePlatformWarning: A true SSLContext object is not available. Thi s prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecurePlatformWarning, -
Python getting blanck files from django server using docker
The problem I have is difficult to explain, so I am sorry if my question is too big. I am creating an API with python and django REST Framework, and one of the functionalities we need is to upload a file so another client can download it. The way I do this, I get it from the request with file_details = request.FILES.get('file'). Then I upload the file with the request python library like this. import requests url = "server_url" payload = {'memberId': '7d2d92fb-a21c-40a5-9e0d-f4f299edb468', 'memberType': 'professional'} file = [ ('file',(file_details.name, file_details.read(), file_details.content_type)) ] headers = {} response = requests.request("POST", url, headers=headers, data=payload, files=file) When I try this in local (on my machine), it works fine. I run our docker container and make the request with the file, and everything works perfectly. Then I download the file from the server and the file is also ok. The problem is that when I upload the code to the server and I make the postman request directly to it, it seems that is correctly uploaded, but when I try to download it I get a blank pdf file. Do you know how to solve this problem? Thanks in advance for your help. -
How to filter from auth_group_permissions table Django
How to filter from auth_group_permissions table Django. actually, I don't know by which model I can filter from auth_group_permissions. from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType I only get this model from Django documentation but I don't get any from for auth_group_permissions table. please anyone helps me. -
how to create range slider in django and javascript
how to create a range slider in Django and javascript? also for data stuff I'm using an API instead of a database I want to create a range slider like that (video demo): https://itslachiteaching.wistia.com/medias/v4cx2mncw8 #views.py def slider(request): form = SliderForm() context = { "slider": form, } return render(request, 'slider.html', context) #forms.py from django_range_slider.fields import RangeSliderField class SliderForm(forms.Form): range_field = RangeSliderField(minimum=10,maximum=102) #slider.html <div>form {{ slider.as_p }}</div> -
django: JOIN two SELECT statement results
MYSQL - working fine SELECT * FROM (SELECT ...) u LEFT JOIN (SELECT ...) e ON (u.id = e.employee_id) DJANGO u = user_with_full_info.objects.values( 'id' ).filter( branch = team['branch__id'], team = team['team__id'], position__lt = team['position__id'], valid = 1 ) d = staff_review.objects.values( 'employee' ).annotate( last_date=Max('date'), dcount=Count('employee') ).filter( month = month() ) e = staff_review.objects.values( 'performance__name', 'performance__style', 'employee__user__id', 'employee__user__salary_number', 'employee__user__last_name', 'employee__user__mid_name', 'employee__user__first_name', 'date' ).filter( month = month(), employee__id__in = Subquery(u.values('id')), date__in = Subquery(d.values('last_date')), ).order_by( 'employee__id' ) With MYSQL I got: | employee_id | performance_id | | -------- | -------------- | | 3 | 2 | | 1 | 3 | | 4 | NULL | With Django I got: | employee_id | performance_id | | -------- | -------------- | | 3 | 2 | | 1 | 3 | How can I fix that? -
Getting ProgrammingError at ... using Heroku
I made some changes to my models.py file and now I return this error when I try to access my heroku app's admin page: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) The above exception (column testingland_mapcafes.cafe_image_url does not exist LINE 1: ...s"."venue_type", "testingland_mapcafes"."source", "testingla... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1828, in changelist_view 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File … -
How do i make my categories function correctly?
so im trying to seperate my blog posts into different categories but right now it all just appears as my username blogcategory.html {% extends "base.html" %} {% block page_content %} <div class="col-md-8 offset-md-2"> <h1>{{ category | title }}</h1> <hr> {% for post in posts %} <h2><a href="{% url 'blogdetail' post.pk%}">{{ post.title }}</a></h2> <small> {{ post.created_on.date }} | Categories: {% for category in post.categories.all %} <a href="{% url 'blogcategory' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> <p>{{ post.body | slice:":400" }}...</p> {% endfor %} </div> {% endblock %} blogdetail.html {% extends "base.html" %} {% block page_content %} <div class="col-md-8 offset-md-2"> <h1>{{ post.title }}</h1> <small> {{ post.created_on.date }} |&nbsp; Categories:&nbsp; {% for category in post.categories.all %} <a href="{% url 'blogcategory' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> <p>{{ post.body | linebreaks }}</p> <h3>Leave a comment:</h3> <form action="/blog/{{ post.pk }}/" method="post"> {% csrf_token %} <div class="form-group"> {{ user.username|default:'Guest' }} </div> <div class="form-group"> {{ form.body }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <h3>Comments:</h3> {% for comment in comments %} <p> On {{comment.created_on.date }}&nbsp; <b>{{ user.username|default:'Guest'}}</b> wrote: </p> <p>{{ comment.body }}</p> <hr> {% endfor %} </div> {% endblock %} blogindex {% extends "base.html" %} {% block page_content %} <div … -
No module named 'corsheaders' docker-compose up
Hy everyone! I'm new in the Django world. I develop a Django website and I want to make a Docker container with the appliation and run it on my localhost. I created my Dockerfile and my docker-compose.yaml but when I run docker-compose up it gives the following error. Attaching to mysite-web-1 mysite-web-1 | Watching for file changes with StatReloader mysite-web-1 | Exception in thread django-main-thread: mysite-web-1 | Traceback (most recent call last): mysite-web-1 | File "/usr/local/lib/python3.10/threading.py", line 1009, in _bootstrap_inner mysite-web-1 | self.run() mysite-web-1 | File "/usr/local/lib/python3.10/threading.py", line 946, in run mysite-web-1 | self._target(*self._args, **self._kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper mysite-web-1 | fn(*args, **kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run mysite-web-1 | autoreload.raise_last_exception() mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception mysite-web-1 | raise _exception[1] mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/init.py", line 381, in execute mysite-web-1 | autoreload.check_errors(django.setup)() mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper mysite-web-1 | fn(*args, **kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/init.py", line 24, in setup mysite-web-1 | apps.populate(settings.INSTALLED_APPS) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate mysite-web-1 | app_config = AppConfig.create(entry) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 223, in create mysite-web-1 | import_module(entry) mysite-web-1 | File "/usr/local/lib/python3.10/importlib/init.py", line 126, in import_module mysite-web-1 | return _bootstrap._gcd_import(name[level:], … -
Unable to run django test in CircleCI
I am implementing CircleCI for one of the projects. The project is built on Django 3.2. My test cases run properly when I run using python manage.py test blog, when I run the same in CircleCI it returns , ====================================================================== ERROR: project.blog (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: project.blog Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'project.blog' Here is my CircleCI config version: 2 jobs: build: docker: - image: circleci/python:3.8 steps: - checkout - run: name: Installing dependencies command: | python3 -m venv venv . venv/bin/activate pip3 install -r requirements.txt - run: name: Running migrations command: | . venv/bin/activate python manage.py migrate --skip-checks - run: name: Running tests command: | . venv/bin/activate python manage.py test blog I understand that CircelCI clones the project in project folder. Is that something that I am missing in config? -
defaultdict new structure in django
i have this defaultdict(list) in my outout defaultdict(<class 'list'>, {'List of tubes': ['2324', '98', '7654', 'List of auto:': [147, 10048, 1009, 10050, 10, 1647, 10648, 649, 1005]}) How i can add a space inside AND WITOUT {(, ? to obtain 'List of tubes': '2324', '98', '7654' 'List of auto:': 147, 10048, 1009, 10050, 10, 1647, 10648, 649, 1005 -
Django display date with user current timezone
I have such model class SomeModel(models.Model): some_field = models.CharField(max_length-100) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Created at')) settings.py TIME_ZONE = "UTC" USE_TZ = True The problem: in postgres created_at value is 2022-01-19 01:18:29.096177+03 now I want to show the user, that object was created on 2022-01-19. But when I call created_at.date() it shows 2022-01-18 How to fix that? -
Django formset labels
I am creating a hosptial management system.For this query on stackoverflow there are four models in play. Order, Pharmacyitem, PharmacySalesBills and Inventory, with formsets set up for PharmacyItem and Order. The natural flow of the creating a pharmacy item, populating a sales bill and inventory work as they should. I.e date, new sales item record created and adjustment to inventory stock and sales bill generated using sales item. My idea is for a doctor to create a order, the pharmacist, does a search at any given time on the order model, and uses the model as a bridge to the pharmacy sales item model, to get quantity and name of product and patient from order object. and then using a booleanfield on the order model, which changes to true once the pharmacy item / sales bill has been created. Question: If a doctor prescribes 3 items, via template using formset, and each form in formset, will have its own id. Do i create an additional field in the order model, that acts as an identifier for the current order [so using the above example all 3 items]. Or is there a way formset can take a label, that shows the … -
How to work with foreign key with mutiple selection
Hi Everyone i am trying to achieve select multiple car with foreign key relation because we need to store data with mutiple row, i am tried with manytomany fied but this is not effective as per our requirement, thats way i am trying solve this with foreign key, pls help me out. models.py class Car_team(BaseModel): team = models.ForeignKey( Team, models.CASCADE, verbose_name='Team', null=True, ) car=models.ForeignKey( Car, models.CASCADE, verbose_name='Car', null=True) city =models.ForeignKey( City, models.CASCADE, verbose_name='City', ) start_date=models.DateField(null=True, blank=True) end_date=models.DateField(null=True, blank=True) forms.py class CarTeamForm(forms.ModelForm): start_date=forms.DateField(initial=datetime.date.today, label='Start Date') car = forms.ModelMultipleChoiceField(queryset=Car.objects.all(), required=True, widget=forms.CheckboxSelectMultiple) class Meta: model = Car_team fields = ['car','team','city','start_date'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(CarTeamForm, self).__init__(*args, **kwargs) self.fields['start_date'].widget.attrs['readonly'] = True widgets = { 'car': forms.CheckboxSelectMultiple(attrs={'class': 'form-control select2'}), } views.py def add_carteam(request, city_id=None, id=None): if id is not None: carteam = get_object_or_404(Car_team, city_id=city_id, pk=id) else: carteam = None if request.method == 'POST': form = CarTeamForm(request.POST, request.FILES,instance=carteam) if form.is_valid(): car = form.cleaned_data['car'] team = form.cleaned_data['team'] start_date = Car_team.objects.filter(car__in=car).values_list('start_date', flat=True).filter(end_date__isnull=True) # if start_date: # messages.error(request,'Car already assigned to another team!') query = Car_team.objects.filter(car__in=car).exists() query_set = Car_team.objects.filter(car__in=car).values_list('team', flat=True) team_name = Team.objects.filter(pk__in=query_set).values_list('name', flat=True) car_id = Car_team.objects.filter(car__in=car).values_list('car', flat=True) car_number=Car.objects.filter(pk__in=car_id).values_list('car_number', flat=True) if query_set and start_date: messages.error(request,'Car already assigned to team {} {}!'.format(team_name,car_number)) # if query: # …