Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels Change HTML/Javascript For Everyone
I want to make it so if a user disconnects from the websocket their status will change to "offline" for everyone that is viewing the user's profile page. I have successfully done so for detecting when users are online but using the same code for disconnecting doesn't work. How should I go about doing this? Here's the code for the Javascript activityWS.onmessage = function(event) { var parsedDict = JSON.parse(event['data']); profileUrl = window.location.origin + '/account/' + parsedDict['user'] + '/'; if (window.location.href == profileUrl) { $('.online-status').text('Online'); } } $(window).on('beforeunload', function(event) { // won't change to offline but online changing works if (window.location.href == profileUrl) { $('.online-status').text('Offline'); } }); -
Cannot log in to token endpoint with username/password: drf token auth and custom user model, Django
I have a basic Django app using Django rest framework, a custom user model inheriting from the default, and basic token authentication. I am able to generate a token for any user by running python3 ./manage.py drf_create_token {USERNAME/EMAIL} and authenticate relevant requests with it. However, when I attempt to hit my token endpoint (in this case http://127.0.0.1:8000/api/token/, or the equivalent for the deployed app), I get { "non_field_errors": [ "Unable to log in with provided credentials." ] } My request body (application/json) is like: { "username": "test@test.com", "password": "test" } I have ensured that the user is active; that the password is correct; and that the username is the same as the email. My custom user class: class Customer(AbstractUser): first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) email = models.EmailField(unique=True) phone_number = PhoneNumberField(unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) is_active=models.BooleanField(default=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["password", "phone_number", "first_name", "last_name", "username"] def __str__(self): return f"{self.first_name} {self.last_name}" relevant urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/users/', include('customer.urls')), path('api/token/', obtain_auth_token, name="auth_token"), ] in settings.py I have the following: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'phonenumber_field', 'customer', 'contact', 'rest_framework', 'rest_framework.authtoken', ] ... REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } ... … -
Django import existing Ppasswords from PHP site that used password_hash()
I need to import a list of users and hashed passwords from an old PHP site that used password_hash() to a new django site. The stored passwords look like this: $2y$10$ZnxKDPbqOfACnGmQeN76o.UtdwWBFBCCLTiGnvCSvl/zqIBeVxhai I found Django password hasher using php format of function password_hash() on here when trying to look this up, and I think that will help for the NEXT step. But currently I can't setup an import process that will correctly bring over the old passwords. When I try to manually create the users during the import process it refuses the password stating "Invalid password format or unknown hashing algorithm." when I look at the users after the import runs. I think I am just going about this totally incorrectly, here is an example snippet where I create the users. usertest = User(username='testguy',email='testguy@test.com',password='$2y$10$ZnxKDPbqOfACnGmQeN76o.UtdwWBFBCCLTiGnvCSvl/zqIBeVxhai') That results in no password being store. Using the create_user function results in the user being created but with that hashed password output as their password: User.objects.create_user(username='testguy',email='testguy@test.com',password='$2y$10$ZnxKDPbqOfACnGmQeN76o.UtdwWBFBCCLTiGnvCSvl/zqIBeVxhai') How can I just get these passwords stored properly in the new database so I can move onto the next step of actually checking against those passwords? -
is it possible to customize e.g an app model field with html/css
I have this model field that holds the description(image from django-admin) but when I print it out on the page it looks like the following(image from django-admin): enter image description here so is it possible to edit the description field so it looks better and is more readable using html/css etc? -
what's the most efficient way to check for orphans when deleting objects in Django?
Say I have a model with a Things table and a table of relationships between the things called ThingRelations. It should not be possible to delete a Thing when there are ThingRelations that point to it, and when there are no more ThingRelations pointing to a given Thing, it should be deleted. I'm currently trying to implement that with signals.post_delete like this: from django.db import models class ThingRelation(models.Model): first_thing = models.ForeignKey('Thing', on_delete=models.PROTECT) second_thing = models.ForeignKey('Thing', on_delete=models.PROTECT) class Thing(models.Model): name = CharField(max_length=260) @receiver(models.signals.post_delete, sender=ThingRelation) def check_relation_and_delete(sender, instance, *args, **kwargs): for thing_id in [instance.first_thing, instance.second_thing]: first_thing_match = ThingRelation.objects.filter(first_thing=thing_id).exists() second_thing_match = ThingRelation.objects.filter(second_thing=thing_id).exists() if not first_thing_match and not second_thing_match: Thing.objects.get(pk=thing_id).delete() Is this the most efficient way to find and delete orphaned Things? I'm very new to databases in general, but won't filtering the (potentially quite large) Things table four times for every deleted ThingRelation be slow when deleting many objects at once? Is there some kind of SQL or Django functionality that makes it so this code isn't run for every object in a bulk operation? -
Django allauth password reset doesn't work when clicking the link from email, but works otherwise
What is supposed to happen: The request is completely handled by the django-allauth package which is supposed to detect the token, save it to the session, redirect to the 'change your password' page, and finally load the token from the session. The problem: The password reset function does not work when clicking the link from the email (Bad Token), but if I copy-paste the link into the url bar or click the href in Inspect Element mode it DOES work. Note: It also works if I reload the page after seeing "Bad Token" I click the link from inside an email app on my mobile device The error: When you click the link from your email you make it all the way to the 'change your password' page but you get a "Bad Token" error as no Token was found in the session. Format of the link emailed to the user: <a href="https://subdomain.url.com/ls/click?upn=DEcd6nIgEEAvb4Zt..." rel="noreferrer" safedirecturl="https://www.google.com/url?q=https://sudomain.url.com/...">link text</a> For clarification, both the href and the safedirecturl work fine if I copy-paste it into the url bar Conclusion: So far, these are my only guesses at the cause of the issue: An external website is referring the user to the page. The safedirecturl … -
how do I manage deletion with multiple foreign keys to the same table in Django?
Say I have a model with a Things table and a table of relationships between the things called ThingRelations. It should not be possible to delete a Thing when there are ThingRelations that point to it. This is how I'm trying to implement that: from django.db import models class ThingRelation(models.Model): first_thing = models.ForeignKey('Thing', on_delete=models.PROTECT) second_thing = models.ForeignKey('Thing', on_delete=models.PROTECT) class Thing(models.Model): name = CharField(max_length=260) How do I automatically delete a Thing when there are no more ThingRelations pointing to it? -
How to define one to many relationship in django
I have a condition that has one to many relationship scenarios because I will have multiple projects inside one account. models.py class Account(models.Model): name = models.CharField(max_length=255, default='') class Project(models.Model): account = models.ForeignKey(User, on_delete=models.CASCADE, null=True) how can I manage this scenario, currently I'm getting the following error: django.db.utils.ProgrammingError: relation "project_account_id_7d9b231b" already exists -
Get many to many relationship object from parent model django
I have the following models and I want to query that if any tag exists in any package room so the query should not return that tag, only return those tags which don't have any package room. models.py class PackageRoom(models.Model): tags = models.ManyToManyField(Tag) class Tag(models.Model): name = models.CharField(blank=True, null=True) views.py queryset = PackageRoom.objects.filter(project_id=project_id).prefetch_related('tags') serializer = PackageRoomListSerializer(queryset, many=True) tag_qs = Tag.objects.filter(project_id=project_id) tag_slz = TagSerializer(tag_qs, many=True) return Response({ 'room_packages': serializer.data, 'individual_packages': tag_slz.data }) -
ajax problem with Django {{ form|crispy }} vs. {{ form.as_p }}
I have a set of dependent dropdowns that depend on the ajax function to work. The ajax works fine with {{ form.as_p }} but it seems never fire when I replace {{form.as_p}} with {{form|crispy}} . As you can see in my html, the only difference is in which one is commented out. {% extends "base.html" %} {% load tailwind_filters %} {% block content %} <div class="max-w-lg mx-auto"> <a class="hover:text-blue-500" href="{% url 'leads:lead-list' %}" >返回客户名单</a > <div class="py-5 border-t border-gray-200"> <h1 class="text-4xl text-gray-800">{{lead.name}}</h1> </div> <form id="leadForm" method="POST" class="mt-5" enctype="multipart/form-data" data-cities-url="{% url 'leads:ajax_load_cities' %}" novalidate> {% csrf_token %} {{ form|crispy }} {% comment %} {{ form.as_p }} {% endcomment %} <div class="flex py-6 "> <a href="{% url 'leads:lead-delete' lead.pk %}" class="flex ml text-white bg-indigo-200 border-0 py-2 px-6 focus:outline-none hover:bg-indigo-600 rounded-md"> Delete</a> <button type='submit' class=" ml-auto text-white bg-blue-500 hover:bg-blue-600 px-6 py-2 rounded-md"> Submit </button> </div> </form> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_region").change(function () { //var dateNow = new Date().getTime() + Math.random(); var url = $("#leadForm").attr("data-cities-url"); var regionId = $(this).val(); $.ajax({ url: url, data:{ 'region': regionId }, success: function (data){ $("#id_city").html(data); } }); }); </script> {% endblock %} -
Problem with deploiement in Heroku for Django APP
Well I've a problem that I can't find a solution. I've already try to deploy to heroku with mysql and postgresql and i've always some kind of a error. The app works just fine in local. The log: Cannot execute silk_profile as silk is not installed correctly. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/init.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/init.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File … -
Its necessary to start an app in Django to load javaScript files?
i'm making a portfolio on Django + Python, and i have successfully loaded all the assets/templates from my project, (such as .css, .jpg, .png files) but the javascript files '.js' are not working. i saw several questions about this issue with Javascript, and i tried all of the solutions that i saw. i have the {% load static %} putted in the beginning of my index.html file i also putted the <script src="{% static 'assets/js/main.js' %}"></script> before each call to the files my static settings are the following: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'portfolio/static/') ] everything seems to be OK in the settings.py file , and the website can load all the images, css, etc.. but as i mentioned before, the javascript seems to not loading. i don't have an app created in my Django project, the dir tree is the following: ├── /Desktop/portfolio ├── manage.py ├── portfolio │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── static │ │ ├── assets │ │ │ ├── css │ │ │ │ ├── files.... │ │ │ ├── js │ │ │ │ ├── breakpoints.min.js │ │ │ │ ├── … -
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.