Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are my Docker containers not taking advantage of added vCPUs?
We have a Docker app with three containers (Django, PostgreSQL, and nginx) that's been running slowly. I am trying to speed up the app by brute force - quadrupling RAM and CPU on the hosting virtual machine. However, I'm not seeing any real benefit from the increase in vCPUs - the overall CPU usage seems to have dropped proportionally, so my peaks at nearly 100% on the 2-vCPU VM have gone down to about 25% on the new 8-vCPU VM. Naturally, the app is not running faster. I'm using Desktop 4.15.9 (93002) on a cloud-hosted virtual machine with 32 GB RAM and 8 vCPUs running Windows Server 2022 Standard 21H2. What might I be doing wrong or missing? As an experiment, I used docker update to try and set how many and which CPUs were being used by each container: docker update --cpus=2 --cpuset=4-5 django docker update --cpus=2 --cpuset=6-7 pg I expected that more CPU usage would be shown for individual logical CPUs in Task Manager and Resource Monitor. However, I did not see any difference in the pattern of usage when I changed cpusets and repeated my slow operation, so I'm ... confused. FWIW, docker stats shows CPU% going … -
Django: Filter ManyToMany Relationship and must include Parent
If User Selects Product Sub Category as Private Car and State as Andaman And Nicobar Islands, I want to Display only those unique RTOs which matches in both Product Sub Category and State. View: product_sub_cat_data = ProductSubCategory.objects.filter( product_sub_category=selected_sub_product_array[2].strip(), product=product_data[0].id ) state_data = State.objects.filter(state=selected_state) rto_grouping_data = RtoGrouping.objects.filter(product_sub_category=product_sub_cat_data[0].id, group__rto_state=state_data[0].id).distinct() Getting Output as: AN01, AN02, DD02, DD03, LD01, PY01, PY02, PY03, PY04, UP14, UP16, DN09, UP61, DD09, UP05, UP07, UP10, UP06, UP08, UP04, UP09, DN13, UP38, LD02, LD03, LD04, LD05, LD07, LD08, LD09, PY05 While the Desired output is: AN01, AN02 (as only these 2 RTOs belong to Andaman And Nicobar Islands) My 4 Models: Product Sub Category class ProductSubCategory(models.Model): class Meta: db_table = 'product_sub_category' verbose_name_plural = 'Product Sub Category' product_sub_category = models.CharField(max_length=256) product = models.ForeignKey(Product, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now=True, editable=False) modified_at = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=STATUS_CHOICES, default=1) is_deleted = models.BooleanField(default=0) Rto Grouping class RtoGrouping(models.Model): class Meta: db_table = 'rto_grouping' verbose_name_plural = 'Rto Grouping for Payout' unique_together = [['group_name', 'from_date', 'product_sub_category']] from_date = models.DateField() to_date = models.DateField() insurer = models.ForeignKey(Company, null=True, on_delete=models.PROTECT) group_name = models.CharField(max_length=256) group = models.ManyToManyField(Rto, related_name='group') product_sub_category = models.ForeignKey(ProductSubCategory, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True) is_verified = models.BooleanField(default=0) status = models.IntegerField(choices=STATUS_CHOICES, default=1) is_deleted = models.BooleanField(default=0) RTO class Rto(models.Model): … -
Django - Allow duplicate user's emails in the grand User model, but unique in its extended models?
Django - Allow duplicate user's emails in the grand User model, but unique in its extended models? I'm working on a project in Django which have a User model extend from AbstractBaseUser; and 2 models extend from User (Customer and Technician). Its working all fine when creating a user or customer or technician. However, whenever I register a new user as either customer or technician (/api/customer/register/ or /api/customer/register/) with the same email (because I define email as username USERNAME_FIELD), it returned me with "This email is already exists." Sure, I understand this since I define the UNIQUE constraint on username and email field in the User model. I want customer to be unique in its own model but not in User model, same for technician. Just like when you sign up for Uber or DoorDash, either you want to be a customer or you want to be a driver or you could be both. AND you could use the same email address to sign up for both. BUT, you cannot use the same email address to sign up again, if you are already signed up with that email as a customer or a driver I have tried to tweak around … -
Like button in Django + AJAX
i want to implement like button in my project. I want to do this without page reloading, so i googled and decided to use JS's AJAX, but there is one problem, i absolute zero in Javascript and i don't know how this s*** works. So, take a look at my code, i hope someone could help me Or there is dead end for me Thanks in advance :) Here's views.py def like_place(request, pk): print(request.method) if request.method == "POST": place = Place.objects.get(id=pk) user = request.user if user in place.place_likes.all(): place.place_likes.remove(user) else: place.place_likes.add(user) place_likes_count = place.place_likes.count() return JsonResponse({'likes_count': place_likes_count}) else: return JsonResponse({'error': 'Invalid request.'}, status=400) Here's my html page <div class="search-and-filters"> <form action="" method="GET"> <input type="text" name="search_query" placeholder="Search by cafe name"> <select name="country_filter" style="text-align: center;"> <option value="">Search by country</option> </select> <select name="city_filter"> <option value="">Search by city</option> </select> <button type="submit">Find Place</button> </form> </div> <div class="feed-container"> <div class="comments-section"> <div class="comment"> <div class="comment-nickname">Никнейм</div> <div class="comment-details">commented at (название заведения)</div> <div class="comment-text">Комментарий</div> <div class="comment-date">3 дня назад</div> </div> </div> <div class="posts-section"> <div class="post"> {% for place in places %} <div class="post-title"><a href="{% url 'place_page' place.id %}" style="color: black;">{{ place.place_name }}</a></div> <form method="post"> {% csrf_token %} <button class="button button-like like-button" data-place-id="{{ place.id }}" style="border: none; background-color: transparent" name="like-button"> <i … -
Django ORM multiple JOINs
I have this SQL query and need to do in django orm select count(*), tabel_d.name from tabel_a join tabel_ on tabel_b.id = tabel_a.b_id join tabel_c on tabel_c.b_id = tabel_b.id join tabel_d on tabel_d.id = tabel_c.d_id group by tabel_d.id How to do that? -
Got "POST http://localhost:8000/cart/add/ 500 (Internal Server Error)" Error when send POST Request through Ajax in Django
When sending Cart data through Ajax on the project details page on Add to cart button. Error show on Console Log , Error { POST http://localhost:8000/cart/add/ 500 (Internal Server Error) } Error Log Image Urls.py: path('add/', cart_add, name='cart-add') Views.py: def cart_add(request): cart = Cart(request) if request.POST.get('action') == "POST": print("oky") product_id = int(request.POST.get('product_id')) product_quantity = int(request.POST.get('product_quantity')) product = get_object_or_404(Product, id=product_id) cart.add(product=product, quantity=product_quantity) response = JsonResponse({"Prodct Name":product.name,"product Qantity":product_quantity}) return response Ajax in HTML File: <script> $(document).on('click','#add-button',function(e){ e.preventDefault(); console.log('{{csrf_token}}') $.ajax({ method: "POST", url : '{% url "cart-add" %}', data:{ product_id: $('#add-button').val(), product_quantity: $('#select option:selected').text(), csrfmiddlewaretoken : '{{csrf_token}}', action : 'post' }, success:function(json){ console.log(json) }, error:function(xhr,errmsg,err){ } }) }) </script> -
I try to add custom command in DRF not work
My manage.py #!/usr/bin/env python # pylint: skip-file """Django's command-line utility for administrative tasks.""" import os import sys def main() -> None: """Run administrative tasks.""" os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "microservice_authentication.settings" ) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": from management.commands.create_user_and_db import CreateUserAndDbCommand # Add your custom management command to the commands dictionary if len(sys.argv) > 1 and sys.argv[1] == "create_user_and_db": print("reached") commands = {"create_user_and_db": CreateUserAndDbCommand()} else: commands = { "create_user_and_db": CreateUserAndDbCommand(), # Add other default Django management commands here, if needed } print("reach") main() My custom command py file # create_user_and_db.py from django.core.management.base import BaseCommand from scripts.create_user_and_db import create_database, create_user_and_grant_privileges class CreateUserAndDbCommand(BaseCommand): help = 'Create the database and user role if they do not exist.' print("reached") def handle(self, *args, **kwargs): print("not reached") create_database() create_user_and_grant_privileges() custom command is not work i get below error $ python manage.py create_user_and_db reached reached reach Unknown command: 'create_user_and_db'. Did you mean create_command? Type 'manage.py help' for usage. -
How can I make a history for a model ManyToManyField in Django?
class Enterprise(models.Model): name= models.CharField(max_length=30) address = models.CharField(max_length=100) phone = models.CharField(max_length=30) def __str__(self): return self.nombre class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) address = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone = models.CharField(max_length=30) enterprise = models.ManyToManyField(Enterprise, related_name='client') def __str__(self): return self.first_name For example: If when creating the client I choose Enterprise 1, when I update it (I already have views) to Enterprise 2, I want the history to tell me that it was previously related to Enterprise 1. I tried this: https://django-simple-history.readthedocs.io/en/latest/ but it didn't work. I also tried with this but it didn't work.: class HistoricalRecord(models.Model): ACTION_CHOICES = [ ('C', 'Created'), ('U', 'Updated'), ('D', 'Deleted'), ] model_name = models.CharField(max_length=100) record_id = models.IntegerField() action = models.CharField(max_length=1, choices=ACTION_CHOICES) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.get_action_display()} {self.model_name} {self.record_id}"` -
Preventdefault while adding comment using ModelForm
I'm new to ajax, jquery, so I want to stop refresh the page everytime I comment on the post. main.html <div class="extra content"> <div class="mb-5"> </div> <button class="cmt_btn ui button mb-5">show / hide comments</button> <div class="comment-box"> {% if obj.comment_set.all %} {% for c in obj.comment_set.all %} <div class="ui segment mb-5"> <img class="ui avatar image" src={{c.user.avatar.url}}> <span>{{ c.user }}</span> <div class='mt-5'>{{ c.body }}</div> </div> {% endfor %} {% endif %} </div> <form action="" method="POST" class='ui fluid form'> {% csrf_token %} <input type="hidden" name="post_id" value={{obj.id}}> {{ c_form }} <button type="submit" name="submit_c_form" class="ui primary button mt-5 w-full">Send</button> </form> </div> form.py class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'})) class Meta: model = Comment fields = ('body',) views.py @login_required def post_comment_create_and_list_view(request): if not request.user.is_authenticated: return redirect('%s?next=%s' % (reverse("account_login"), request.path)) profile = Profile.objects.get(user=request.user) qs = Post.objects.filter( Q(author__user__in=profile.friends.all()) | Q(author=profile) ).order_by("-created") # initials c_form = CommentModelForm() if 'submit_c_form' in request.POST: c_form = CommentModelForm(request.POST) if c_form.is_valid(): instance = c_form.save(commit=False) instance.user = profile instance.post = Post.objects.get(id=request.POST.get('post_id')) instance.save() return redirect('posts:main-post-view') context = { 'qs': qs, 'profile': profile, 'c_form': c_form, } return render(request, 'posts/main.html', context) models.py class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) script in side the … -
Unresolved attribute reference 'objects' for class 'Item' [closed]
When I try to count no of rows from a table in django then it shows Un-resolve attribute error and dose not show the message. item_count = Item.objects.count() context = { 'item_count': item_count } return render(request, 'index.html', context)' i tried this in views -
DJango returns seemingly erroenous 301
I am working on a Password-Reset view with Django Rest Framework, using a generic UpdateAPIView. It should expose a PUT method, but no matter when type of request I throw at it, it returns 301 Moved Permanently. I've read that setting TRAILING_SLASH = True can cause this behavior, but that doesn't apply here, as the request URL ends with a slash http://localhost/api/auth/password/reset/ urlpatterns = [ path('auth/password/reset/', views.ResetPasswordView.as_view(), name='password_reset'), ] class ResetPasswordView(generics.UpdateAPIView): serializer_class = serializers.ResetPasswordSerializer model = User permission_classes = [permissions.AllowAny,] def get_object(self, queryset=None): email_address = account_models.EmailAddress.objects.filter(reset_key=self.request.POST.get('key')).values()[0] return User.objects.filter(id=email_address['user_id'])[0] def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): return Response({'validation_error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) if not serializer.data.get('new_password') == serializer.data.get('new_password2'): return Response({'new_password': ['Passwords must match.']}, status=status.HTTP_400_BAD_REQUEST) try: validate_password(serializer.data.get('new_password')) except Exception as ex : return Response({'invalid_password': [ex]}, status=status.HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get('new_password')) self.object.reset_key = None self.object.save() return Response({ 'status': 'success', 'code': status.HTTP_200_OK, 'message': 'Password updated successfully', 'data': [] }) class EmailAddress(ExportModelOperationsMixin('email_address'), models.Model): user = models.OneToOneField(to=User, related_name='email_address', on_delete=models.CASCADE) email = models.EmailField(max_length=255) reset_key = models.CharField(default=None, null=True, max_length=255) reset_sent = models.DateTimeField(null=True) class Meta: verbose_name = _("email address") verbose_name_plural = _("email addresses") unique_together = [("user", "email")] def __str__(self): return self.email def save(self, *args, **kwargs): verify_email_signal.send(sender=self.__class__, email=self.email, key=self.verify_key) self.verification_sent = timezone.now() super(EmailAddress, self).save(*args, **kwargs) -
Cannot start docker for django
Hi I am trying to install django with Docker and I cant not run the Django application. But my postgresql still work normally Here is my terminal My Dockerfile # docker/app/Dockerfile FROM python:3.11-alpine LABEL maintainer="Tran Son Hoang son.hoang01@gmail.com" ENV PYTHONUNBUFFERED=1 \ PROJECT_DIR=/app/ COPY . ${PROJECT_DIR} #COPY --chmod=755 docker/app/entrypoint.sh /poinofsale_entrypoint.sh WORKDIR ${PROJECT_DIR} EXPOSE 8000 8000 RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev curl bash RUN pip install --no-cache-dir pipenv RUN pipenv install --system --deploy RUN pipenv --clear #ENTRYPOINT ["sh", "/poinofsale_entrypoint.sh"] CMD ["gunicorn", "-c", "docker/app/gunicorn.py"] My docker-compose.yml file # docker-compose.yml version: '3.9' services: # Django application app: build: context: . dockerfile: docker/app/Dockerfile container_name: poinofsale-app ports: - "8000:8000" env_file: - .env volumes: - ./:/app/ depends_on: - postgres # PostgreSQL Database postgres: image: postgres:15-alpine container_name: django-docker-db ports: - "5432:5432" env_file: - .env volumes: - pgdata:/var/lib/postgresql/data restart: unless-stopped volumes: pgdata: networks: default: name: django-network The result is like above, even I run successfull but when I open my Docker desktop, the result is like image below The status is always Exited for django app. Anyone have hint for this? I have tried to research and most of the result is same with my configuration. -
Django Python : Manager isn't accessible via model instances
I'm trying to query an object set and use the number of the amount of objects to do a for loop that will present parameters of each object. I'm using a 2D array to store the parameters so they can be presented respective to their object. I would like not just a solution but a better way in general of doing this .p.s. I'm new to django This is the code from views.py def flashcard(response): form = Flashcard_verif(response.POST) if response.method == "POST" and form.is_valid(): head = form.cleaned_data["header"] ques = form.cleaned_data["question"] ans = form.cleaned_data["answer"] flashcard_data = Flashcard(header=head, question=ques, answer=ans) # this is where the error is occuring flashcard_obj = Flashcard(header=head, question=ques, answer=ans).objects.all() rawHeader, rawQuestion, rawAnswer = Flashcard(header=head, question=ques, answer=ans).flash_format() flashcard_data.save() if len(flashcard_lib) > 1: for i in range(0, len(flashcard_lib), 1): flashcard_lib.append([rawHeader, rawQuestion, rawAnswer]) print(flashcard_lib) return render(response, "main/Flashcard.html", { "form":form, "Flashcard_lib":flashcard_lib, "flashcard":flashcard_obj}) else: flashcard_lib.append([rawHeader, rawQuestion, rawAnswer]) print(flashcard_lib) return render(response, "main/Flashcard.html", { "form":form, "header":rawHeader, "question":rawQuestion, "answer":rawAnswer }) else: form = Flashcard_verif() return render(response, "main/Flashcard.html", { "form":form}) This is my template that utilises the 2d array: <div class="flashcard-view" id="flash" style="visibility: hidden"> {% if Flashcard_lib|length >= 2 %} {% for i in flashcard_obj %} <div class="flashcard"> {{ i.0 }} {{ i.1 }} {{ i.2 }} … -
Updating urlpatterns for django-smart-selects
I am attempting my first django project by building on top of the polls example from the django documentation. I would like to add linked/cascading dropdowns to a form and found my way to django-smart-selects. I read the documentation but wasn't sure how integrate the suggested updates to project's urls.py urlpatterns from the documentation into what I have currently. The smart select urls mentioned in the linked documentation urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^chaining/', include('smart_selects.urls')), ) The current value of urlpatterns in my project's ursl.py file. urlpatterns = [ path('', include('TimeTracking.urls')), path('admin/', admin.site.urls), path('data-browser/', include('data_browser.urls')), ] Obviously adding those entries to my urlpatterns = [] wouldn't work but I attemtped it anyway... NameError: name 'url' is not defined -
Create wordpress user from Django web application
I would like to create a WordPress user from my Django web application. In Django, I have a User model, and I want to create a user on a WordPress site at the end of the save method. I found a solution on the web that looks like this: class User(models.Model): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True) def save(self): ...some things... import requests username = self.email password = "f{wp_user_password}" api_url = f"my-wordpress-site/wp-json/wp/v2/users" data = { 'username': username, 'email': self.email, 'password': password } response = requests.post(api_url, json=data, auth=(username, password)) if response.status_code == 200: print("WordPress user created") However, when I try to execute this code, it raises a 401 error. How can I resolve this issue? -
Django Admin reverse inline many-to-many extremely slow to load
I have three models Organisation, Event and EventReport. Event and EventReport have a many to many relationship. An Event is only ever associated with a single Organisation. An Event may have many EventReports and a EventReport may be related to multiple Events. class Organisation(models.Model): ... name = models.TextField() url = models.URLField() ... class Event(models.Model): ... organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name = "events") event_reports = models.ManyToManyField(EventReport, blank=True) ... class EventReport(models.Model): date = models.DateField() summary = models.TextField() My objective is to see all of the Events that a particular EventReport is linked to. This is a reverse Many-to-Many relationship, so I am using a "through" model. I've configured admin.py as follows: class EventInLine(admin.TabularInline): model = Event.event_reports.through class EventReportAdmin(admin.ModelAdmin): search_fields=['date','summary'] inlines = [ EventInLine, ] When loading an EventReport in Admin.. it works but takes an extremely long amount of time to load. The EventReport page does list multiple Events under a section called: "EVENT-EVENTREPORT RELATIONSHIPS" Each associated Event is represented in a single dropdown as a Event object e.g. event_event_reports object (10487) with the STR representation of each object in the dropdown. I believe the large amount of time is due to populating the dropdown box with every Event in the database … -
Filter the exact match from the django query set
I have gearbox_model values like this in the queryset in Django gearbox_model = 'XLG , 'SG' I have values arrays and I want to filter these values from the query set values = [ 'LG', SG'] So , I annotate the query set to create the gearbox_model_array queryset = queryset.annotate(gearbox_model_array=SplitComma("gearbox_model")) the gearbox_model_array becomes like this gearbox_model_array = [ 'XLG' , 'SG' ] Then I do filtering for value in values: queryset = queryset.filter(gearbox_model_contains=value) The issue is __contains returning the substring matches as well . For example the record gearbox_model_array = 'XLG , SG' returns as the substring 'LG' exist in it. I Also tried queryset = queryset.filter(gearbox_model_array__iexact=[value]) queryset = queryset.filter(gearbox_model_array__in=value) using the these above Got exception django.db.utils.DataError: malformed array literal: "LG" LINE 1: ...productmanagement_pump"."gearbox_model", ',') IN ('LG')) sub... -
Get session data from all connections in Django Channels
In my Django live time chat app I want to go through all the active connections and retrieve data stored inside request.session in each browser. I want to do this when a new connection to the web socket it made. For example say there is 3 active connections to the chat app; Chrome browser; session data - {'username':'Sam'} Chrome browser; session data - {'username';'James'} Firefox browser; session data - {'username':'Logan'} I want to get a list of all usernames on ChatComsumer.connect. How can I do this? consumers.py (connect method) class ChatComsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'main' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) #GET ALL USERNAMES HERE. self.accept() -
Cpanel deployment of Django project getting 404 Not Found Error when entering any path besides just the domain
For the sake of the question, the domain of my site is domainname.com Typing in the domain into the web gets a functional page with loaded html and css. However, when I click on a button, for example, "Register", though the path changes to the correct corresponding path seen in urls.py on my code, instead of generating the corresponding view, I get a 404 notfound error. Here is what my urls.py looks like: urlpatterns = [ path("", views.home, name='home'), path("register/", views.register, name='register'), path("adgen/", views.IndexView.as_view(), name='index'), path('ad/create/', views.ad_create, name='ad-create'), path('ad/<int:pk>/', views.ad_detail, name='ad-detail'), ] I have also attached what the homepage looks like which is able to generate properly: When I enter just the domain- www.domainname.com, the page generates views.home properly However, when I enter anything past just the domain, such as www.domainname.com/register/, the page gives a 404 notfound error. On views.home, I can click a button called "Register" which brings me to the path www.domainname.com/register/ but gives a 404 notfounderror. I can edit urls.py (replacing "" with "hello/" in the first path), looking like the following: urlpatterns = [ path("hello/", views.home, name='home'), path("register/", views.register, name='register'), path("adgen/", views.IndexView.as_view(), name='index'), path('ad/create/', views.ad_create, name='ad-create'), path('ad/<int:pk>/', views.ad_detail, name='ad-detail'), ] and the path www.domainname.com/hello/ gets a … -
Uploading image to folder named by id of django object using api
I want uploaded files to be placed in folder named the id of an object. When I was doing sites by only using Django I did it like this: I want uploaded files to be placed in folder named the id of an object. When I was doing sites by only using Django I did it like this: def getImageURL(instance, filename): path = os.path.join("posts/{}/post_image.png".format(instance.id)) if os.path.isfile("media/" + path): print("image with this id already exist, ") os.remove("media/posts/{}/post_image.png".format(instance.id)) return path else: return path class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models.CharField(max_length=200, default="no title") text = models.CharField(max_length=500) image = models.FileField(upload_to=getImageURL, blank=True, default="no-image.png") posted = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) It also works when I'm uploading an image using the admin panel. But when I'm doing the exact same thing through api, my images are being uploaded to folder named "None" which leads to overwriting the image after making a new post. -
Remove sidebar from django UI
Whenever the user clicks on models that are shown in the sidebar list, should navigate to that model's page and the sidebar should get removed(collapse). How can I achieve this? -
Registration in Django with sending by smtp qr code for 2fa
Threw django project on hosting, but no domain yet, front on react, run locally. The problem is that smtp does not send a letter to mail. Here are the settings EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' views current_site = get_current_site(request) mail_subject = 'TOKEN' message = render_to_string('emails/account_activation_email.html', { 'user': user, 'qr_code': device.config_url, }) to_email = serializer.validated_data['email'] email = EmailMessage( mail_subject, message, to=[to_email] ) email.content_subtype = "html" email.send() I assume that the letter is not sent because there is no domain and protocol http, because locally everything worked. Maybe someone had such a problem, if the domain with ssl purchase it will pass ? -
Django, calling an event after StreamingHttpResponse is closed
Here is my code: def stream(self,request: HttpRequest,user,camera_index): try: url = self.config["cameras"][int(camera_index)]["url"] except IndexError or TypeError: return HttpResponseNotFound() response = StreamingHttpResponse(self.__stream(url),content_type="multipart/x-mixed-replace;boundary=frame") return response def __stream(self,url): video_cap = cv2.VideoCapture(url) while True: _, frame = cv2.imencode('.jpg', video_cap.read()[1],[int(cv2.IMWRITE_JPEG_QUALITY), 100]) yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame.tobytes() + b'\r\n\r\n') First, I want to know whether the __stream function is ended if user close the page. I did some tests about it but I am not sure. Second, can I add a callback to __stream function that will be called when streaming is closed? -
Django channels-redis WS
I have a problem with Redis WebSocket connection. I am using a server that prefers a unixsocket configuration. REDIS CONF FOR MY SERVER My files and sample template look like this: settings.py ASGI_APPLICATION = 'public_python.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(("unix:///home/Temeria/domains/temeria.pl/redis.sock", 8560), {"password": "my_pass"})], }, }, } asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import TableSG.urls # importuj swoje urlpatterns dla WebSocket z urls.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'public_python.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( TableSG.urls.websocket_urlpatterns ) ), }) views.py def items_view(request): return render(request, 'TableSG/item.html') class ItemConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() items = await self.get_items() await self.send(text_data=json.dumps(items)) @database_sync_to_async def get_items(self): items = SklepModel.objects.all().values() return list(items) urls.py from django.urls import path, include from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views app_name = 'TableSG' urlpatterns = [ # other urls path('items/', views.items_view, name='items'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) websocket_urlpatterns = [ path('ws/items/', views.ItemConsumer.as_asgi()), ] template item.html {% extends "BaseSG/base.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <ul id="items"> </ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> var socket = new WebSocket('wss://' + window.location.host + '/ws/items/'); socket.onmessage = … -
Manually decorating function with extend_schema results in RecursionError
I have a HistoricalModelViewSet class which is used in all other view sets (class StuffViewSet(HistoricalModelViewSet)), it adds couple of /history endpoints (DRF thing, https://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing). Then I'm using drf-spectacular to generate a /swagger view, and there is a different structure to the /history endpoint than the rest of the view set. So I dynamically decorate the function with extend_schema using a serializer set in the child view: class HistoricalModelViewSet(viewsets.ModelViewSet): def __init__(self, **kwargs): self.list_history = extend_schema( responses={200: self.historical_serializer_class(many=True)}, )(self.list_history) @action(detail=False, methods=["get"], url_path="history", url_name="list-history-list") def list_history(self, request): serializer = self.historical_serializer_class(history_items, many=True, context=context) return Response(serializer.data) This all works fine, can view /history for all models. However when viewing /swagger everything works fine couple of times but then after about 5 reloads it errors with: myapp-api-1 | 2023-07-31 11:23:16,553 ERROR django.request log 2577 140001382692608 Internal Server Error: /myapp/schema/ myapp-api-1 | Traceback (most recent call last): myapp-api-1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner myapp-api-1 | response = get_response(request) myapp-api-1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response myapp-api-1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) myapp-api-1 | File "/usr/local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view myapp-api-1 | return view_func(*args, **kwargs) myapp-api-1 | File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 84, in view myapp-api-1 | return self.dispatch(request, *args, **kwargs) myapp-api-1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line …