Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is making a different models for different categories is good, Django?
I'm making a website that provides services Shall I create different model for different type of service available -
Django How to use Javascript file from my local Django project in an external app
Let's say I have an application, myapp, and in that application I have installed another application via pip install wiki to add a wiki into my project. The wiki app is installed in the following directory: /Users/{my_username}/.virtualenvs/{my_virtualenv_name}/lib/python3.9/site-packages/wiki/ So to make modifications I have to overwrite the templates. In myapp I have been able to modify without problems the styles and others of the wiki app by overriding the templates, but the problem comes when I want to load javascript libraries external to wiki and that are in my local project (myapp) I would like to add the following js, but for some reason it doesn't work: <script type="text/javascript" src="/static/myapp/bootstrap/js/bootstrap-typeahead.js"> </script> <script type="text/javascript" src="/static/myapp/scripts/jquery.autocomplete.min.js"> </script> <script type="text/javascript" src="/static/myapp/scripts/myapp.js"></script> <script type="text/javascript" src="{% static 'project/search.js' %}"></script> <script type="text/javascript" src="{% static 'myapp/scripts/underscore-1.8.3.min.js' %}"> Probably if i add those js files in site-packages it will work but I don't think its good practice. Any ideas or suggestions on how to import such js files correctly? -
TypeError: Password must be a string or bytes, got BoundField
I am creating a login page. There I want to receive json format at backend, with fields username and password in string format. But when I try to authenticate username and password (in views.py). I get the following error: TypeError: Password must be a string or bytes, got BoundField. views.py from .serializers import event_serializer, student_serializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError @api_view(['POST', 'GET']) def login_view(request): if request.method == "POST": serializer = student_login_serializer(data=request.data) if serializer.is_valid(): print("serializer is valid") username_pwd = serializer username = username_pwd["username"] password = username_pwd["password"] student = authenticate(request, username=username, password=password) if student is not None: login(request, student) events = Event.objects.all() serializer = event_serializer(events, many=True) return Response(serializer.data, status=status.HTTP_202_ACCEPTED) else: return Response(serializer.data, status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) elif request.method == "GET": users = Student.objects.all() serializer = student_serializer(users, many=True) return Response(serializer.data) serializers.py from rest_framework import serializers from .models import Student, Club, member_request, Event, Comment from django import forms class student_login_serializer(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Password'})) fields = ['username', 'password'] models.py from django.contrib.auth.models import AbstractUser from django.db import models class Student(AbstractUser): pass Please feel free to ask me for more details regarding this problem and … -
FAIL: test_category_model_entry (store.test.test_model.TestCategoriesModel)
I am trying to do unit test using coverage.py. From my understnadng I supposed to passed the test with no error as object name is 'django'. However, the output is irritates me when it mentioned Category Object (1) instead of 'django' and due to that my test will be forever error. Kindly somebody please help. from django.test import TestCase from store.models import Category, Product class TestCategoriesModel(TestCase): def setUp(self): self.data1 = Category.objects.create(name="django", slug="django") def test_category_model_entry(self): # Test category model data insertion/types/field attributes data = self.data1 self.assertTrue(isinstance(data, Category)) self.assertEqual(str(data), "django") The output displays as follows: in test_category_model_entry self.assertEqual(str(data), "django") AssertionError: 'Category object (1)' != 'django' Category object (1) django -
How can I let users authenticate into my django-react website with github?
I can't find ANYTHING on google or stackoverfliow about this. I'm using django and react and I want one of those "Log in with Github" buttons on my login page. I doubt anyone has time to write the whole process but maybe a link to a good source? Thanks! -
How to refresh quantity of cart in the span or the div after add product to cart AJAX / Django?
The product is successfully added to the cart but the div containing the cart value is not up to date. You will have to refresh the page so that the div is up to date. I tried the load() and html() methods. How to refresh cart container when I add the product to the cart ? I need a help please. Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> JS Code $(".form-order").on('submit', function(e){ e.preventDefault(); var product_id = $(this).attr('data-id') var quantity = $(this).find("#id_quantite").val() console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', dataType: 'json', data: data, success: function(data){ $("cartval").load(); … -
Django Stripe library is having trouble with Payment Method
I am using Stripe JS on my front end, and sending it to my backend, which is based on Django. All of generating a subscription is working, except for the payment method. Here's the code: class PurchaseSubscriptionView(APIView): def post(self, request, user_id): price_name = request.data.get("price_name") payment_method = request.data.get("payment_method") user = User.objects.get(id=user_id) customer, created = djstripe.models.Customer.get_or_create(subscriber=user) customer.add_payment_method(payment_method) price = djstripe.models.Price.objects.get(nickname=price_name) customer.subscribe(price=price) return Response({"success": "eventual subscription data"}) My payment_method looks like this (all of this is fake card data): { "id":"pm_1Ia7gGJs57u3g5HDEpaI5Pv2", "object":"payment_method", "billing_details":{ "address":{ "city":"None", "country":"None", "line1":"None", "line2":"None", "postal_code":"None", "state":"None" }, "email":"None", "name":"None", "phone":"None" }, "card":{ "brand":"visa", "checks":{ "address_line1_check":"None", "address_postal_code_check":"None", "cvc_check":"None" }, "country":"US", "exp_month":2, "exp_year":2022, "funding":"credit", "generated_from":"None", "last4":"4242", "networks":{ "available":[ "visa" ], "preferred":"None" }, "three_d_secure_usage":{ "supported":true }, "wallet":"None" }, "created":1616972764, "customer":"None", "livemode":false, "type":"card" } However upon this line: customer.add_payment_method(payment_method) I get the following error: TypeError: quote_from_bytes() expected bytes What exactly am I missing here? Is this not how I am supposed to use a payment method? This is using the Djstripe library -
Django Reverse function not working in this example
I'm not able to access the url named "forum" using the reverse function. It gives me this error: django.urls.exceptions.NoReverseMatch: Reverse for 'forum' not found. 'forum' is not a valid view function or pattern name. I'm able to access all my other namespaces URLs within the other apps. But I just can't access anything by name from my root URLs.py file. Here is my root URLs.py file from django.contrib import admin from django.urls import path, include from machina import urls as machina_urls from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('forum/',include(machina_urls), name='forum'), path('admin/', admin.site.urls), path('symposium/', include('symposium.urls')), path('elearning/', include('elearning.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Efficient Django query filter first n records
I'm trying to filter for the first (or last) n Message objects which match a certain filter. Right now I need to filter for all matches then slice. def get(self, request, chat_id, n): last_n_messages = Message.objects.filter(chat=chat_id).order_by('-id')[:n] last_n_sorted = reversed(last_n_messages) serializer = MessageSerializer(last_n_sorted, many=True) return Response(serializer.data, status=status.HTTP_200_OK) This is clearly not efficient. Is there a way to get the first (or last) n items without exhaustively loading every match? -
Using python manage.py runserver is giving me "file or directory does not exist"
So I keep getting that message and I am in the right folder when doing the command. I pip install django'd, I ran the command django-admin startapp firstproject, but this problem persists. I even tried updating django and python and reinstalled everything once. The photo I've attatched are the contents of my projects directory. Has anyone else had this problem before? -
Test for proper exception with Pytest
I want to test if a Django Rest Framework returns the proper exception when required, but the test always fails when the exception is raised, instead of succeeding when the exception is the right one: This is my view: @api_view(http_method_names=['GET']) def get_fibonacci(request: Request) -> Response: """ Calculates the fibonacci value for number sent as query_param 'n' """ try: n = int(request.query_params['n']) except ValueError: raise ValueError("The value of 'n' must be an integer.") fibonacci_of_n = fibonacci_dynamic_v2(n) return Response(fibonacci_of_n) And this is my test: def test_n_is_a_string_returns_proper_exception(client) -> None: test_url = f"{fibonacci_url}?n=str" response = client.get(test_url) assert response.status_code == 404 And this is the result of the test: =============================== short test summary info ======================================= FAILED tests/test_api.py::test_n_is_a_string_returns_proper_exception - ValueError: The value of 'n' must be an integer. Results (1.08s): 23 passed 1 failed - api/coronavstech/fibonacci_methods/tests/test_api.py:20 test_n_is_a_string_returns_proper_exception I don't know how to instruct Pytest to succeed the test when the exception is the right one, instead of failing it because there was an exception, wich is the result expected from the request. -
Why does django give an httpresponse error when running my code?
first time asking on stack. I am really struggling to figure out what is causing this error message: **The view econlabs.views.balance didn't return an HttpResponse object. It returned None instead.** I feel like there is an issue with the form initialization in the balance function in views.py. I don't know Django very well or Python. Please help me with this error. Code below: *models.py* class Balance(models.Model): userBalance = models.DecimalField(max_digits=10, decimal_places=2, null=True) *forms.py* lass BalanceForm(forms.ModelForm): class Meta: model = Balance fields = ['userBalance'] *views.py* def balance(request): form = BalanceForm(initial={"userBalance":107}) if form.is_valid(): if request.method == "POST" and "form10" in request.POST: formValue = form.cleaned_data.get('userBalance') form2 = formValue - 10 return render(request, "econlabs/balance.html", {'form2': form2}) return render(request, "econlabs/balance.html", {'form': form}) -
DRF serialize PK Field
I have added User as a PK to model Category and I am passing the ID via an ajax request however something is clearly wrong with the serializer as in the views it returns None whilst if I do the request via Postman everything works as expected. Could someone please point out what I am doing wrong? class CategorySerializer(TaggitSerializer, serializers.ModelSerializer): author = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all()) posts = PostSerializer(many=True, read_only=True) tags = TagListSerializerField() class Meta: model = Category fields = ('id', 'name', 'description', 'created_at', 'updated_at', 'posts', 'tags', 'author') # User Serializer class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id', 'email') -
Class not instantiating properly within Django Form function
I created a class to manage Oauth token renewal. The token is stored in the database using a Django model. I can make API calls after instantiating the class. When I try to do the same within a Django Form it always gives an error, stating that it can't locate the access token. The token is retrieved from a queryset within the class init method. If no token is found it should then fetch a new token. Within Django shell if I delete the token from the database and then create a new object from the class, it will fetch a new token. Within the form both methods are failing. The settings fields with the API keys aren't loaded properly, so fetching the token doesn't work. I can't retrieve the existing token from the database or fetch a new one if it's missing. The form itself doesn't do anything except validate the fields, and instantiate this class from the FormView form_valid function. The error is thrown at self.client.fetch_token. This error is a credentials error because it can't access the API keys from the settings. It works in the Django shell. The first line of code that fails is if self.api_token … -
pytest-django: mailoutbox work only if last fixture
If I use the mailoutbox fixture like this, it works: def test_send_invoices_via_mail_page(user_client, invoice, mailoutbox): url = reverse(send_invoices_via_mail_page) response = user_client.get(url) assert response.status_code == 200 log = LogOfInvoiceMail.objects.get(invoice=invoice) assert log.success, log.exception assert log.invoice == invoice assert log.exception == '' assert len(mailoutbox) == 1, mailoutbox But if I use it like this it fails: def test_send_invoices_via_mail_page(mailoutbox, user_client, invoice): Error: len(mailoutbox) is 0 Why does is the order of the arguments important here? It took me a very long way to find this work-around. -
Updating a large number of foreign key references in Django
I have a companies and employees tables, along with a third employees records table which contains a foreign key to both the companies and employees tables. The company table has an entry of 'Company A'. Subsequently, 'Company A' splits into two new entries: 'Company A1' and 'Company A2'. Now in the employees records table, currently a large number employees are associated with 'Company A'. For each employee associated with 'Company A', I want to create two new entries which associates the employee with both 'Company A1' and 'Company A2'. What would be the optimal way to accomplish this with Django? Considering that there could be hundreds of thousands or possible millions of rows of employee records that need updating. -
How to get the most liked users on a particular date in django
So I have a social media app, where users can like the posts of other users. Now I fetch the top 20 users who have received the most number of likes. Everything is perfect. But the problem is I cant figure out , how I can fetch the top users who have received the most likes on a particular date, for example get the top users who received most likes only today My LIKES MODEL class PostLike(models.Model): user_who_liked = models.ForeignKey(User, on_delete=models.CASCADE) post_liked = models.ForeignKey(Post, on_delete=models.CASCADE) liked_on = models.DateTimeField(default=timezone.now) SIMPLIFIED POST MODEL class Post(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='author') caption = models.TextField() date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField( User, blank=True, through=PostLike) image = models.TextField() class Meta: ordering = ['-id'] SIMPLIFIED USER MODEL class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) user_name = models.CharField(max_length=100, unique=True) date = models.DateTimeField(default=timezone.now) profile_picture = models.TextField( default="https://www.kindpng.com/picc/m/24-248253_user-profile-default-image-png-clipart-png-download.png") bio = models.CharField(max_length=200, default="") objects = CustomManger() def __str__(self): return self.user_name ** My query to get the top users who received the most number of likes ** users = User.objects.annotate(num__smiles=Count('meme_publisher__smiles')).order_by('-num__smiles')[:20] # So everything is perfect and I am getting the users, now I dont know how to get the top users with most likes on a PARTICULAR DATE, for example … -
django admin: save image like base64
I'd like to upload image through django admin panel, but I need to save it as a base64 string in database How could I do it? + I would like to see image in admin DB may move someday and it will be better to save just base64 string, so I won't depend on some file structure (as if I'll store original images somewhere) ps. I have django 2.2.6 version -
How to define the sum of multiple columns values into one column in Django models.py
I have a django models.py as follows: from django.db import models class StudentList(models.Model): name=models.CharField(max_length=200) def __str__(self): return self.name class Marks_of_each_Student(models.Model): student_name=models.ForeignKey(StudentList,on_delete=models.CASCADE) s1=models.IntegerField() s2=models.IntegerField() s3=models.IntegerField() Total=models.IntegerField(default=0,editable=False) def calculate_total(self): return self.s1+self.s2+self.s3 def save(self): self.Total=self.calculate_total() I want to have a column names Total containing the value of s1+s2+s3 in it when entered via ORM commands through shell. I tried the following but it did not worked out. from main_page.models import StudentList,Marks_of_each_Student >>> x=StudentList(name="XYZ NAME") >>> x.save() >>> x1=Marks_of_each_Student(student_name=x,s1=90,s2=90,s3=90) >>> x1.save() >>> x1 <Marks_of_each_Student: Marks_of_each_Student object (1)> >>> x1.Total 0 All other columns are having the correct values but this Total is not giving correct results. How do I proceed to make sure that the changes are reflected in Total column and also I was not getting these data saved for Marks_of_each_Student in MySQL table. Can anyone help me?? -
how can send and receive and show it without refresh page in django?
i created a django chat app and now i want send and receive message and show it in same page without refreshing... my views function is: @login_required def message_form(request,id,slug,user_id): user2=request.user user_id=user_id user = get_object_or_404(User,id=user_id) msg = Message.objects.filter(sender=user) post = get_object_or_404(Post,id=id,slug=slug) post2 = Post.objects.filter(user=post.user) inbox = Message.objects.filter(reciever=request.user) sentbox = Message.objects.filter(sender = request.user) message1 = Message.objects.filter(post = post ,sender=user,reciever=post.user).order_by('date') message2 = Message.objects.filter(post = post ,sender=post.user,reciever=user).order_by('date') message3 = list(chain(message1, message2)) message3 = sorted(message3, key=operator.attrgetter('id')) form = MessageForm(request.POST or None,request.FILES or None ) if request.method == 'POST': if form.is_valid(): message = form.save(commit=False) if post.user == request.user: message.sender = post.user message.reciever = user else: message.sender = request.user message.reciever = post.user message.post = post message.post_user = post.user message.post_image = post.image1 message.save() form = MessageForm() return HttpResponse() context={ 'post':post, 'post2':post2, 'inbox':inbox, 'sentbox':sentbox, 'form':form, 'message1':message1, 'user_id':user_id, 'msg':msg, 'message2':message2, 'message3':message3, 'user2':user2, } return render(request,'user_chats.html',context) and this is my templates : {% for box3 in message3 %} <div class=" border bg-light my-3 p-3 msg_show " id="msg_show" style="border-radius:20px; " > <span class="p-2 my-5 msg" id="msg" >{{ box3.msg_content }}</span><br> <span class="date text-muted ">{{ box3.whenpublished }}</span> </div> {% endfor %} <form class="mt-2 " id="form_id" method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group mx-auto" > <div class="input-group-append"> <button class="btn updateButton'" type="submit" name="button"> send </button> … -
How to fix double click issue in large cell in IPython Notebook?
I use an interactive Python shell to interact with my Django application and one cell of the IPython Notebook has almost 400 lines. My problem is that the double click doesn't work well inside this specific cell so that I'm unable to double-click and select text quickly. Any idea how to fix this issue other than reducing the cell size ? This is how I start the server in a virtual env : python manage.py shell_plus --notebook -
how to create a removal button that depends on his parent and make a function remove() by jquery on it?
I need to search by whether it is one query or more. I'm not strong in Javascript or Jquery, however, the function does very well whether for (plus button) in one or more query and for (removal button) for one query only bt when it created if there are more than one search field sometimes be created and sometimes not created. I don't really know what is going on but all I notice that when I click on (plus button) which has the removal button it can create a new removal button and if I click the plus button in the parent that hasn't button removal the removal button doesn't create. there are my code and screenshot to see the error but please note that I do for-loop in HTML elements into form to retrieve the number of requests that exists in the query to create the same number of search fields therefore, I create the button that adds and remove that search except for the first field. correct search added for removal btn wrong search added for removal btn search.html <div class="search-field"> <h2 class="show"></h2> {% if query_length|length < 2 %} <form method="get" id="main_search"> <div class="form-group row search_repeated search_group"> <div … -
get Cross-Origin Request Blocked error in django for one special url
i used django and reactJs for my web application. all of urls are ok but just a url get Cross-origin blocked error. this is my urls.py: from . import views urlpatterns = [ path('',views.order_view,name="order"), path('create-ticket',views.create_ticket_view,name="create-ticket"), path('get-tickets-list/<int:id>',views.tickets_list_view,name='get-tickets-list'), path('change-state/order/<int:order_id>/state/<int:state_id>/', views.change_state_order_view, name='change-state'), path('create-common-answer/',views.create_common_answer_view,name='create-common-answer'), path('get-common-answer/',views.get_common_answer_view,name='get-common-answer'), path('get-states/',views.get_states_view,name='get-states'), ] and all of these are ok except one and that is : path('change-state/order/<int:order_id>/state/<int:state_id>/', views.change_state_order_view, name='change-state'), code view : @api_view(['PUT','DELETE','OPTIONS']) @permission_classes([IsAuthenticated,IsAdminPerm]) def change_state_order_view(request,order_id,state_id): try: order = Order.objects.get(id=order_id) except: return Response({'error':'404 Not found...!'},status=404) if request.method == "PUT": order.operator.add(request.user) elif request.method == "DELETE": order.operator.remove(request.user) order.state_ticket_id = state_id order.save() return Response({ 'message':'عملیات با موفقیت انجام شد.', 'result' : { 'order' : order.id, 'user_email' : request.user.email, 'name' : request.user.name, 'method' : request.method } }) and my reactJs code : const instance = axios.delete('http://MY_DOMAIN/api/orders/change-state/order/6273/state/1',{ headers: {'Authorization': 'token 079054fc245dc0894f896c31cd2ce2924e68cdb3'} }); console.log(instance); -
How not to delete default image when new one is uploaded?
I wrote code that deletes old user avatar when user uploads new one. And the problem is that, if user has default avatar and decides to change it, default image gets deleted. Here is my code: @receiver(pre_save, sender=Profile) def delete_file_on_change(sender, instance, **kwargs): if instance.pk: try: old_image = Profile.objects.get(pk=instance.pk).image except Profile.DoesNotExist: return new_image = instance.image if old_image and old_image.url != new_image.url: old_image.delete(save=False) I tried this: @receiver(pre_save, sender=Profile) def delete_file_on_change(sender, instance, **kwargs): if instance.image.url == '/media/default.jpg': ... But it didn't work because print(instance.image.url) for some reason, returns not /media/default.jpg but url of newly uploaded file. Also, here's my view: def update_user(request): if request.method == 'POST': if 'edit_profile' in request.POST: profile_form = UpdateProfileForm(request.POST or None, request.FILES, instance=request.user.profile) if profile_form.is_valid(): profile_form.save() return redirect('editprofile') profile_form = UpdateProfileForm(instance=request.user.profile) context = {'ps_form': password_form, 'u_form': user_info_form, 'pr_form': profile_form} return render(request, 'update_user.html', context=context) -
how to create an infrastructure of REACT, REACT NATIVE and DJANGO DRF on AWS
What would be the best way to create the infrastructure below on AWS: Please note that React and Django (DRF) are being dockerized, therefor there is a docker-compose.yml that has both the front end and back end) (PLEASE ADVISE IF I SHOULD DECOUPLE IT IN CASE THERE IS ANOTHER SOLUTION) FRONT END BACK END Front end React ----- > Backend Django (DRF) Mobile app React Native