Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django's Bulk Update Correctly to Append to List
I have a dictionary list of items in validated_data which I currently update the user and save to db. for book in validated_data: book.user = self.context['request'].user obj.save() I would like to make use of Django's bulk update instead. I found the following example: Which I modified like so: for book in validated_data: book.user = self.context['request'].user Book.objects.bulk_update(validated_data, update_fields = ['user']) However, I don't see how this can work. First, validated_data was never actually updated in this example. How can I update each item in validated_data to contain my new value? -
Getting 404 code on Django TestCase with valid args on revers function
I need help with Django TestCase, and reverse function. I'm not getting what I'm doing wrong, but all my cases are response with 404. In short the project suppose to get url and generate short url and redirect it. It works but I don't understand why the TestCases are not Pls help! view.py from .models import UrlTable, ShortUrlTable @csrf_exempt def create(request): if request.method == 'POST': try: post_url = json.loads(request.body) except Exception as e: return HttpResponseBadRequest(str(e),content_type='text/plain') if UrlTable.objects.filter(url_text=post_url["url"]).exists(): url = UrlTable.objects.get(url_text=post_url["url"]) short = ShortUrlTable(url=url, short_url_text=create_random_code(), num_clicks=0) short.save() else: url = UrlTable(url_text=post_url["url"]) try: url.full_clean() except ValidationError as v: return HttpResponseBadRequest(str(v),content_type='text/plain') url.save() short = ShortUrlTable(url=url, short_url_text=create_random_code(), num_clicks=0) short.save() domain = request.get_host() msg = str(url.url_text+" ->"+domain+"/s/"+short.short_url_text) return HttpResponse(msg, content_type='text/plain') elif request.method == 'GET': msg = str("Hello World") return HttpResponse(msg, content_type='text/plain') def redirect_url_view(request, url_short_part): try: shorter_link = ShortUrlTable.objects.get(short_url_text=url_short_part) shorter_link.num_clicks += 1 print(shorter_link.num_clicks) shorter_link.save() return HttpResponseRedirect(shorter_link.url.url_text) except Exception: raise Http404('Sorry this short link is not exist') urls.py from django.urls import path from . import views urlpatterns = [ path('create', views.create, name='create'), path('s/<str:url_short_part>', views.redirect_url_view, name='redirect'), ] class TestViews(TestCase): def setUp(self): self.client = Client() self.create_url = reverse('create') self.url = UrlTable(url_text="https://google.com") self.url.save() self.short = ShortUrlTable(url=self.url, short_url_text=create_random_code(), num_clicks=0) self.short.save() self.url_short_part = self.short.short_url_text self.redirect_url = reverse('redirect',args=[self.url_short_part]) self.fake_url_short = 'aa' self.redirect_url = … -
Django Tailwind Typography Prose not working properly
I want to learn tailwind and I am using Django, but I occured a problem that typography isn't working, I don't know why.. because other tailwind classes works very well. I am using that to run tailwind with django django-tailwind.readthedocs.io/ my html <div class="prose lg:prose-lg prose-slate"> {{ post.post_text | safe}} </div> my config tailwind contains in plugin section require('@tailwindcss/typography'), that line that I know is necessery How can I make that prose class works like it should? Other classes from standard tailwind works properly. I know also that css is generated for prose, and text is html with all and others but they are without tailwind-css Cheers -
Django get_absolute_url calling same URL as current page
I am trying to add a "+ New Review" link to a page on my Django site that will take you to a 'uuid:pk/new_review/' page that houses a form to submit a URL for a specific post. I am currently facing issues where the link is redirecting to the same page, and I think the issue is stemming from my use of get_absolute_url(), which I am still having trouble getting my head around. urls.py urlpatterns = [ path('<uuid:pk>/', ListingDetailView.as_view(), name = 'listing_detail'), path('<uuid:pk>/new_review/', NewReview.as_view(), name = 'new_review'), ] views.py class ListingDetailView(LoginRequiredMixin, DetailView): model = Listing template_name = 'listing/listing_detail.html' context_object_name = 'listing_detail' login_url = 'account_login' class NewReview(LoginRequiredMixin, CreateView): model = Review template_name = 'listing/new_review.html' fields = ['review'] context_object_name = 'new_review' def form_valid(self, form): form.instance.user = self.request.user form.instance.listing_id = get_object_or_404(Listing, pk = self.kwargs['pk']) return super().form_valid(form) models.py class Review(models.Model): listing_id = models.ForeignKey( Listing, on_delete=models.CASCADE, related_name='reviews', ) user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) review = models.TextField(max_length=5000) def __str__(self): return self.listing_id def get_absolute_url(self): return reverse('listing_detail', args=[str(self.listing_id)]) listing_detail.html ... <p><a href="{{ new_review.get_absolute_url }}">+ New Review</a></p2> ... -
External API in django
I want to call an external API in my django app that build with django Restfull How I can call it? for example in one of the my urls there is an API that deliver wheather status from another API Can every body help me? thank you -
how to fix NoReverseMatch django/python
I want to add a link to my html file: <a href="#" class="btn btn-secondary">Read</a> views.py def detail(request, year, month, day, post): post = HomeData.objects.get( year=year, month=month, day=day, slug=slug) return render(request, 'main/articles/detail.html', {'post': post}) urls.py in app 'main' app_name='main' urlpatterns = [ path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.detail, name='DETAIL'), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('main.urls', namespace='main')), path('', include('main.urls', namespace='main')), ] error Exception Type: NoReverseMatch Exception Value: Reverse for 'articles_detail' not found. 'articles_detail' is not a valid view function or pattern name. Exception Location: D:\django\postsSite\myEnv\lib\site-packages\django\urls\resolvers.py, line 698, in _reverse_with_prefix Python Executable: D:\django\postsSite\myEnv\Scripts\python.exe how can i fix it? -
Get session value from django form
I have 2 forms, one is the main one and the other one opens in a modal window. I need my second form to get the company session value (AIGN_EMP_ID), however, I don't know how to send this value when I call my form from the Context. First form.py class MayoresForm(Form): act_cuenta = () act_fechaini = DateField( widget=DatePickerInput( format=Form_CSS.fields_date_format, options=Form_CSS.fields_date_opts, attrs={'value': Form_CSS.fields_current_date} ), label="Fecha desde: ", required=True, ) act_fechafin = DateField( widget=DatePickerInput( format=Form_CSS.fields_date_format, options=Form_CSS.fields_date_opts, attrs={'value': Form_CSS.fields_current_date} ), label="Fecha hasta: ", required=True, ) def __init__(self, *args, **kwargs): # -------------------------------------------------------------------------------------- self.AIGN_OPCIONES = kwargs.pop("AIGN_OPCIONES") self.PERMISOS = [] # para recuperar los permisos de la tabla __json_values = json.loads(json.dumps(self.AIGN_OPCIONES)) self.PERMISOS = recuperarPermisos(__json_values, 'con.transaccioncab') # -------------------------------------------------------------------------------------- # Obtiene la variable de sesion desde la vista y la asigna al self self.AIGN_EMP_ID = kwargs.pop("AIGN_EMP_ID") super(MayoresForm, self).__init__(*args, **kwargs) self.fields['act_cuenta'] = ChoiceField(label='Cuenta: ', choices=self.get_choices(), required=True) for form in self.visible_fields(): # form.field.widget.attrs['placeholder'] = Form_CSS.fields_placeholder + form.field.label.lower() form.field.widget.attrs['autocomplete'] = Form_CSS.fields_autocomplete form.field.widget.attrs['class'] = Form_CSS.fields_attr_class self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.form_id = Form_CSS.getFormID(self) self.helper.attrs = Form_CSS.form_attrs self.helper.form_tag = True self.helper.form_error_title = Form_CSS.form_err_title self.helper.form_class = Form_CSS.form_class self.helper.label_class = 'col-sm-3 text-right form-control-sm' self.helper.field_class = 'col-sm-6' self.helper.layout = Layout( Div( DivHeaderWithButtons(instance_pk=None, remove_create=False, remove_delete=True, remove_print=True, remove_cancel=False, permisos=self.PERMISOS, save_name=' Consultar'), Div( Div( Div( Div( Div( HTML("<h3 … -
Django: Inherit class with API Data
I want to ask the user for a password in my first view and in the other views use this password to show data on the frontend. So far I just saved the password in a session and I instantiated the API every time I clicked on another view. What I want is to save the state of that API call (for example the token) in this class. I thought I could try with inheritance - I want to know in general if this is a good approach and also what I am doing wrong: class APItoInherit: def create(self, server, username, password): self.APISession = theAPI("https", server, username, password) return self.APIsession class FirstView(APItoInherit, TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... api = self.create(self.request.session.get('url'), self.request.session.get('usr'), self.request.session.get('pwd')) ... return context class SecondView(APItoInherit, TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... tmp = someAPIClassFunction(self.APISession) # <--- break ... return context My goal is to instantiate the API in the first view (for example to get a token) and later on use it to call methods of the API Class implementation. If this cannot be done that way, is there any other way I can comfortably save and hand the API Object (APISession) over … -
How to do ajax pagination with QueryString Parameters in Django?
I want to create pagination with multiple QueryString Parameters, I created regular pagination with Django only but while creating Ajax pagination with multiple QueryString I faced problems. My views: def products(request): products = Products.objects.all() if request.method == 'GET': per_page = request.GET.get("option") paginator = Paginator(products, per_page) # data from get request is not passed properly page = request.GET.get('page') try: product_list = paginator.page(page) except PageNotAnInteger: product_list = paginator.page(1) except EmptyPage: product_list = paginator.page(paginator.num_pages) return render(request, './item/shop.html', {'products': products}) My Query parameter submitting html: <select name="show-product-count" class="form-control" id= "show-product-count"> <option value="9">Show 9</option> <option value="12" selected="selected">Show 12</option> <option value="24">Show 24</option> <option value="36">Show 36</option> </select> My Ajax/Jquery: $(document).ready(function () { $("#show-product-count").on("change", function(){ var selectedValue = $(this).val(); $.ajax({ url : $(this).data('url'), type : "GET", data : {"option" : selectedValue}, dataType : "json", success : function(){ } }); }); }) -
Django. How to get value from multiple checkboxes
Hey I have seen many questions about this but i dont know why it isnt working for me. I have this piece of code in my home.html file: <form action="/result/" method="post"> <div class="form-locat-att"> {% csrf_token %} Location: <input type="text" name="location_input" required/> <p></p><br> <button class="btn btn-block btn-round", name="search_button">Search</button> <p></p> <h5>Zabytki</h5> <p></p> <input type="checkbox" id="museum" name="att[]" value=" Museum OR"> <label for="muzeum"> Museum</label> &nbsp; <input type="checkbox" id="statue" name="att[]" value=" Statue OR"> <label for="pomnik"> Statue</label> &nbsp; <input type="checkbox" id="castle" name="att[]" value=" Castle OR"> <label for="zamek"> Castle</label> &nbsp; <input type="checkbox" id="palace" name="att[]" value=" Palace OR"> <label for="palac"> Palace</label> <p></p> </div> </form> And this is my views.py: def result(request): if request.method == 'POST' and 'search_button' in request.POST: attrac = request.POST.getlist('att[]') locat = request.POST.get('location_input') print(attrac) # (here i have some irrelevant code where i render my context) return render(request, 'przewodnik_app/result.html', context) return render(request, 'przewodnik_app/result.html') I am trying to print attrac which should give me values from the checkboxes i've checked. When i use the .get method with id for example request.POST.get('museum') it returns correct value. When i am using name the list is always empty. -
How to implement function to delete all items from cart (django)
hey guys I made a website in django and it has a cart feature in it . Currently I've implemented a feature that you can delete items but it only deletes them on by one. I'm stuck on how to get the feature to delete all items currently in the cart cart.html {% for cart_item in cart_item %} {% if cart_item.quantity < cart_item.product.stock %} <a <a href="{% url 'cart:full_remove' cart_item.product.id %}" class="custom_icon"><i class="fas fa-trash-alt custom_icon"></i></a> {% endif %} {% endfor %} cart urls.py from os import name from django.urls import path from . import views app_name='cart' urlpatterns = [ path('add/<uuid:product_id>/', views.add_cart, name='add_cart'), path('', views.cart_detail, name='cart_detail'), path('remove/<uuid:product_id>/', views.cart_remove, name='cart_remove'), path('full_remove/<uuid:product_id>/', views.full_remove, name='full_remove'), ] cart views.py def full_remove(request, product_id): cart = Cart.objects.get(cart_id=_cart_id(request)) product = get_object_or_404(Product, id=product_id) cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.delete() return redirect('cart:cart_detail') -
I cannot import a module into python
I'm taking a django course and when I go to put urls, it's causing this problem: Code: Folder structure: -
escape single quotes in django date filter
I have this html code snippet: <td><button value="{{i.0}}" type="button" onclick="setEndActivity({{i.0}}, '{{i.1}}', '{{i.8}}', '{{i.10}}', '{{i.4 | 'date:Y-m-d H:m:s'}}')">End</button></td> I'd like to escape single quotes here: 'date:Y-m-d H:m:s' . Even better to create better mask to ISO format. -
Change inherit field to required in a Serializer
I have a serializer like that: from rest_framework import serializers class MySerializer(serializers.Serializer): field1 = serializers.CharField(required=False) field2 = serializers.IntegerField(required=False) field3 = serializers.BooleanField(required=False) ... I want to inherit this class but changing field1to required=True, who can I do that? I know that I can redefine the field like this: class MySerializer2(MySerializer): field1 = serializers.CharField(required=True) But I dont like to do this. -
How to format variable in template as currency?
I am trying to format a string in a template to display as a currency. {{ object.cost }} Would I be able to do something like "${:,.2f}".format({{ object.cost }}) in the template? -
Bearer Authentication does not work on mobile, however it works on pc ( react, django )
I wrote a React app with a backend on Django that works fine on PC. However, when I open it on my iPhone (ios 15), it does not include Authenticate: Bearer 'my_token'. const getStats = async () => { console.log(accessToken) let response = await fetch('http://192.168.1.2:8000/api/getstats', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer ' + String(accessToken), }, }) Django gets this header when getting requests on PC: {'Content-Length': '', 'Content-Type': 'application/json', 'Host': '192.168.1.2:8000', 'Connection': 'keep-alive', 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjQwMDI3NTExLCJpYXQiOjE2NDAwMjYzMTEsImp0aSI6Ijk0OTdlZGZjZWEzYzQwMTJiYzc5YjQ2ODc4YWJiYWQ2IiwidXNlcl9pZCI6MiwiZW1haWwiOiJ5YnJvdmNAZ21haWwuY29tIn0.nKdBwT4XmKSWlqMP3EYF_pXpLgJAjDR_XuaSsummgbQ', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36', 'Accept': '*/*', 'Origin': 'http://192.168.1.2:3000', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'} As you can see, an Authentication token was provided and everything worked fine {'Content-Length': '', 'Content-Type': 'application/json', 'Host': '192.168.1.2:8000', 'Origin': 'http://192.168.1.2:3000', 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/96.0.4664.101 Mobile/15E148 Safari/604.1', 'Accept-Language': 'en-GB,en;q=0.9', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive'} This one Django gets as header when I send request from my iPhone. And this is my function on Django that print those headers @api_view(['GET']) # @permission_classes([IsAuthenticated]) def getStats(request): print(request.headers) print(request.user) all_cart_elems = Cart.objects.all() all_orders = Orders.objects.all() all_users = Telegram_users.objects.all() print(len(all_cart_elems)) data = { 'cart_elems': len(all_cart_elems), 'orders': len(all_orders), 'all_users': len(all_users) } … -
django taggit similar_objects problem(maybe queryset)
Currently, when searching for a tag like Instagram, an image list page including the tag has been created. I wanted to list the related tag list in one line here, and I found out that the 'taggit' package already has a good function called 'similar_objects'. My 'view.py' is designed to expose only certain tags as follows. If you add "similar_objects," "'ImageTagListView' object has no attribute 'object'" occurs. I think it's a "queryset" problem. Please tell me the solution. Thank you in advance. class ImageTagListView(ImageListView): template_name = 'imageapp/taglist.html' model = Image def get_queryset(self): return Image.objects.filter(tags__name=self.kwargs.get('tag')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tagname'] = self.kwargs['tag'] context["related_items"] = self.object.tags.similar_objects()[:4] return context -
Django - How to add multiple objects to a database dyanmically via a API endpoint use rest_framework
Django supports a method to allow you to query your database and add multiple objects to it using the Objects.create_bulk() I’ve had a good look on google to better understand how to use this method, but i’m not sure how to achieve what it is i’m trying to achieve. Here’s where i’m at so far: I’ve created an api endpoint that lists all the inventory objects that currently exists I’ve also created an api endpoint that allows you to filter by playerId and will return all inventory items that player owns Here’s what i’m trying to do: Create an API endpoint that allows multiple elements to be added to a specified users inventory (playerId) I just need an endpoint to allow a POST method to append multiple elements to a specified player’s inventory, it should look something like this: def add_multiple_items_to_inventory(request, pk): itemsToAdd = Inventory.objects.bulk_create( [Inventory( playerId: 1, elementId: 2, elementId: 2, elementId: 2, elementId: 4, elementId: 7)) serializer = InventorySerializer(data=itemsToAdd) 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) so hitting this endpoint with some data like this -> { playerId:1, elementId: 1, elementId: 1, elementId: 1, elementId: 2, elementId: 2, elementId: 7, } should add elements [1,1,1,2,2,7] to … -
How to add attachments in Sendgrid Django
I'm trying to figure out how to add attachments to my email I am sending through sendgrid. I have an .xlsx file in the same directory however it won't get attached. I currently have my code like this: with open(f'name-{filenumber}.xlsx', 'rb') as fd: encoded = base64.b64encode(fd.read()) attachment = Attachment() attachment.content = (encoded, 'utf-8') attachment.filename = f'name-{filenumber}.xlsx' message = Mail( from_email='email.@email.com', to_emails= os.getenv("RECIPIENT_EMAIL"), subject='Sending with Twilio SendGrid is Fun', html_content='<strong>and easy to do anywhere, even with Python</strong>') message.add_attachment(attachment) try: sg = SendGridAPIClient('SENDGRID_API_KEY') response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) But I keep getting this error AttributeError: 'BadRequestsError' object has no attribute 'message' Along with this: python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request``` -
Unit testing an authenticated user in Django
I am trying to test access as a logged in user. I'm having trouble with the unit test below which won't work with me. class ExampleTest(TestCase): def setUp(self): self.client = Client() self.example_user = get_user_model().objects.create_user( username='exampleuser', email='user@example.com' ) self.example_user.set_password('testing12345') self.example_user.save() def test_taking_too_much_time(self): my_client = self.client #my_client = Client() my_client.login(username='exampleuser', password='testing12345') #my_client.force_login(self.example_user) response = my_client.get('/example/link/') self.assertEqual(response.status_code, 200) I have tried everything, but despite various solutions, I receive a message. AttributeError: 'HttpRequest' object has no attribute 'user' In the project I have a signal that eliminates the 'bug' if I comment on it. @receiver(user_logged_in, sender=User) def log_in(request, sender, **kwargs) I am waiting for feedback. -
String with white space being passed incorrectly in a Django template
I have a variable called "Vintage White" that I am trying to pass to an attribute of an input element like so. <input name={{ attribute_value }}> What I expect is for the element to be rendered like this <input name="Vintage White"> But instead I get this <input name="Vintage" white> How do I pass the entire string with white spaces to the input element so that I get my expected result? -
Public Transportation Webapp in DJANGO : models (many-to-many relationship) for transportation systems and routes
I have to make a webapplication that would allow a userbase to create alerts about controlers in public transportation in a big city. It would include mostly trains and buses. I'm quite stuck with how to create the model. I've already created the Alert that has a station attribute with a one-to-one relationship, and a line attribute also. I have two models : a model Stations, and a model Line. Now each transportation mode (bus/train) has a line, stations and a schedule. I used a many-to-many fields in the Line model, but I don't know how to order the stations, since a bus while go through each station in an orderly fashion, neither how to link that to a schedule. I thought about making another model "Route" with each instance having an attribute Line, Station and Order, but that doesn't seem optimal for routes that have many stations. (Transportations/models.py) class Station(models.Model): Station_name = models.CharField(max_length=200) Station_adress = models.CharField(max_length=300) Station_number = models.PositiveIntegerField(blank=True, null=True) Station_desc = models.CharField(max_length=150, blank=True, null=True) Station_vehicule = models.ForeignKey(Vehicule, on_delete=models.CASCADE) def __str__(self): return f'{self.Station_name} {self.Station_desc}' class Line(models.Model): Line_number = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) Line_name = models.CharField(max_length=200, blank=True, null=True) Line_vehicule = models.ForeignKey(Vehicule, on_delete=models.CASCADE) Line_stations = models.ManyToManyField(Station) def __str__(self): return f'{self.Line_vehicule}: {self.Line_number}' class Line_station(models.Model): … -
I am trying to complete the URL for my Medical Store System
It is my first Personal Project using Django in Python. I am trying to create a Medical Store management System why do I get an error "/admin/API" in the Django rest framework. The error is: "Not Found: /admin/api/ [20/Dec/2021 23:30:15] "GET /admin/api/ HTTP/1.1" 404 5358 Not Found: /admin/api [20/Dec/2021 23:30:20] "GET /admin/api HTTP/1.1" 404 5355" -
django orm AND condition for same key with multiple options
ihave a model WebDocuments with multiple objects of different document type and i want to apply and condition document_type= ['PAN', 'DL'] doc_obj = WebDocuments.objects.filter(is_active=True) q_objects = Q() if document_type: q_objects &= [Q(type=doc) for doc in document_type] check_obj = doc_obj.filter(q_objects) if check_obj: return True return False i want to return True or False wheather both document type exist of not. i have both document type in my db still it returning empty because it filtering both type on save object . is there is any way to do it with and operator or i have to loop queryset with all doc types here is my model class WebDocuments(TimeStampedModel): uuid = models.UUIDField(default=uuid.uuid4, null=True, blank=True) lead = models.ForeignKey(Lead, related_name='web_lead_document') type = models.CharField(choices=DocumentTypeChoices.choices, max_length=100) -
Project Can not be created in Django
Traceback (most recent call last): File "/usr/bin/django-admin", line 2, in from django.core import management ModuleNotFoundError: No module named 'django'