Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem in using Django model's related_query_name
I have two Django projects which share the same model files. I do all the DB migrations on project A, and use the data in project B. Everything works but one thing. I have a User model and Post model class User(models.Model): ... class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,related_name="posts", related_query_name='post') ... Using related_name user.posts.all() works for both projects, but not the related_query_name User.objects.filter(post=[whatever]) works in project A but not B. It reports Django.core.exceptions.FieldError: Cannot resolve keyword 'post' into field. I also have a third project also using the same DB and also works. The difference is project B is not using it as the default DB, but does it matter? I just don't know why related_query_name only works for A project but B. -
Like button in Django + AJAX (dubl)
I want to implement a 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 have absolutely zero knowledge 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 a 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; … -
adding a user in django admin is impossible
I created a customuseradmin model and add a field (age) to it . now when i want to add a user despite using legal characters for username, it gives me error in django admin panel and want me to correct username here is the code of my model from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) and the view from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' and form as well from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = UserCreationForm.Meta.fields+('age',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields any answer would be appreciated Thanks i did not find any answer after a couple of hours searching the internet -
Original exception text was: 'AnonymousUser' object has no attribute 'email'
This is the error i am getting:AttributeError: Got AttributeError when attempting to get a value for field email on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the AnonymousUser instance. Original exception text was: 'AnonymousUser' object has no attribute 'email'. view.py def get(self, request, *args, **kwargs): user = UserSerializer(request.user) return Response(user.data, status= 200 ) Serializer.py class UserSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) username = serializers.CharField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) first_name = serializers.CharField(required=True, max_length=32, ) last_name = serializers.CharField(required=True, max_length=32, ) password = serializers.CharField(required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model=User fields = ['token', 'email', 'username', 'first_name', 'last_name', 'password', 'id'] I am trying to use the GET method in rest_framework django My email fields is okay in both places -
django.template.exceptions.TemplateSyntaxError: 'i18n' is not a registered tag library
i work on Django==4.2.3. when i try to open admin panel i get error - TemplateSyntaxError at /admin/. here is screenshot of error - second screenshot. my views.py from django.shortcuts import render from .forms import BookedCarForm def book_car(request): if request.method == 'POST': form = BookedCarForm(request.POST) if form.is_valid(): booked_car = form.save(commit=False) booked_car.availability = True booked_car.save() return redirect('success-url') # Redirect to a success page or another view else: form = BookedCarForm() return render(request, 'booking_car.html', {'form': form}) i have other apps too i tried to change code of inner files -
In view testing,client put and delete method is not working as expected
#views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Order,Pizza,Box,Topping from .serializers import OrderSummarySerializer ,ToppingSerializer,BoxSerializer,PizzaSerializer class OrderListAndDetailApiView(APIView): # 1. List all def get(self, request, *args, **kwargs): order = Order.objects.filter(user = request.user.id) print(order) serializer = OrderSummarySerializer(order, many=True) return Response(serializer.data, status=status.HTTP_200_OK) # 2. Create def post(self, request, *args, **kwargs): print("request body is your request.data",request.data) print("request id:",request.user.id) data = { 'customer': request.data.get('customer'), 'address': request.data.get('address'), 'user': request.user.id } serializer = OrderSummarySerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get_object(self, order_id, user_id): try: return Order.objects.get(id=order_id,user = user_id) except Order.DoesNotExist: return None # 3. update def put(self, request, order_id, *args, **kwargs): order_instance = self.get_object(order_id,request.user.id) return Response( {"res": "Object with order id does not exists"}, status=status.HTTP_400_BAD_REQUEST ) data = { 'customer': request.data.get('customer'), 'address': request.data.get('address'), 'user': request.user.id } serializer = OrderSummarySerializer(instance = order_instance, data=data, partial = True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # 4. Delete def delete(self, request,order_id,*args, **kwargs): order_instance = self.get_object(order_id,request.user.id) if not order_instance: return Response( {"res": "Object with order id does not exists"}, status=status.HTTP_400_BAD_REQUEST ) order_instance.delete() return Response( {"res": "Object deleted!"}, status=status.HTTP_200_OK ) #urls.py from django.urls import path from .views import ( OrderListAndDetailApiView ) urlpatterns = [ path('order', OrderListAndDetailApiView.as_view(),name="order"), path('order/<int:order_id>/',OrderListAndDetailApiView.as_view(),name="details") ] #test.py … -
Django-admin custom logentry for model inlines
I have been struggling to resolve this issue for 2 days now without success... Here is my working admin.py that has custom logentries that are coming straight from the model (imnCode) class imnCodeAdmin(admin.ModelAdmin): list_display = ('imn_code', 'description', 'killlife', 'addcheck') @admin.display(description='IMN Code') def imn_code(self, obj): return obj.code @admin.display(description='Description') def description(self, obj): return obj.text_value @admin.display(description='Kill Life') def killlife(self, obj): return obj.kill_life @admin.display(description='Exclude') def addcheck(self, obj): return obj.add_check fieldsets = ( ('Change Information', { 'fields': ('code', 'text_value', 'kill_life', 'add_check'), }), # Add other fieldsets here if needed ) def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'code': db_field.verbose_name = 'IMN Code' elif db_field.name == 'text_value': db_field.verbose_name = 'Description' elif db_field.name == 'kill_life': db_field.verbose_name = 'Kill Life' elif db_field.name == 'add_check': db_field.verbose_name = 'Exclude' return super().formfield_for_dbfield(db_field, **kwargs) field_custom_names = { 'code': 'IMN Code', 'text_value': 'Description', 'kill_life': 'Kill Life', 'add_check': 'Exclude', } def save_model(self, request, obj, form, change): if change: obj_before = self.model.objects.get(pk=obj.pk) changes = [] for field in obj._meta.fields: field_name = field.attname old_value = getattr(obj_before, field_name) new_value = getattr(obj, field_name) if old_value != new_value: field_verbose_name = self.field_custom_names.get(field_name, field.verbose_name.capitalize()) change_url = reverse('admin:OCR_imncode_change', args=[obj.pk]) changes.append(f"Changed {field_verbose_name}: <strong>FROM:</strong>{old_value} <strong>TO:</strong> {new_value} <strong>FOR: <a href='{change_url}'>{obj.code}</a></strong>") if changes: content_type = ContentType.objects.get_for_model(obj) LogEntry.objects.create( user_id=request.user.pk, content_type_id=content_type.pk, object_id=obj.pk, object_repr=str(obj), action_flag=CHANGE, change_message=", ".join(changes), ) super().save_model(request, … -
Django prefetch related used inside a serializer method making too many queries. How to use prefetch related to reduce queries in following case?
By investigating why some apis are taking too much time to respond I encountered that it's because of the db queries increases as the queryset increases. In Django select related and prefetch related will helps to reduce this problem. Here I am trying to solve such a problem where I used prefetch related in a serializer and still making too much db queries. models.py class Order(models.Model): orderid = models.AutoField(primary_key=True) order_number = models.CharField(max_length=20, unique=True) #.... class SubOrder(models.Model): suborderid = models.AutoField(primary_key=True) orderid = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="orderitems", db_column="orderid" ) order_number = models.CharField(max_length=50) product_quantity = models.PositiveIntegerField() #.... views.py class GetOrderDetailsByStore(mixins.ListModelMixin, generics.GenericAPIView): def get(self, request, order_number=None, *args, **kwargs): start = time.time() logger.info("started %s", start) store_id = self.kwargs["storeid"] status_list = [SubOrder.Suborder_Status.PAYMENT_INITIATED, SubOrder.Suborder_Status.PAYMENT_FAILED, SubOrder.Suborder_Status.PAYMENT_PENDING, SubOrder.Suborder_Status.ORDER_INITIATED] order_items = Order.objects.filter(Q(storeid=store_id) &~Q(order_status__in=status_list)).order_by( "-created_date" ) order_items_eager_loading = AllOrderSellerSerializer.setup_eager_loading( order_items) serializer = AllOrderSellerSerializer(order_items_eager_loading, many=True).data end = time.time() diff = end - start logger.info("ended %s", end) logger.info("time taken %s", diff) return Response({"message": "success", "data": serializer}, status=status.HTTP_200_OK) serializer.py class AllOrderSellerSerializer(serializers.ModelSerializer): orderitems = AllOrderItemsSellerSerializer(many=True) store_reference = serializers.CharField(source="store_reference.store_reference") user_reference = serializers.CharField(source="user_reference.user_reference") number_of_items = serializers.SerializerMethodField("get_number_of_items") class Meta: model = Order fields = ["order_number", "order_request_number", "store_reference", "user_reference","number_of_items", "total_amount", "orderitems"] @staticmethod def get_number_of_items(obj): list_of_pdt_quantity_of_order = [order_item.product_quantity for order_item in obj.orderitems.filter(orderid=obj.orderid)] total_ordered_products_quantity = sum(list_of_pdt_quantity_of_order) return total_ordered_products_quantity # return obj.orderitems.count() … -
python-django: How to debug "OPTIONS /api-token-auth/ HTTP/1.1" 200 0
when a POST request for token authentification is made in a browser, the request is changed to an OPTIONS request due to CORS preflights. I followed this tutorial to adapt for those requests. I now get the django-rest-framework's response "OPTIONS /api-token-auth/ HTTP/1.1" 200 0 which is considered to be an XMLHttpRequest error from the front-end. How do I debug this error? What is the problem here? -
Why does Django's annotate seemingly modify the QuerySet?
I have a model, that (extremely simplified for the example) looks like this: class Car(models.Model): driver = models.ForeignKey(Person, on_delete=models.PROTECT) # details of Person don't really matter here class Meta: managed = False # the project has a shared db with another project, included because I don't know if it's relevant db_table = "cars" I wish to have field called driver_name present on the Car model. My approach to that was to create a custom manager that annotates the queryset: class CarManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( driver_name = models.ExpressionWrapper( models.F("driver__surname") + ", " + models.F("driver__name"), output_field=models.TextField() ) ) and then I set it as Car's manager, objects = CarManager(). Now, by my understanding of annotate, this should just add a new field called driver_name that's a combination of each driver's name and surname, on each of the objects in the default queryset. I must be mistaken though, because there are 10 Car objects in the database, and running Car.objects.all() returns a queryset with a single object. That object happens to be the last Car in the database, but I don't know if that's relevant, since I don't have any way to check. If I remove the annotation from the custom manager, … -
Unable to connect to Postgres from a Docker container
I have two containers on a server, one running a Postgres instance from a docker container. However, I can't seem to be able to connect to PG from inside either of the containers, it just times out. I've tried docker exec -it backend bash followed by: psql --host <server_ip> --port 8080 -U root -d main, which locally prompts for password, but times out here. python then which prints connection info locally and on the server shell, but not from inside the container (exception raised after around a minute). More info: docker logs postgres doesn't show anything helpful. mtu is 1500 for docker0, eth0, and eth1. The server is a basic droplet on Digital Ocean. -
How can i add custom field to admin panel for User Model
How can I add a custom field for the User Model to the admin page? I have defined a Char field to abstract User. Although I can see this field in the database, I can't see it in the Django admin panel. I created a Meta class and wrote my field, but it's still invisible on the admin panel. This issue is not happening with my custom models, only with Django's User model. Can anybody tell me why this is happening and what I should do? -
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 }} …