Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
duplicate key value violates unique constraint error in Django
I have a model named package in an app named exam. I use Django rest framework and have the following View: class PackageListCreaet(ListCreateAPIView): queryset = Package.objects.all() serializer_class = PackageSerializer permission_classes = (IsAdminAndReadOnlyForStaff,) @method_decorator(rest_error_decorator(logger)) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) and the following serializer: class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = ('pk','name','price','exams','active') when I try creating a new package from Django admin it works just fine. But when I try creating a new package using the API above it throws the following error: duplicate key value violates unique constraint \"exam_package_pkey\"\nDETAIL: Key (id)=(1) already exists I looked around a bit to find a solution and realized the problem is that the id field of exam_package table is out of sync. I tried syncing it like this and it didn't work. Then I tried removing all records (which happened with no error) and setting the primary key to 1 like this. And it still doesn't work. I looked into this link and realized maybe my probmlem is the same and maybe DRF is creating two new instances which is why I get the error. But I have no idea how to fix it. -
How I'm be able to query a multiple data in single model?
How do I able to query if have three Car Models Car A, Car B andCar C and I wanted to switch this position base on their ordering? How do I able to perform that and what class based view should I use or just a function-based view? Original DB : Car A --> Car B --> Car C Alter DB : Car C --> Car B --> Car A class CarColor(models.Model): colors = models.CharField(max_length=50) def __str__(self) -> str: return self.colors class Car(models.Model): car_name = models.CharField(max_length=50) car_model = models.CharField(max_length=200) car_description = models.TextField(max_length=200) car_color = models.ForeignKey(CarColor, on_delete=models.CASCADE) car_image = models.ImageField(null=True, blank=True, upload_to='media', default='imageholder.png') date_manufactured = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): """ After creating or updating a Car, this function will be triggered and redirection using reverse""" return reverse("car_detail", kwargs={"pk": self.pk}) class Meta: ordering = ['date_manufactured'] def __str__(self): return f'{self.car_name}' -
Django tests AssertionError for update view
I tried to create Django test for UpdateView but I have such problem as: self.assertEqual(application.credit_purpose, 'House Loan') AssertionError: 'Car Loan' != 'House Loan' Car Loan House Loa def test_application_update(self): application = Application.objects.create(customer=self.customer, credit_amount=10000, credit_term=12, credit_purpose='Car Loan', credit_pledge=self.pledge, product=self.product, number_request=2, date_posted='2020-01-01', reason='None', repayment_source=self.repayment, possible_payment=1000, date_refuse='2020-01-02', protokol_number='123457', status=self.status, language=0, day_of_payment=1, credit_user=self.user) response = self.client.post( reverse('application_update', kwargs={'pk': application.id}), {'credit_purpose': 'House Loan'}) self.assertEqual(response.status_code, 200) def test_application_update(self): application = Application.objects.create(customer=self.customer, credit_amount=10000, credit_term=12, credit_purpose='Car Loan', credit_pledge=self.pledge, product=self.product, number_request=2, date_posted='2020-01-01', reason='None', repayment_source=self.repayment, possible_payment=1000, date_refuse='2020-01-02', protokol_number='123457', status=self.status, language=0, day_of_payment=1, credit_user=self.user) response = self.client.post( reverse('application_update', kwargs={'pk': application.id}), {'credit_purpose': 'House Loan'}) self.assertEqual(response.status_code, 200) self.assertEqual(application.credit_purpose, 'House Loan') -
Templates are not found in django deployed project
I have got a Django Project. It runs perfectly using "python2 manage.py runserver". I have deployed the project in a server and I get "Template not found" error. I have changed the path in views file for the main page and now it works, but I have got two new issues: I have got an {% include "/lateral/menu.html" %} line that does not work in main.html All the href in buttons that redirect the user to other html files do not work either. I think it has something to do with the paths, how should I added them in order to be relative path? My structure: -APP1 -APP2 -WEB ---manage.py ---TEMPLATES ------main.html ------logout.html ------loging.html ------LATERAL ---------menu.html Some lines of my views file in order to check how I add the paths: def loging(request): # Función vista return render(request, "loging.html") I have tried changing to some variations of the paths and with absolute paths too without success. All was working perfectly locally. -
when i submit my form My Comment form dosen't save in database
I create a 5 star rating system using django with javascript and i want to user comment like this: i want to click on the stars and then return the value that is an integer this is my models: class Review(models.Model): course = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='reviews') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) rating = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)]) comment = models.TextField() created = models.DateField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name} my views: @csrf_exempt def productDetailView(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) new_comment = None if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.course = product new_comment.rating = request.POST['rating'] new_comment.save() else: form = ReviewForm() return render(request, 'shop/product_detail.html', {'product': product, 'form': form}) js function: $(document).ready(function(){ $('.rate .rate-item').on('click', function(){ var value = $(this).data('value'); $.ajax({ url: '{{ product.get_absolute_url }}', type: 'POST', data: {'rating': value}, success: function(response){ alert('Rating saved successfully!'); } }); }); }); and my template: <form method="post"> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Fast name" }} </div> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Last Name"}} </div> <div class="rate-label">Your Rating:</div> <div class="rate"> <div data-value="1" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="2" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="3" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="4" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="5" class="rate-item"><i class="fa fa-star" … -
How to delete File Field and File(in project root) in django?
I want to delete the data inside the file field and the file uploaded through the file field. I'm beginner. models.py class Fruits(Signable): name = models.CharField( _('Name'), max_length=200, ) description = models.TextField( _('Description'), null=True, blank=True, ) this_is_my_file = models.FileField( _('Photo image'), null=True, blank=True, upload_to='myfile/' ) def __str__(self): return self.name def delete(self, *args, **kwargs): if self.this_is_my_file: self.this_is_my_file.delete() super().delete(*args, **kwargs) Like the code above, I added 'def delete' to the existing model as shown above through search. But I don't know how to use this function. How do I use this in view and template? My part of view is below. views/fruits.py class FruitsDetailView(LoginRequiredMixin, DetailView): template_name = 'frutis/detail.html' login_url = 'login' model = MyObjects def get_context_data(self, **kwargs): pk = self.object.pk context = super().get_context_data(**kwargs) ... return context How do I execute the delete function in this view? I want to delete it when I press the 'delete' button on the template. Should I send a post request from template and receive it from view? I've been thinking about it for 4 days, but I don't know what to do. -
Single model instances on separate html
What is a best way to display single model instances on different html? I know how it is done on single page (forloop), but could not figure out how the same would be possible on different html. i.e. single question per page? my pseudo model: class Question(models.Model): desc = models.CharField() -
Remote DRF Auth and handle payload with JWT
I have auth_service, tpm_api and frontend enviroments. All services use the same secret_key. My users and permissions are on the auth_service. I am using jwt_simple for Authentication on auth_service. On the frontend service, I get token from auth_service with username and password. I am sending requests to endpoints in my tpm_api service with this token. I'm parsing the response and displaying it in my frontend service. So far, no problem. However, I am not getting the token.payload data within the tpm_api service. I added REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), } in settings.py. When I send request to tpm_api service, under self.request.authenticators there is <rest_framework.authentication.BasicAuthentication object 0x000001668986C430> and <rest_framework.authentication.SessionAuthentication object at 0x000001668986C6A0>. I need <rest_framework_simplejwt.authentication.JWTAuthentication object at 0x000001FFDCD23790>. I don't have user model anywhere except auth_service. ##### auth_service model.py ##### from django.db import models from django.contrib.auth.models import AbstractUser perm_parent_choices = [ ("app", "app"), ("factory", "factory"), ("department", "department"), ("role", "role"), ] class User(AbstractUser): perms = models.ManyToManyField("login.Perm", related_name="user_perms", blank=True) gsm = models.CharField(max_length=15, null=True) class Perm(models.Model): parent = models.CharField(max_length=50, choices=perm_parent_choices, null=True) name = models.CharField(max_length=50) short_code = models.CharField(max_length=5) def __str__(self): return self.short_code ##### auth_service views.py ##### class UserViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserSerializer queryset = models.User.objects.all() def list(self, request, *args, **kwargs): ############################## from rest_framework_simplejwt.authentication import … -
Django FileSystemStorage does not save anything to media folder
I'm working on a Django backend deployed on a server, here's my settings: DEBUG = False STATIC_URL = "/staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") And I want to save the users' images outside the django folder, so I've created a custom FileSystemStorage in this way: from django.core.files.storage import FileSystemStorage key_store = FileSystemStorage(location="/home/usr/project/media/", base_url="/media") Where I put the absolute path of ubuntu server. def profile_picture_url(instance, *_): return f"{instance.user.uuid}/profile.picture.png" picture = models.FileField( storage=key_store, default=None, upload_to=profile_picture_url ) But it doesn't create any file inside media folder. Any solution? -
Adding image for blog posts
Coding some kind of blog with django, and I can't make homepage to contain images of the articles... It just doesn't upload a image... my Views.py : class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' my Models.py: class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") #author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = models.ImageField(upload_to="profile_pics", blank=True, null=True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="blog_posts") def total_likes(self): return self.likes.count() def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") My Forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag', 'body', 'image') widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}), 'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}), 'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}), } and my add_post.html : {% extends 'base.html' %} {% block title %}Make an article{% endblock %} {% block content %} {% if user.is_authenticated %} <h1>Make an article</h1> <div class="form-group"> <form method="POST"> <br/> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button class="btn btn-dark">POST</button> </div> {% else %} <h1>You are not allowed to post! You need to <a href="{% url 'login' %}">Log in</a> or <a href="{% … -
Rest api detail User Not Found code user not found Error postman
i am generating a token for each logged in user. But on Get request through postman i am getting this error. please guide me what's wrong ! postman error screenshot my models.py class allmodelfields(AbstractBaseUser): USERNAME_FIELD = 'email' #id_no = models.BigAutoField(primary_key=True,serialize=False,verbose_name="ID",) email = models.EmailField(verbose_name='Email',max_length=255,unique=True,) password = models.CharField(max_length=255) confirm_password = models.CharField(max_length=255) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30,blank = True) last_name = models.CharField(max_length=30,blank = True) number_code = models.CharField(max_length=10) phone_no= models.CharField(max_length=10) pincode = models.CharField(max_length=10) house_no = models.CharField(max_length=50) street = models.CharField(max_length=50,blank = True) locality = models.CharField(max_length=50,blank = True) state = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) ip = models.CharField(blank = True,max_length = 20) # auto filled fields full_name = models.CharField(max_length=100,)#default = first_name + middle_name + last_name) full_number = models.CharField(max_length = 23)#f'{number_code} {phone_no}' created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) is_ active = models.BooleanField(default=False) unique_id = models.CharField(max_length = 10, editable=False) def __str__(self): return self.email def full_name_func(self): return f'{self.first_name} {self.middle_name} {self.last_name}' def full_number_func(self): return f'{self.number_code}|{self.phone_no}' class Meta: abstract = True class Customer(allmodelfields): account_type = models.CharField(max_length=20,choices=customer_account_choices,default=" ") class Dealer(allmodelfields): account_type = models.CharField(max_length=20,choices= dealer_account_choices,default=" ") serializers.py class customerprofileserializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['id','full_name','email','unique_id','full_number'] class dealerprofileserializer(serializers.ModelSerializer): class Meta: model = Dealer fields = ['id','full_name','email','unique_id','full_number'] urls.py path("customerprofileview/", customerprofileview.as_view(),name='customerprofileview'), path("dealerprofileview/", dealerprofileview.as_view(),name='dealerprofileview'), views.py class customerloginview(APIView): renderer_classes = [apirenderer] def post(self,request,format=None): … -
Django Rest api Update View form can't update single attribute
I have created an Employee CRUD in Django REST using generic views. when update view page is loaded I couldn't find the current values in the fields. so I can't update a single value. when i update a single value it shows other fields must be required. I need to update a single value. eg: Phonenumber How can i do that? class EmpUpdateView(UpdateAPIView): queryset = Employee.objects.all() serializer_class = EmpModelSerializer lookup_field = 'id' [enter image description here](https://i.stack.imgur.com/7Slum.png) enter image description here -
session expires while switching to another app.route in flask
Session expires when the '/mobile-confirmation' app.route runs and the user redirects to login page @app.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "POST": #SignUp form Insert codes ...... db.execute("SELECT tempcode FROM users WHERE id = %s", [userID]) tmpcode = db.fetchall() sms_soap.send_by_base_number([tmpcode[0][0]], phonenum[0][0], 999999) executor.submit(tempcodecountdown, username) session["user_id"] = userID return redirect("/mobile-confirmation") else: return render_template("signup.html") @app.route("/mobile-confirmation", methods=["GET", "POST"]) @login_required def confirmmobile(): user_id = session["user_id"] if request.method == "POST": enteredcode = request.form.get("tempcode") db.execute("SELECT tempcode FROM users WHERE id = %s", [user_id]) tmpcode = db.fetchall() if enteredcode == tmpcode[0][0]: db.execute("UPDATE users SET activation = %s WHERE id = %s", ['yes', user_id]) mydb.commit() return redirect('/dashboard') else: return render_template("mobileconfirmation.html") and these are session settings @app.after_request def after_request(response): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response app.config["SESSION_FILE_DIR"] = mkdtemp() app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" app.config["TEMPLATES_AUTO_RELOAD"] = True app.config['SESSION_COOKIE_SAMESITE'] = "None" app.config['SESSION_COOKIE_SECURE'] = True it was working correctly in another ide but now I have this problem on cpanel -
Django - how to retrieve data from two models (at the same time) related with OneToOne relation?
In Django I have two models: class Car(models.Model): model_name = CharField(...) make_name = CharField(...) car_exterior_color= = CharField( CHOICES ) class CarWash(models.Model): car_washed = BooleanField(...) wash_date = DateTimeField(...) added_wax = BooleanField(...) car = models.OneToOneField(Car, on_delete=models.CASCADE, verbose_name="Car washed") I need to show such table in view, that retrieves data from two models: model_name make_name car_ext_col car_washed ? added_wax ? wash date IS Lexus blue Yes No 2023-02-02 G37 Infiniti white No No -- RX Lexus red Yes No 2023-02-02 Corolla Toyota green No No -- Tundra Toyota blue Yes Yes 2023-02-02 Q70 Infiniti yellow Yes Yes 2023-02-03 Civic Honda black Yes No 2023-02-03 Malibu Chevrolet red Yes Yes 2023-02-04 GS Lexus yellow Yes No 2023-02-04 Q30 Infiniti white No No -- What should I write in views.py? How to retrieve data from two models to get table as above? -
hi, i want add search bar to myproject but don't return anything
this view for search: class Search(generic.ListView): model = Blog template_name = 'pages/blog_list_view.html' context_object_name = 'blog' def get_queryset(self): search = self.request.GET.get("q") search_result = Blog.objects.filter( Q(title__icontains=search) | Q(description__icontains=search) | Q(active=True)) return search_result search form in _base.html <form action="{% url 'search' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> my model class Blog(models.Model): title = models.CharField(max_length=100) cover = models.ImageField(upload_to='blog_cover/') description = models.CharField(max_length=200) text = models.TextField() author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) active = models.BooleanField(default=False) date_create = models.DateField(auto_now_add=True) date_modified = models.DateField(auto_now=True) def __str__(self): return f'{self.title} : {self.author}' def get_absolute_url(self): return reverse('blog_detail', args=[self.id]) tip: "I use Persian language for search" I tried __icontains and __contains but result was same -
Writing a tuple search with Django ORM
I'm trying to write a search based on tuples with the Django ORM syntax. The final sql statement should look something like: SELECT * FROM mytable WHERE (field_a,field_b) IN ((1,2),(3,4)); I know I can achieve this in django using the extra keyword: MyModel.objects.extra( where=["(field_a, field_b) IN %s"], params=[((1,2),(3,4))] ) but the "extra" keyword will be deprecated at some point in django so I'd like a pure ORM/django solution. Searching the web, I found https://code.djangoproject.com/ticket/33015 and the comment from Simon Charette, something like the snippet below could be OK, but I can't get it to work. from django.db.models import Func, lookups class ExpressionTuple(Func): template = '(%(expressions)s)' arg_joiner = "," MyModel.objects.filter(lookups.In( ExpressionTuple('field_a', 'field_b'), ((1,2),(3,4)), )) I'm using Django 3.2 but I don't expect Django 4.x to do a big difference here. My db backend is posgresql in case it matters. -
Can i make an stackedInline connnection between two model without having any connection between them ? in Django
class Item(models.Model): name=models.CharField(max_length=250) description = model.TextField() class Photo(models.Model): item = models.ForiegnKey(Item) title=models.ChaField(max_length=250) here is admin.py class PhotoInline(admin.StackedInline): model = Photo class ItemAdmin(admin.ModelAdmin): inlines = [PhotoInline] admin.site.register(Item,strong text ItemAdmin) admin.site.register(Photo) i want to have an inline connection between without them having any relationship -
(Django model) How does this Message model works?
So I am following a Youtube video on how to create a chatting app. Then it build a model that I don't understand. Here's the Message model I came across and can't understand how it works. class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') body = models.TextField() date = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def send_message(from_user, to_user, body): sender_message = Message(user=from_user, sender=from_user, recipient=to_user, body=body, is_read=True) sender_message.save() recipient_message = Message(user=to_user, sender=from_user, recipient=from_user, body=body, is_read=True) recipient_message.save() return sender_message def get_message(user): users = [] messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last') # filter by user=the login user, recipient=the sender, the lastest message from each sender, order the lastest message by sender using time for message in messages: users.append({ 'user': User.objects.get(pk=message['recipient']), 'last': message['last'], 'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count(), }) return users I understand the different fields of the Message model but I fail to understand why it create two instances of the message model in the send_message() function. One for sender message and another for recipient message. recipient_message = Message(user=to_user, sender=from_user, recipient=from_user, body=body, is_read=True) Then for the recipient_message I'm not clear why the recipient field is set to from_user instead of to_user?? Could anyone please help me with this? I am … -
Getting ERROR "You must provide at least one recurring price in `subscription` mode when using prices."
Hello I am beginner in Django while trying to create Subscription with stripe i am getting error as InvalidRequestError at /stripe/create-checkout-session Request req_M2eko0H9LwXvDz: You must provide at least one recurring price in subscription mode when using prices. This is my views.py code snippet. `checkout_session = stripe.checkout.Session.create( success_url=request.build_absolute_uri(reverse('main:complete') ) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('main:cancelled_transaction')), client_reference_id=request.user.id if request.user.is_authenticated else None, customer_email = email, payment_method_types=['card'], line_items=[ { 'quantity': 1, 'price_data':{ 'product':'PRODUCT_ID', 'unit_amount':settings.STRIPE_PRICE_ID, 'currency':'INR', # 'recurring':'DAY' } } ], mode='subscription', ) ` I have tried to use https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-line_items-price_data-recurring in my code. -
How to add reference Parameters in extend_schema decorator in drf-spectacular
I'm using drf-spectacular to generate the swagger/redoc API documentation. I am facing issue in customising the schemas generated. I am trying to generate reference parameter using @extend_schema decorators in drf_spectacular but did'nt get the expected schema. extend_schema - ` from drf_spectacular.utils import extend_schema @extend_schema( parameters=headerParam, responses = {200:Response1,400:errorresponse}, tags = ['User'], )` headerParam - `headerParam = [ OpenApiParameter( name='Accept-Language', location=OpenApiParameter.HEADER, type=OpenApiTypes.STR, description='ISO 2 Letter Language Code', required=True, enum=['en', 'ar'], # default='en', ), OpenApiParameter( name='Accept', location=OpenApiParameter.HEADER, type=OpenApiTypes.STR, description='Type of response you are expecting from API. i.e. (application/json)', required=True, default='application/json', ), ]` The problem I am facing is the schema in drf_spectacular is generating this as below - `"parameters": [ { "in": "header", "name": "Accept", "schema": { "type": "string", "default": "application/json" }, "description": "Type of response you are expecting from API. i.e (application/json)", "required": true }, { "in": "header", "name": "Accept-Language", "schema": { "type": "string", "enum": [ "ar", "en" ] }, "description": "ISO 2 Letter Language Code", "required": true } ],` I want to generate like this - "parameters": [ { "$ref": "#/components/parameters/Accept" }, { "$ref": "#/components/parameters/Accept-Language" } ],` Thank you and Appreciate for the help in Advance :) I have done R&D but didn't find anything related to this. -
i am getting 405 error for get method in my django api, instead, i want a default message for get method
For django API, which we have written, post method is allowed but instead of get method, i am getting 405 error, but instead i want some default message like- "error". I am sharing my code. Please let me know if anyone can help. @api_view(['GET']) @permission_classes([AllowAny]) -
how change database's port dynamically(django)
i have a django project that it should have ability to change the database's port dynamically for security reasons. for example there should be a template like ( port= ) and the administrator should enter a port and change the default one. how to do this? -
500 error on django channels send message to group
I have the following Django channels consumer but when I try to send data to the stocks group، it returns a 500 error. Also, I don't get any error logs. Here is the consumer: class AuthRequiredConsumer(JsonWebsocketConsumer): def connect(self): user = self.scope['user'] print(isinstance(user, AnonymousUser)) if isinstance(user, AnonymousUser): raise DenyConnection("authentication required") self.accept() class ChatConsumer(AuthRequiredConsumer): groups = ['stocks'] channel_layer_alias = "stocks" def stocks_data(self, event): print(event) return self.send_json({'message': event['text']}) def receive_json(self, content, **kwargs): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "stocks", { "type": "stocks.data", "text": "Hello there!", }, ) message = content["message"] self.send_json({"message": message}) Also, I use this middle to authenticate users by the token: @database_sync_to_async def get_user(token_key): try: token = Token.objects.get(key=token_key) return token. user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) async def __call__(self, scope, receive, send): try: token_key = (dict((x.split('=') for x in scope['query_string'].decode().split("&")))).get('token', None) except ValueError: print("error") token_key = None scope['user'] = AnonymousUser() if token_key is None else await get_user(token_key) return await super().__call__(scope, receive, send) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) And here is the routing config: application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": TokenAuthMiddlewareStack( URLRouter( [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()) ] ) ) , } ) I debugged the receive_json method using breakpoints And I saw self.channel_name and self.channel_layer is None!! Does anyone … -
Does Django save model objects other than `save()` or `create()` methods?
I'm writing something like the following: class Foo(models.Model): a = models.CharField() def f(foo: Foo) -> Foo: y = Foo( **{field.name: getattr(foo, field.name) for field in foo._meta.get_fields()} ) # copy foo with pk y.a = "c" return y My concern is whether y are saved to DB before users call save() method. Could it occur? -
In Django's auth contrib module, how do I correctly return an error when overriding the asswordResetConfirmView view?
I'm using Django 3 and the auth contrib module. I want to override the reset password procedure via an API and so I have a method that looks like this .... class CompleteResetPasswordView(PasswordResetConfirmView): @method_decorator(csrf_exempt) def dispatch(self, request): body = json.loads(request.body) self.data = body # validate user, password, and confirm password if user is not None: ... return Response('Success', status=HTTP_200_OK) ... return Response('Error', status=HTTP_500_INTERNAL_SERVER_ERROR) When the user cannot be validated and the "return Response('Error', status=HTTP_500_INTERNAL_SERVER_ERROR)" is invoked, this error is returned AssertionError at /password-reset-complete .accepted_renderer not set on Response I would liek a JSON response (in addition to the 500 status code) to be returned to the view, but haven't figured out how to manipulate what I have to make this happen.