Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redis becomes bottleneck when my app has high usage, but metrics seem normal
My project is using Django 3.2 with django-redis and is hosted on Heroku with the Redis Enterprise Cloud add-on for hosting Redis. I'm monitoring my app's performance with Sentry. Whenever my app has high usage, Sentry shows all interactions with Redis as taking a lot more time (could even be up to 10 seconds). The Redis add-on offers metrics and everything looks normal there; read/write latency is max 0.07ms. Adding more dynos (instances) relieves the issue, but I don't understand how all this is connected to Django doing Redis requests (e.g. adding celery tasks). Does anybody have an idea as to what might be going on? -
How to upload image file in post request in python?
class UpdateProfilePictureSerializer(serializers.ModelSerializer): user_uuid = serializers.UUIDField(label=("uuid"), required=True, error_messages={ "invalid": "uuid_require", "required": "uuid_require", "blank": "blank_uuid"}) profile_picture = serializers.ImageField( label=("Profile Picture"), required=True, error_messages={ "invalid": "invalid_profile", "required": "profile_required", "blank": "blank_profile"}) class Meta: model = User fields = ['user_uuid', 'profile_picture'] def validate(self, validated_data): user_uuid = validated_data.get('user_uuid') try: user = User.objects.get(user_uuid=user_uuid) profile_picture = validated_data.get('profile_picture') if (profile_picture is not None): check_validate_image_extension(profile_picture.name) if profile_picture.size > MAX_FILE_SIZE: raise serializers.ValidationError("invalid_image_size") user.profile_picture = profile_picture else: raise serializers.ValidationError("profile_error") user.save() except User.DoesNotExist: raise serializers.ValidationError("user_not_exist") return validated_data This is my serializer which will handle data from request body from a view My question is that I'm writing test cases For this endpoint I want to test it in a test file So what I have to do is make Post request using below code. response = self.client.post(url='api/endpoint', data = {'profile_picture':'', 'user_uuid':'some valid uuid'} My question is what should I pass in profile_picture key. So it will be a valid file. I mean i want to upload image from a path that is app/tests/test.jpg According to serializer what should i pass in. Both key's value's If pass file with open('test.jpg','rb') throwing me error -
Django/Celery: AttributeError when invoking task
I'm defining a Celery task to send bulk emails and am getting an unexpected error when invoking it with Celery. The function works fine by itself without Celery, and line-by-line it works fine in the Django shell, so at this point I am completely lost. models.py: class TimestampedModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class BroadcastMessage(TimestampedModel): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) message_subject = models.CharField(max_length=100) message_text = models.TextField(blank=False, null=False) def __str__(self): return f"Message from {self.teacher} on {self.created_on}: {self.message_subject}" class Teacher(TimestampedModel): studio = models.ForeignKey(Studio, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f"{self.user.username}" class BroadcastMessageTracker(TimestampedModel): message = models.ForeignKey(BroadcastMessage, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) delivered_on = models.DateTimeField(auto_now_add=True) delivery_successful = models.BooleanField(default=True) exception = models.TextField(blank=True, null=True) views.py class BroadcastMessageCreateView(CreateView): model = BroadcastMessage fields = [ "message_subject", "message_text", ] template_name = "studios/broadcastmessage_form.html" success_url = reverse_lazy("dashboard") def form_valid(self, form): teacher = Teacher.objects.get(user=self.request.user) form.instance.teacher = teacher # storing the response so we can action on the saved object before redirecting response = super().form_valid(form) send_bulk_email.delay(self.object.id) return response tasks.py @shared_task(bind=True) def send_bulk_email(self, message_id): message = BroadcastMessage.objects.get(id=message_id) teacher = message.teacher students = Student.objects.filter(teacher=teacher, is_active=True, opt_out_of_receiving_email=False) mail_ctr = 0 for student in students: tracker = BroadcastMessageTracker() tracker.message = message tracker.student = student tracker.delivery_successful = True if student.email: try: ret = send_mail( subject=message.message_subject, message=message.message_text, from_email=teacher.user.email, … -
I use django, postgresql, redis, channels, Docker tools for my project.I have some problem with Docker postgresql image
When I run docker-compose up command This error occured: django.db.utils.OperationalError: could not translate host name "postgres_db" to address: Temporary failure in name resolution My docker-compose.yml file: version: "3.5" services: redis: image: redis:latest networks: - redisnet postgres_db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres django_wsgi: container_name: django_wsgi build: context: . command: uwsgi --socket=:9000 --module=core.wsgi:application --py-autoreload=1 volumes: - .:/code env_file: - .env networks: - webnet - redisnet links: - redis - postgres_db:postgres_db depends_on: - postgres_db django_asgi: container_name: django_asgi build: . # command: python manage.py runserver 0.0.0.0:8002 command: daphne -b 0.0.0.0 -p 8002 core.asgi:application env_file: - .env volumes: - .:/code networks: - webnet - redisnet links: - redis - postgres_db:postgres_db depends_on: - postgres_db nginx: image: nginx:1.15.0 depends_on: - django_asgi - django_wsgi volumes: - ./nginx:/etc/nginx/conf.d - ./static:/static networks: - webnet ports: - "80:80" networks: webnet: redisnet: My Dockerfile: `FROM python:3.8 ENV PYTHONUNBUFFERED 1 ENV REDIS_HOST "redis" RUN mkdir /code WORKDIR /code RUN pip install --upgrade pip RUN pip install psycopg2 COPY requirements.txt /code/ RUN pip install uwsgi RUN apt-get update && apt-get install -y tdsodbc unixodbc-dev RUN pip install -r requirements.txt ADD . /code/` My nginx default.conf file: upstream django_wsgi { server django_wsgi:9000; } upstream django_asgi { server django_asgi:8002; … -
Django static files load combined with css function url() generates weird & string in paths
I have deployed a django website to digital ocean, and storing static files into AWS buckets. So far so good, 'some' of my static files are loading correctly. For example, files like: <link rel="icon" href="{% static 'images/logo.svg' %}"> <script src="{% static 'js/jquery-3.3.1.slim.min.js' %}"></script> are loaded totally fine. The generated url when inspecting chrome's dev tools for, say the above logo is: https://<REGION>.digitaloceanspaces.com/<BUCKET NAME>/static/images/logo.svg?AWSAccessKeyId=<ACCESS KEY ID>&Signature=<AWS SECRET> which is correct, and the logo shows indeed on my webpage. Now, the weird thing is that I have some inline <style> blocks for which 'it nearly works'. Let me explain, I have the following piece in my html: <style> header#background-image { background-image: url("{% static 'images/header-background.svg' %}"); } </style> which is rendered as (again looking at chrome's dev tool): <style> header#background-image { background-image: url("https://<REGION>.digitaloceanspaces.com/<BUCKET NAME>/static/images/header-background.svg?AWSAccessKeyId=<ACCESS KEY ID>&amp;Signature=<AWS SECRET>&amp;Expires=1673362355"); } </style> The reason I mentioned this is 'nearly' ok is because I noticed the &amp; pieces of string in the generated url. If I correct those changing them to simple & and go to the modified link I indeed see my background image... This is so weird and drives me crazy, anybody got an idea of what is happening? -
Django custom auth backend not triggering when user does not exists
In Django==3.1.6, using a custom auth backend for insensitive login does not work properly. It only prints something when the user exists (lowercase). Whenever I enter a uppercase, it doesnt work and prints nothing. In my settings.py AUTHENTICATION_BACKENDS = [ 'users.UserEmailBackend.UserEmailBackend', 'django.contrib.auth.backends.ModelBackend', The auth backend # gets the user_model django default or your own custom from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.db.models import Q # Class to permit the athentication using email or username # requires to define two functions authenticate and get_user class UserEmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() print("AAAAA") # write to a file try: # below line gives query set,you can change the queryset as per your requirement username = username.lower() user = UserModel.objects.filter( Q(username__iexact=username) | Q(email__iexact=username) ).distinct() except UserModel.DoesNotExist: return None if user.exists(): ''' get the user object from the underlying query set, there will only be one object since username and email should be unique fields in your models.''' user_obj = user.first() if user_obj.check_password(password): return user_obj return None else: return None def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None You see there's a print("AAAAA") in the authenticate method. This is only called when … -
Dependant Drop Down in Java Script
I had made a form which include dependant drop down list but while I am selecting the dependant dropdown its just passing the index value. How can i add a value to the dependant dropdown list HTML SECTION <div class="form-row m-b-55"> <div class="name">Department</div> <div class="value"> <div class="input-group"> <div class="rs-select2 js-select-simple select--no-search"> <select name="department" id="department"> <option disabled="disabled" selected="selected">Select Department</option> </select> <div class="select-dropdown"></div> </div> </div> </div> </div> <div class="form-row m-b-55"> <div class="name">Course</div> <div class="p-t-15"> <div class="input-group"> <div class="rs-select2 js-select-simple select--no-search"> <select name="course" id="course"> <option disabled="disabled" selected="selected">Select Course</option> </select> <div class="select-dropdown"></div> </div> </div> </div> </div> JAVA SCRIPT var courseObject = { "Commerce":["B.Com CA","B.Com IF","B.Com Finance","M.Com"], "Computer Science" : ["B.Sc Computer Science","BCA","M.Sc Computer Science"], "Physics":["B.Sc Physics","M.Sc Physics"], "Chemistry":["B.Sc Chemistry","M.Sc Chemistry"] } window.onload = function(){ var departmentSel = document.getElementById("department"); var courseSel = document.getElementById("course"); for (var x in courseObject){ departmentSel.appendChild(new Option(x,x)); } departmentSel.onchange=function(){ courseSel.length = 1; for (var y in courseObject[this.value]){ courseSel.appendChild(new Option(courseObject[this.value][y],y)); } } } OUTPUT I need to get value as course name not just as id -
How to filter an object with ManyToMany field?
I'm building a view where I add a product to a cart. To do this I create an instance of a CartItem model wich is related to a cart, a product and has variations (color, size...). When the instance of CartItem is created I want to check if it alredy exists to know if I need to increment its stock or create a new one. So I first check for one with the same cart and product (ok so far). But then I don't know how to check if one that has the same variations exists (which is a ManytoMany fied). the view : def add_to_cart(request, product_id): product = Product.objects.get(id = product_id) variation_list = [] if request.method == "POST": print(request.POST) for item in request.POST: key = item value = request.POST[key] try: variation = Variation.objects.get(product = product, variation_category__iexact = key, variation_value__iexact = value) variation_list.append(variation) except: pass print(variation_list) try: cart = Cart.objects.get(cart_id=_get_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create(cart_id=_get_cart_id(request)) cart.save() try: cart_item = CartItem.objects.get(product=product,cart=cart) # How to filter cart_item so I know if it matches with variation_list cart_item.product_quantity +=1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create(product=product,cart=cart) cart_item.save() for variation in variation_list: cart_item.variation_list.add(variation) return redirect('cart') the Product model: class Product(models.Model): name = models.CharField(max_length=50, unique=True) slug = … -
Only able to get /article/1/ to load. /article/2/ displays a 404
Each page in /articles/x/ represents one article, each article has its own article content which is in the ArticleContent model which is structure like id tag css_id css_class content article_id (foreign key that points to Article Table) 1 p blab la 1 2 p bahaofs 2 actual database has more records for multiple article_ids loading /article/1/ works exactly as expected with article content ArticleContent Model class ArticleContent(models.Model): lemons = models.ForeignKey('Article', on_delete=models.CASCADE) order = models.IntegerField(blank=True) tag = models.CharField(max_length=20) css_id = models.CharField(max_length=100, blank=True) css_class = models.CharField(max_length=100, blank=True) extra = models.TextField(max_length=200, blank=True) content = models.TextField(max_length=2000, blank=True) Article Model class Article(models.Model): def __str__(self) -> str: return self.title title = models.TextField(max_length=200) slug = models.SlugField(max_length=100, blank=True) preview = models.TextField(max_length=500) hasimage = models.BooleanField(default=True) image = models.ImageField(upload_to='articles/static/articles/images', blank=True) date = models.DateTimeField(blank=True) url = models.TextField(blank=True) alt = models.TextField(max_length=1000, blank=True) urls.py app_name = 'article' urlpatterns = [ path('', views.index, name='index'), path('articles/<int:pk>/', views.DetailView.as_view(), name='article_detail'), ] views class DetailView(generic.DetailView): model = ArticleContent template_name = 'articles/article_detail.html' def get_queryset(self, *args, **kwargs): article_content = ArticleContent.objects.filter(lemons_id=self.kwargs['pk']) return article_content def get_context_data(self, *args, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in settings context['ordered_article_content'] = self.get_queryset() context['kwargs'] = self.kwargs['pk'] context['is_header_on'] = True context['is_footer_on'] = True context['header_links'] = HeaderLinks.objects.all() context['footer_links'] = … -
Django Rest Framework nested writable Serializers
I want create a writable multi Level Serializer with 2 and more Levels. But when I use the code under. I get Response BAD REQUEST 400. When I exclude the TaskSerializer its working (1Level) but more nested its not working. What I can do that it works? Thanks in advance. views.py class BoardView(APIView): def get(self, request, email): user = User.objects.get(email=email) boards = Boards.objects.filter(board_creator=user.id) serializer = BoardsSerializer(instance=boards, many=True) return Response(serializer.data) def post(self, request, email): response = Response() data = request.data['board'] user = User.objects.filter( email=data['board_creator']).first() if user is None: response.data = { 'detail': 'User not found' } response.status_code = status.HTTP_404_NOT_FOUND return response boards_by_user = Boards.objects.filter(board_creator=user.id) board_len = boards_by_user.filter( board_name=data['name']) if len(board_len) > 0: response.data = { 'detail': 'Board already exists' } response.status_code = status.HTTP_409_CONFLICT return response data['board_creator'] = user.id print(data) serializer = BoardsSerializer(data=data) if serializer.is_valid(): serializer.save() response.status_code = status.HTTP_201_CREATED response.data = { 'detail': 'Board created successfully' } return response response.status_code = status.HTTP_400_BAD_REQUEST return response model.py class Boards(models.Model): board_name = models.CharField(max_length=255, null=None) board_creator = models.ForeignKey(to=User, on_delete=models.CASCADE) def __str__(self) -> str: return str(self.board_name) class Columns(models.Model): column_name = models.CharField(max_length=255, null=None) board = models.ForeignKey( to=Boards, on_delete=models.CASCADE, related_name='columns') def __str__(self) -> str: return str(self.column_name) class Tasks(models.Model): task_title = models.CharField(max_length=255, null=None) task_description = models.TextField(null=True, blank=True) task_created = models.DateTimeField(default=timezone.now) … -
Django project working on IP address of droplet. But, it does not work on custom domain
I have my domain on GoDaddy and my hosting setup in DigitalOcean. So after I setup my basic django project, I used a droplet to deploy the code to an IP address. When I run this command, my project was running at my [IP_ADDRESS]:8000: gunicorn -w 2 -b 0.0.0.0:8000 --chdir /home/USER_NAME/projectdir/test_project test_project.wsgi Then, I put the three digital ocean nameservers in GoDaddy. I also modified the settings.py file by using the ALLOWED_HOSTS variables: ALLOWED_HOSTS = ['IP_ADDRESS', 'www.DOMAIN_NAME', 'DOMAIN_NAME'] My Nginx configuration looks something like this: server { listen 8000; listen 80; server_name IP_ADDRESS DOMAIN_NAME www.DOMAIN_NAME; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/USER_NAME/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } But still, I get 'This Site can't be reached'. I also checked that the nameservers have been updated by using https://lookup.icann.org/en. So I don't know where the problem lies. If you need any additional information let me know. Thank you -
Using Modelform with ModelChoicefield does not work for me, gives undefined error when submitting the form
I am trying to use a form that adds data to the model RaportProductie using AJAX. In the form I have 2 dropdown inputs that take data from the ManoperaRaportareBloc model. These are the attributes from ManoperaRaportareBloc : categorie_lucrare and subcategorie_lucrare When I submit the form it shows an error with undefined. Please help. ty. forms.py: class RaportProductieForm(forms.ModelForm): data = forms.DateField(initial=datetime.date.today) categorie_lucrare = forms.ModelChoiceField(queryset=ManoperaRaportareBloc.objects.all().values_list('categorie_lucrare', flat=True)) subcategorie_lucrare = forms.ModelChoiceField(queryset=ManoperaRaportareBloc.objects.all().values_list('subcategorie_lucrare', flat=True)) class Meta: model = RaportProductie fields = ['lucrare', 'data', 'tip', 'subcontractor', 'obiectiv', 'categorie_lucrare', 'subcategorie_lucrare', 'um', 'cantitate', 'valoare_prod'] views.py: def raportproductie_create_view(request): # request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": # get the form data form = RaportProductieForm(request.POST) # save the data and after fetch the object in instance if form.is_valid(): instance = form.save() # serialize in new friend object in json ser_instance = serializers.serialize('json', [ instance, ]) # send to client side. return JsonResponse({"instance": ser_instance}, status=200) else: # some form errors occured. data = { 'result': 'error', 'message': 'Form invalid', 'form': 'oops.' } return JsonResponse(data, status=400) # some error occured return JsonResponse({"error": ""}, status=400) template.html: $("#friend-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the … -
Why is app.urls not found?(Django Python)
I’m making my first django based backend server and I registered the urls for each app like urlpatterns = [ path('admin/', admin.site.urls), path('backfo/', include('backfo.urls')), path('commun/', include('commun.urls')), path('starts/', include('starts.urls')), path('travleres/', include('travleres.urls')), path('starts/', include('starts.urls')), path('new/', include('new.urls')), path('joint/', include('joint.urls')), ] Then I get this error in cmd saying -> ModuleNotFoundError: No module named 'backfo.urls' I don’t get what went wrong and if you need more code I’ll post it on. -
Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused
I am trying to run celery without running RabbitMQ. But this repo I am working on has these two lines CELERY_BROKER_URL = 'amqp://localhost' # for RabbitMQ CELERY_RESULT_BACKEND = 'rpc://' # for RabbitMQ which gives me this error consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused. How can I run celery successfully without RabitMQ I tried running celery without RabbitMQ but failed -
Django - Prefill admin creation form with inline forms
I'm trying to create a form in Django admin, that, when you create a new entry, will take the latest entry, and fill the new entry with that data. E.g. (Book and Author are just examples) class Book(models.Model): id = models.Autofield(primary_key=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) name = models.Charfield(max_length=200) class Author(models.Model): id = models.Autofield(primary_key=True) name = models.Charfield(max_length=200) I then added this to the admin page: class BookInline(StackedInline): model = Book extra = 0 class AuthorAdmin(ModelAdmin): inlines = [BookInline] admin.site.register(Author, AuthorAdmin) Now when I create a new Author, I want the form to be filled in with the last created author and his books So if said author had 5 books, it would now fill this form with the name of that author, and also add the 5 books. I was able to fill the author form by adding this to the AuthorAdmin class: def get_changeform_initial_data(self, request): return model_to_dict(Codebook.objects.all().get())#Temp But the books are not filled this way. Is it somehow possible, to pass the books into the inline forms? (Running Django 3.2 and Python 3.9) -
Correct way to add dynamic form fields to WagtailModelAdminForm
I have a use case where I need to add dynamic form fields to a WagtailModelAdminForm. With standard django I would normally just create a custom subclass and add the fields in the __init__ method of the form. In Wagtail, because the forms are built up with the edit_handlers, this becomes a nightmare to deal with. I have the following dynamic form: class ProductForm(WagtailAdminModelForm): class Meta: model = get_product_model() exclude = ['attributes', 'state', 'variant_of'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance: self.inject_attribute_fields() def inject_attribute_fields(self): for k, attr in self.instance.attributes.items(): field_klass = None field_data = attr.get("input") field_args = { 'label': field_data['name'], 'help_text': field_data['help_text'], 'required': field_data['is_required'], 'initial': attr['value'], } if 'choices' in field_data: field_args['choices'] = ( (choice["id"], choice["value"]) for choice in field_data['choices'] ) if field_data['is_multi_choice']: field_klass = forms.MultipleChoiceField else: field_klass = forms.ChoiceField else: typ = field_data['attr_type'] if typ == 'text': field_klass = forms.CharField elif typ == 'textarea': field_klass = forms.CharField field_args['widget'] = forms.Textarea elif typ == 'bool': field_klass = forms.BooleanField elif typ == 'int': field_klass = forms.IntegerField elif typ == 'decimal': field_klass = forms.DecimalField elif typ == 'date': field_klass = forms.DateField field_args['widget'] = AdminDateInput elif typ == 'time': field_klass = forms.TimeField field_args['widget'] = AdminTimeInput elif typ == 'datetime': field_klass = forms.DateTimeField … -
Only allow specific url
The user can type an URL like this https://music.apple.com/us/artist/billie-eilish/1065981054. But the us in the URL can also be de or ru (depending on artist). Some URLs can also be written like this https://www.example.com. How can I check if the users typed URL is build like this example URL? -
Download videos from a remote site with PyhtonDownload videos from a remote site with Pyhton
Hello I want to download videos from x one site locale with pyhton, when I search the Internet I only download the video at the given address, can you help this process how to pull videos from http traffic while browsing within a single site Hello I want to download videos from a site x locale with pyhton, when I search the Internet, it only downloads the video at the given address, how can you help me pull videos from http traffic while browsing within a single site? -
Send data in a complete tree structure using django serializers
I have 2 models: Folder and Entity. class Folder(models.Model): name = models.CharField(max_length=255, null=False, blank=False) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name="child") class Entity(models.Model): name = models.CharField(max_length=255, null=False, blank=False) folder = models.ForeignKey('Folder', on_delete=models.SET_NULL, null=True, blank=True, related_name="entities") So a folder can have both child folders and entities. Now I want to send the data in a tree structure and I have written a serializer for it. class ListFolderSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Folder fields = ['id', 'name', 'children'] def get_children(self, instance): child_folders = Folder.objects.filter(parent=instance).order_by("name") child_entities = Entity.objects.filter(folder=instance).order_by("name") all_children = [] if child_folders or child_entities: child_folders_data = ListFolderSerializer(child_folders, many=True).data child_entities_data = ListEntitySerializer(child_entities, many=True).data all_children.extend(child_folders_data) all_children.extend(child_entities_data) return all_children else: return None class ListEntitySerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ['id', 'name'] This is working fine but as the data keep on increasing the time to get this tree is increasing. So any optimized way to do this? -
Display records with respect to their id's in Django
My Django application includes a page named list in which list creates against a user to after analysis of .pcap file: The problem is I want to display the results on the basis of id in hash table. The id in hash_mod table has one to many relationships. Therefore, It'll be easy for me to fetch the results on the basis of id. How I will use the primary key (id in hash_mod) table to link through foreign key (hash_id in demo) table to fetch the results. I have also share the image url to view the list.html what it looks like. In list.html there is a button named "View" which is using the post method. There is for loop in list.html which recognize the total number of files analyzed by a user. When a user will analyze a file an id and hash will create in "hash_mod" table which I have mentioned below. Id will treat as a foreign key in another table, so I want to fetch the result witch respective to their primary key id and foreign key id. if anyone have still problem to understand the question anyone can ask. But please don't give a negative … -
How can I filter groups based on user_id in django-template-language
how can I filter the groups based on the user in Django-template-language with if else condition <tbody> {% for group in groups %} <tr> <td>{{group.name}}</td> <td><input type="checkbox" name="add_group[]" id="group-{{group.id}}" value=" {{group.id}}" checked ></td> </tr> {% endfor %} </tbody> -
How to log requests in Django Rest Framework?
I am using middleware to log requests: class RequestsMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): logger.info(request) logger.debug(request.body) response = self.get_response(request) return response If I send an image to the server: response = self.client.post( self.url, data={ 'id': user_id, 'photo': open(f'{test_data}/image.jpeg', 'rb'), 'licenses': [f'{self.license_id}'],}, format='multipart', HTTP_AUTHORIZATION=f'{token}') logger.debug(request.body) shows something like: b'--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="id"\r\n\r\ndbdeb624-fba8-4718-819c-b6c4eb358dbf\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="photo"; filename="image.jpeg"\r\nContent-Type: image/jpeg\r\n\r\...\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="licenses"\r\n\r\ncbe1ed8f-52eb-4089-b66b-ea01fc9e450g\r\n--BoUnDaRyStRiNg--\r\n' This message is unreadable. Is there a way to format the message? -
Field 'id' expected a number but got 'POST'
This is my view: def edit_bendrija_view(request, bendrija_id): """ A view to edit Bendrijos name """ bendrija = get_object_or_404(Bendrija, id=bendrija_id) if request.method == 'POST': existing_bendrija = BendrijaForm(request.POST, instance=bendrija) if existing_bendrija.is_valid(): existing_bendrija.save() messages.success(request, "Your Bendrija Was Updated") return redirect(reverse('bendrijos')) else: messages.error(request, "Your Bendrija Was Not Updated") existing_bendrija = BendrijaForm(instance=bendrija) context = { 'existing_bendrija': existing_bendrija, "bendrija": bendrija, } return render(request, 'home/edit_bendrija.html', context) I am trying to edit an existing model using a form, the model only has 2 CharFields so its very simple, everything works up until I click the submit button, then the error that is the title comes up, and I am completely lost, especially because the error says the problem is on the "bendrija = get_object_or_404(Bendrija, id=bendrija_id)" line, this is the form if you are wondering: <form action="POST"> {% csrf_token %} <div class="row"> {{ existing_bendrija.name | as_crispy_field }} </div> <div class="row"> {{ existing_bendrija.address | as_crispy_field }} </div> <div> <p> <button type="submit" class="btn btn-success">Submit</button> </p> </div> </form> any suggestions? because I have 0 idea why the id is getting the request method and not the model id -
Pylint is not able to locate the model in the context of the views.py file
I'm using VSCode and the Pylint that ships with it, i.e., no extension. Everything has been running smooth for many months and I've never had an issue with Pylint presenting weird alerts. I recently started learning Django and today when following the official Django Documentation tutorial part 4 pylint could not recognize a couple of statements related to a model. Pylint can't recognize the (choice_set) method below selected_choice = question.choice_set.get(pk=request.POST['choice']) Pylint can't recognize (question.id) below return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) The errors I get from pylint are below choice_set: Unknown Cannot access member "choice_set" for type "Question" Member "choice_set" is unknownPylancereportGeneralTypeIssues and id: Unknown Cannot access member "id" for type "Question" Member "id" is unknownPylancereportGeneralTypeIssues At first I thought the issue might've been I'd forgot to cross reference the Question and Choice models, but this is not the case. For reference, here are the related files for the project #models.py from django.db import models from django.utils import timezone import datetime class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text #views.py from .models import Choice, … -
ValueError: Expected a boolean type django and mysql
I can't start my django with mysql, it's inside docker and it gives me a valueerror that I don't know how to fix self.raise_on_warnings = config["raise_on_warnings"] File "/usr/local/lib/python3.10/site-packages/mysql/connector/abstracts.py", line 937, in raise_on_warnings raise ValueError("Expected a boolean type") ValueError: Expected a boolean type