Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Limiting selection of many to many field on ModelForm to just values from parent record
Could really use some help. I have a django app that has the following tables: Mission. Package. Target. Flight. A mission has 1 or many packages. 1 or many targets and 1 or many packages. A package has one or many flights. A Flight has a many to many relationship such that there is a multi-select field that allows you to select pre-added targets (added as children of the mission parent) to the flight. The problem is the dropdown shows all targets ever added to the database. I was expecting it would only show targets that belong to the mission parent. How do I limit the target options that appear in the Flight form, to just those of targets that belong to a mission? Mission Model class Mission(models.Model): # Fields campaign = models.ForeignKey( 'Campaign', on_delete=models.CASCADE, null=True) number = models.IntegerField( default=1, help_text='A number representing the mission order within the campaign.', verbose_name="mission number") name = models.CharField( max_length=200, help_text='Enter Mission Name') description = models.TextField( help_text='Enter Mission Description/Situation.', default="Mission description to be added here.") Package Model class Package(models.Model): # Fields mission = models.ForeignKey( 'Mission', on_delete=models.CASCADE, null=True) name = models.CharField( max_length=200, help_text='Enter Package Name', verbose_name="Package Name") description = models.TextField( help_text='Enter Mission Description/Situation.', null=True, blank=True, verbose_name="Description … -
Djoser user creating route return a socket error
I'm using Djoser to create a user from my front-end. When I create a user from the React app with this request const newStudent = () => { fetch(`${process.env.REACT_APP_SERVER_URL}/auth/users/`, { method: 'POST', headers: { "Accept": "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ email: "mss@domain.hr", display_name: "Maa", username: "as", password: "sa", role: 1 }) }) } The request completes, the new user gets created but this nice error pops up in the Django console ---------------------------------------- Exception occurred during processing of request from ('192.168.1.6', 49473) Traceback (most recent call last): File "C:\Python39\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Python39\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python39\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Mislav\.virtualenvs\backend-EBmKnWnA\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Mislav\.virtualenvs\backend-EBmKnWnA\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Python39\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine ---------------------------------------- The interesting thing is that other requests work fine after the socket error Doing the exact same request from postman doesn't cause the error [08/Apr/2021 13:15:46] "POST /auth/users/ HTTP/1.1" 201 104 My Djoser setup DJOSER = { 'USER_ID': 'id', 'LOGIN_FIELD' : 'username', 'LOGOUT_ON_PASSWORD_CHANGE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': … -
Invalid block tag on line 2: 'else', expected 'endblock'. Did you forget to register or load this tag?
I followed one django tutorial on youtube. I am currently category page where I want to have urls like this: "../search/<category_name>" I have no problem loading the page until I want to search the category. I am using the name in the category database which is 'django' so that I can avoid error. The URLs FYI, I'm using vscode and run the code in django html language. I have read some discussion regarding to this issue. I have followed one advice to rearrange so that it can read the code easily but when I save the code is going back to the state shown in the picture below. Therefore, I encounter an error due to invalid block tag. Django html code back to its state when I save picture Invalid block tag Output -
Django annotate and apply different aggregation functions on the same field
I'm using django annotate and I want to apply multiple aggregations on the same field: queryset = queryset.apply_filters( user=user, start_date=start_date, end_date=end_date ).values('product').annotate( avg_a=Avg('field_a'), total_a=Sum('field_a'), ) But I'm getting the following FieldError: django.core.exceptions.FieldError: Cannot compute Sum('field_a'): 'field_a' is an aggregate I'm quite sure that SQL queries like this one: SELECT AVG(field_a), SUM(field_a) FROM random_table GROUP BY product Are totally valid. To recap: How I could apply multiple aggregation functions on the same field using annotate? -
Make HTML custom field sortable in django-admin
I have a very simple model that just consists of a name and serial number. I can use that serial number to ask for a status on an API and I want to display the result as icon/HTML: class ProductAdminForm(admin.ModelAdmin): class Meta: model = Product fields = ["get_status", "name",] def get_status(self, obj): status = get_status_from_API(obj)["status"] style = """style="height: 10px; width: 10px; border-radius: 50%; COLOR display: inline-block;" """ if status == 2: new_style = style.replace("COLOR", "background-color: green;") elif status == 2: new_style = style.replace("COLOR", "background-color: red;") else: new_style = style.replace("COLOR", "background-color: grey;") return mark_safe(f"""<span class="dot" {new_style}></span>""") How can I make the get_status column sortable? -
New ckeditor's plugin is not showing
I am trying to add a Plugin in django-ckeditor in my BlogApp. How i am trying to do :- I have downloaded a plugin from ckeditor site named hkemoji and I have pasted it in the main plugins file of ckeditor but when i try to check in browser then it is not showing in Browser. I have seen many tutorial but nothing worked for me. Any help would be appreciated. Thank You in Advance. -
How to get data from model to model when user click button in django
So in my website, i have this page with products, and another page titled " MyList ", so 2 templates. The page with the products has a model which stores the products ( name, price , link). So what I want to do is the following: I want to have a button for every product, and when the user clicks it, that product should be added to his list page. Like on a shop, when you add a product to your cart. But I really don't understand how to do this, and how my view should look like :/ in this image u can see the webpage with the productshere is the model of the products -
Django not recognizing blocks and endblocks in HTML
this block isn't recognizing my HTML code, which is weird. Is there anyway to fix this? <!DOCTYPE html> {% extends 'base.html %} {% block content %} <!DOCTYPE html> <div style="border: 2px solid #000;"> <h1> This is the body </h1> <p> Here is where you put stuff </p> </div> {% endblock content %} -
Problem with TypeError: a bytes-like object is required, not 'str'
recently I started with Django, and now I'm working on a website and I have an error. Note: I use Manjaro Linux. I have found a template online (calorietracker is the name)that I want to use some parts for my website but I cannot run this template. This is what I get when I try to run it... (calorietracker) [mahir@mahir-pc mysite]$ ./manage.py runserver Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/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 "/home/ma1bolg3s/calorietracker/mysite/mysite/settings.py", line 72, in <module> "default": django_cache_url.parse(os.getenv("MEMCACHED_URL")) File "/home/ma1bolg3s/.local/share/virtualenvs/calorietracker-UDGAzgdx/lib/python3.7/site-packages/django_cache_url.py", line 60, in parse if '?' in path and query == '': TypeError: a bytes-like object is … -
DRF - created_by and last_updated_by fields - how to make it work?
How to make created_by and last_updated_by fields work in Django REST Framework? Created by should be populated when the object is created and last_updated_by should be updated any time the object is updated. The usual way is to use CurrentUserDefault but that is not working on PATCH methods if the last_updated_by is not included in the payload. last_updated_by = serializers.HiddenField(default=serializers.CurrentUserDefault()) Do you know how to do that? Maybe the best way would be to modify the serializer data inside the ViewSet but I can't figure out how. -
Dynamically determine Django template tags file to be loaded inside {% load %} using a variable
I have a set of applications in a Django project all of which have similar templates. In each template for each application, I load the template tags file I have defined for that application: {% load <appname>tags %} But since appname is different for every application, it causes the templates (which are identical otherwise) to differ. I can determine appname programmatically inside a template, so all I need is a way to do something like this: {% load appname|add:'tags' %} Is such a thing possible? The idea above doesn't work because the result of the expression is parsed directly, rather than being interpreted the way other tags are. The end goal is to have the templates which are the same across all the applications to be shared via soft links, to reduce code duplication. -
I am getting cannot serialize error in django 3.1
I have created a new user model as shown below: In this, I am creating a new user model and an admin from abstract user and BaseUserManager. I have also added some extra fields like gender and phone number. from django.contrib.auth.base_user import BaseUserManager from django.db.models import Manager from importlib._common import _ from django.db import models from django.contrib.auth.models import AbstractUser from phone_field import PhoneField # Create your models here. class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('Users must have email address.') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Super user must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): genders = ( ('m', _('Male')), ('f', _('Female')), ('o', _('Other')), ) username = None email = models.EmailField(_('email address'), unique=True) is_passenger = models.BooleanField(default=True) is_driver = … -
Cerbot error when completing challenges while running Django dockerized application with NGINX (and UWSGI)
When building and running my docker project with docker compose I get an error on the cerbot. The following errors were reported by the server: Domain: example.com Type: connection Detail: Fetching http://example.com/.well-known/acme-challenge/5bGuPxC5Bd-jqT6BOBS91XJg0cNjxc: Connection refused To fix these errors, please make sure that your domain name was entered correctly and the DNS A/AAAA record(s) for that domain contain(s) the right IP address. Additionally, please check that your computer has a publicly routable IP address and that no firewalls are preventing the server from communicating with the client. If you're using the webroot plugin, you should also verify that you are serving files from the webroot path you provided. My docker compose file part of the proxy is: proxy: build: context: ./proxy volumes: - static_data:/vol/static - ./proxy/default.conf:/etc/nginx/conf.d/default.conf ports: - "80:80" depends_on: - web And my docker file of the proxy is: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf COPY ./uwsgi_params /etc/nginx/uwsgi_params USER root RUN mkdir -p /vol/static RUN chmod 755 /vol/static RUN apk add --no-cache python3 python3-dev py3-pip build-base libressl-dev musl-dev libffi-dev gcc cargo sudo RUN pip3 install pip --upgrade RUN pip3 install certbot-nginx RUN mkdir /etc/letsencrypt RUN certbot --nginx -d example.com --email info@example.com -n --agree-tos --expand USER nginx My understanding is that the … -
post_save signal in django
I want to save the user IP address and the reference link in UserLog whenever the user performs any changes in the model. Currently, I am using post_save signal for this purpose. But the problem is, that it does not pass the request argument that's why I am unable to use request.META.get. Can anyone guide me to this or is there any other best practice to perform this. @receiver(post_save, sender=Session) def session_added_success(sender, instance, created, **kwargs): user = request.user action = "Logout" action_from_page = request.META.get('HTTP_REFERER') campus = request.user.campus remarks = f"{user} created a new session" login_ip = request.META.get('REMOTE_ADDR') if created: log = UserLog.objects.create( user=user, action=action, action_from_page=action_from_page, campus=campus, remarks=remarks, ip_address=login_ip) if created == False: print("Record Updated") -
Is there a way to set @csrf_exempt decorator to a view class?
I am trying to allow sending POST request without CSRF token, but getting an issue #view.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework import viewsets from .serializer import AuthorSerializer, MessageSerializer from .models import Author, Message @csrf_exempt class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.order_by('-send_time') serializer_class = MessageSerializer def listMessages(self, page): per_page = 5 queryset = Message.objects.all()[page * per_page: page * per_page + per_page] return JsonResponse(queryset, safe=False) class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer AttributeError: 'function' object has no attribute 'get_extra_actions' Is there a way of getting this working? -
Will Django run on Windows Server 2019 or 2016?
I am trying to launch my app which i have created using flutter and django.I have started a server, the server provider is asking which OS i want in my server ,he is giving the option of Windows server 2016 and 2019. Which one should i choose? How will Django work in a Windows Server? -
Converting jsonb_each postgresql query to Django ORM
I have a query that joins on a jsonb type column in postgres that I want to convert to Django SELECT anon_1.key AS tag, count(anon_1.value ->> 'polarity') AS count_1, anon_1.value ->> 'polarity' AS anon_2 FROM feedback f JOIN tagging t ON t.feedback_id = f.id JOIN jsonb_each(t.json_content -> 'entityMap') AS anon_3 ON true JOIN jsonb_each(((anon_3.value -> 'data') - 'selectionState') - 'segment') AS anon_1 ON true where f.id = 2 GROUP BY anon_1.value ->> 'polarity', anon_1.key; Following are my models: class Tagging(BaseModel): class Meta: db_table = "tagging" json_content = models.JSONField(default=dict) feedback = models.ForeignKey("Feedback", models.CASCADE) class Feedback(BaseModel): class Meta: db_table = "feedback" feedback_text = models.TextField(blank=True, null=True) The json_content field stores data in the following format: { "entityMap": { "0": { "data": { "people": { "labelId": 5, "polarity": "positive" }, "segment": "a small segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 75, "anchorOffset": 3 } }, "type": "TAG", "mutability": "IMMUTABLE" }, "1": { "data": { "product": { "labelId": 6, "polarity": "positive" }, "segment": "another segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 138, "anchorOffset": 79 } }, "type": "TAG", "mutability": "IMMUTABLE" } } } What I want is to get count of the polarities per tag. … -
Pytest-django admin interface
I have been looking for sources where I would get some examples of testing Django admin interface using pytest. From this question, I got one of the examples that I am following now. However, it is not in pytest, it is also more advanced testing than I am looking for. PS: I am also new guy in testing and kind struggle some parts from there. Anyways, Here is my class in admin.py: class Sample(admin.ModelAdmin): readonly_fields = ("id",) list_display = ("id", "name", "report") list_filter = ("name", "report") search_fields = ("name", "report__name") save_as = settings.SAVE_AS_NEW I want to do something like this: assert readonly_fields == "id" for every field I have following setup in test_admin.py: class MockRequest: pass request = MockRequest @pytest.mark.django_db() class TestSampleAdmin: @pytest.fixture(autouse=True) def _setup_model(self) -> None: self.site = AdminSite() self.model = ModelAdmin(Sample, self.site) def test_recommendation_list_display(self) -> None: view = self.model print(view.readonly_fields) But my printout is empty, while I expect it to be "id" What am I doing wrong and how can I make it work? -
Django : Paginator page exceed max page
I'm currently working on CBV Paginator in Django redirecting last page when given page exceed maximum pages. So, let's say there's Post models that has 200 instances and ListView with paginated_by=10. Then maximum page is 20. So, when I enter URL with "?page=21", it return 404 Error Page. I want to redirect to maximum page. How can I do? -
django - iterate through model in create view & return inline formset
I'm trying to create a formset that will allow the user to set scores for each Priority when creating a new project with the CreateView. The Priority model already has data associated (3 values) foreach Priority that has been created I'm trying to return a char-field in the Project CreateView where the user can enter the score for the Priority. Currently I have the three char-fields showing up in the Project CreateView but I'm getting this error when trying save NOT NULL constraint failed: home_projectpriority.priority_id. I have done some testing & it looks like the ProjectPriority is never having the Project or Priority values set only the score value. I have been struggling for days trying to get this to work. I appreciate all the help. Views.py class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm success_url = 'home/project/project_details.html' def get_context_data(self, **kwargs): ChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('score',), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = ChildFormset(self.request.POST, instance=self.object) else: data['priorities'] = ChildFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() priorities = context["priorities"] self.object = form.save() if priorities.is_valid(): priorities.instance = self.object priorities.save() return super().form_valid(form) Models.py class Priority(models.Model): title = models.CharField(verbose_name="Title", max_length=250) def __str__(self): return self.title class Project(models.Model): name … -
Django ListView how loop in one field in the template?
I have django ListView I know I can loop in it like this {% for i in object_list %} {% i.id %} {% endfor %} I want to loop in one field only {% for i in object_list.id %} {% i %} {% endfor %} -
Dockerize Django app failed with error "/bin/sh: [python3,: not found"
my docker-compose file as below: Django_2.2: build: context: . dockerfile: Dockerfile_Build_Django # Give an image name/tag image: django_2.2:iot container_name: Django_2.2 depends_on: - Django_Mongo_4.2.12 networks: sw_Django: ipv4_address: 192.168.110.12 ports: - 8000:80 restart: always volumes: - type: volume source: vol_django_codes target: /usr/src/app My docker file "Dockerfile_Build_Django" as below: FROM python:3.9.3-alpine3.13 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . . RUN pip install -r requirements.txt # CMD ["python","./IoTSite/manage.py","runserver","0.0.0.0:80"] CMD python ./IoTSite/manage.py runserver 0.0.0.0:80 but when I run "docker-compose up", it failed with below errors, [root@Django]# docker logs Django_2.2 /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found I have been searching for solution for a long time and tried many fixes found via google, no luck so far. any help is appreciated. I feel like getting involved in IT is a waste of life because coding according to guide/user manual for 5 mins then troubleshooting for hours or even days... -
Django template how to compare current item with the previous item in for loop?
My context is an integer array, I'm trying to make a table where every number is compared to the previous one and I will display an arrow indicating if this number has increased or decreased. This is what I'm trying to make {% for number in object_list %} {% if forloop.first %} {% set prev_number = number %} {%endif%}{%endfor%} {% for number in object_list %} {% if number > prev_number %} ... {% else %} ... {% endif %} {% set prev_number = number %} {% endfor %} I know there is not {%set%} tag in django is there any tag equivalent to it? something like {%with%} but doesn't require {% endwith %} or a template tag that does it or I should do it in the views. -
Send email from Django in docker container
I have deployed an existing application inside a docker container. The email service is now working any more. I have exposed the email server port (587), but still not working. This is my django email configuration: # EMAIL handler EMAIL_HOST = "smtp.office365.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "email@email.com" EMAIL_HOST_PASSWORD = "pssword" these are my container exposed ports: docker run -d -p 8001:8020 -p 587:587 --name ... 587/tcp -> 0.0.0.0:587 8020/tcp -> 0.0.0.0:8001 -
whenever i write django-admin,i get this error:ModuleNotFoundError: No module named 'django.utils'
$ django-admin Traceback (most recent call last): File "c:\python\python38\lib\runpy.py", line 194, in _run_module_as_main return run_code(code, main_globals, None, File "c:\python\python38\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Python\Python38\Scripts\django-admin.exe_main.py", line 4, in File "C:\Users\Asus\AppData\Roaming\Python\Python38\site-packages\django_init.py", line 1, in from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils'