Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
This is my html code can you help me how i convert my code into jquery
This is my html code: In this code i am displaying my blogs without ajax. In ajax, If i display my blogs without refresh page this code will mandatory in ajax calls so please help me how i write this code in jquery {% for blogs in blog %} <div class="card" id="card" style="width: 18rem;"> {% if ".jpg" in blogs.image.url or ".jpeg" in blogs.image.url or ".png" in blogs.image.url %} <img src="{{blogs.image.url}}" class="card-img-top" height="280" width="280" alt="..."> {% endif %} {% if '.mp3' in blogs.image.url %} <audio controls width="320" height="240"> <source src="{{blogs.image.url}}" type="audio/ogg"> </audio> {% endif %} {% if '.mp4' in blogs.image.url or '.mkv' in blogs.image.url or '.HDV*' in blogs.image.url %} <video width='400' controls> <source src="{{blogs.image.url}}" type='video/mp4'> Your browser does not support the video tag. </video> {% endif %} {% if '.3gp' in blogs.image.url or '.AVI*' in blogs.image.url %} <video width='400' controls> <source src="{{blogs.image.url}}" type='video/mp4'> Your browser does not support the video tag. </video> {% endif %} <div class="card-body"> <h5 class="card-title">{{blogs.title}} Written by {{blogs.author}} </h5> <h5 class="card-title">{{blogs.date}} | {{ blogs.time|time:"H:i" }}</h5> <p class="card-text">{{blogs.description}}</p> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group me-2" role="group" aria-label="First group"> <button type="button" data-sid="{{blogs.id}}" class="btn btn-success">Update</button> </div> <div class="btn-group me-2" role="group" aria-label="Second group"> <input type="button" data-sid="{{blogs.id}}" class="btn btn-danger" … -
Python recursion function to change the elements value
Example data = OrderedDict([('VaryasyonID', '22369'), ('StokKodu', '01277NUC'), ('Barkod', 'MG100009441'), ('StokAdedi', '1'), ('AlisFiyati', '272,00'), ('SatisFiyati', '272,00'), ('IndirimliFiyat', '126,00'), ('KDVDahil', 'true'), ('KdvOrani', '8'), ('ParaBirimi', 'TL'), ('ParaBirimiKodu', 'TRY'), ('Desi', '1'), ('EkSecenekOzellik', OrderedDict([('Ozellik', [OrderedDict([('@Tanim', 'Renk'), ('@Deger', 'Ten'), ('#text', 'Ten')]), OrderedDict([('@Tanim', 'Numara'), ('@Deger', '41'), ('#text', '41')])])]))]) It is an XML value if '#text' is inside the dict, it means the other tuples are attributes of the element. I have to insert data to db in this format. [{'@_value': 'Haki', '@_attributes': {'@Tanim': 'Renk', '@Deger': 'Haki'}}] I basically get the #text put in '@_value' key and other tuples inside the '@_attributes' dict. If dict doesn't contain '#text' then I save it as it is. Now if I do it with this function it works. def get_attrs_to_element(value): ## value type should be dict text_value = '' res = [] #check for attributes for key, val in value.items(): if '#text' in key: text_value = value['#text'] del value['#text'] attr_obj = { "@_value": text_value, "@_attributes": dict(value) } res.append(attr_obj) return res return value And I call this function where I am iterating over the whole XML as they are key value tuples. if isinstance(value, dict): whole_dict[key] = get_attrs_to_element(value) Now this works. But I also need this function to work when there is … -
How do i display the objects related to a foreign key in django
my models: class Company(models.Model): name = models.CharField(max_length=250) def __str__(self): return str(self.name) class Products(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="display") engine = models.CharField(max_length=250, blank=True) cyl = models.CharField(max_length=250, blank=True) bore = models.CharField(max_length=250, blank=True) def __str__(self): return str(self.engine) + " (ref:" + str(self.ref) + ")" my views.py: def Companies(request): context = { 'categories': Company.objects.all() } return render(request, 'product_list.html', context) HTML : {% for category in categories %} <h2>{{ category.name }}</h2> {% for item in category.item_set.all %} {{ item_engine }} {% endfor %} {% endfor %} how do i display every objects of Products(engine,cyl,bore) following its name -
Django dynamic form with many to many field
I'm looking for advice and maybe a little help with my problem. I'm trying to save m2m field but in a "user-friendly" way, it's mean instead of using multiple select fields I want to use something different. I have simple classes # here I store all subnet mask for IPv4 addresses class SubnetMask(models.Model): mask = models.CharField(max_length=15) mask_length = models.CharField(max_length=3) class IPv4Address(models.Model): ip = models.CharField(max_length=15) subnet_mask = models.ForeignKey(SubnetMask, on_delete=models.SET('')) class Computer(models.Model): OS_type = models.ForeignKey(OS, on_delete=models.SET('')) computer_name = models.CharField(max_length=100) ip_address = models.ManyToManyField(IPv4Address) description = models.CharField(max_length=1000, blank=True) Now I'm assuming that one PC can have more than one IP. When in DB have will be many IPs, listing and adding the IP address will be frustrating, so I thought I can use multiple-select field with a searching field but I can not find any good solution to use in adding form (I tried to use searchableselect but it only works in admin site). I tried also to prepare my own form using JS, now, I got something like this https://imgur.com/a/zyhZ5kE, but the first element has two fields one is a text field where the user enters the IP, second, the user can select subnet mask (this is code in HTML). The second element … -
Django's Syntax is not translated in the CSS Files in the Statics Folder
In my django project everything is working fine ,my css file is loaded just fine, but in my css file i assigned a background image body:before{background-image: url({% static 'images/bg/bg3.jpg' %}); but it won't load as django's {% static '' %} thing is not translated by django into that image's url, and it also gives me a warning, so what should i do to make django translate that css file or what other ways should make that line work. the css file is succesfully recived by the client browser but that line is still as it is and not translated by dbjango into the image's url which creates that error. Note: I have tried to type that line in the <head> tag in the html file and it worked but it gives me error in the code editor, there must be a better way to do that! -
How to fetch data with no record of the foreign key after a specific date?
This model is completely unrealistic. Please don't ask me this question "why you did this". I just want to present to you the purpose that I want to learn. Think of a student and that student is saving the books he reads in the system. After a long time, the data accumulated, we had to make a query. Sturent.objects.filter(book__isnull=True) In this way, I can fetch students who have no book record. But I want to attract students who are not registered after a current date. In the example above you see student 1 and student 2. Both have book records. Imagine hundreds of students this way. I want to get a list as a queryset of students who are not registered after a current date. Thanks in advance if anyone knows how to do this. -
On creating and activating the virtual environment using pipenv shell
In the book the following picture was said to appear when you code: However when ran pipenv shell, I'm now getting the name of virtual env in the brackets: PS C:\Users\name\Desktop\env> pipenv shell Launching subshell in virtual environment... Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Try the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\Users\name\Desktop\env> What is the reason for this? -
Django - AWS S3 is serving empty static files
I created a S3 bucket and set up the Django static storage with Boto3. The settings are the following DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'imoveis-django' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.sa-east-1.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/' I ran collectstatic and the static files were uploaded to the bucket. However, when they are served, they are empty, as you can see in the picture below. I checked in the bucket and the files are not empty there. -
You are authenticated as allaye, but are not authorized to access this page. Would you like to login to a different account?
so i am trying to update my user profile, the login and registration works well, but when i try to update the user profile it does not work and i dont receive any error. after updating when i try to access the django admin page i get the about error message. let say i login into the admin page as boss which is a super user, and into my app as gate, after updating gate details when i try to access the admin page with had already been loged in by boss, i get the about error message. below are my code. /views.py def signin(request): form = UserLogin(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: login(request, user) return redirect('index') else: return redirect('signin') return render(request, 'login.html', {'form': form}) @login_required() def profile(request): print(request.user) if request.method == 'POST': # current_user = UserProfile.objects.get(username=request.user) form = UserDetailsUpdate(request.POST, instance=request.user) if form.is_valid(): form.save(commit=True) return redirect('profile') form = UserDetailsUpdate(instance=request.user) return render(request, 'profile.html', {'form': form}) /models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=20, blank=True) website = models.URLField(blank=True) image = models.ImageField(blank=True) def __str__(self): return self.user.username /forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) sex = forms.CharField() class Meta: model = User fields = … -
I want to keep the changed text color even when the link is clicked
I am a student learning Django. I changed the text color when I clicked the Nav-link, and it disappears the moment I go to the link by clicking the link button. It remains the moment you put the mouse on it, but the text color disappears the moment you release the mouse. How do I get a link to remain after visiting? Code : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="https://fonts.googleapis.com/css2?family=Comfortaa:wght@300&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <style> .menu-wrap li{ display: inline-block; padding: 10px; } .menu-wrap a[selected]{ color:#637B46; font-weight: 600; } </style> </head> <body> {% load static %} <link rel="stylesheet" href="{% static 'main.css' %}"> <div class="text-center navbar navbar-expand-md navbar-light"> <a class="navbar-brand" href="/" style="margin-top:30px;">ZERONINE</a> <button class="navbar-toggler" style="margin-top:30px;" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> </div> <nav class="navbar navbar-expand-lg"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="menu-wrap" style="margin: auto;"> <li class="nav-link"><a class="nav-link" href="/" class="nav-link">전체상품</a></li> {% for c in categories %} <li class="nav-link"><a href="{{c.get_absolute_url}}" class="nav-link {% if current_category.slug == c.slug %}active{% endif %}" >{{c.name}}</a></li> {% endfor %} <li class="nav-link"><a href="{% url 'zeronine:post' %}" class="nav-link">자유게시판</a></li> {% csrf_token %} {% if user.is_authenticated %} <li class="nav-link"><a href="{% url 'zeronine:logout' %}" class="nav-link"><b>{{ … -
django-admin-autcomplete-filter not working
Resource https://pypi.org/project/django-admin-autocomplete-filter/ I have used the pip command to install this, but when I add to my installed_apps list, I get an error and cannot run my dev environment. OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', 'admin-auto-filters', ] Am I doing something wrong? -
request.user in django is None for anonymous user
using python 3.6.8 django 2.2 I have started seeing a weird thing in server logs where anonymous users in django are not being added to the request, I am using the django.contrib.auth.context_processors.auth as my first context-processor. suddenly I am seeing 'NoneType' object has no attribute 'is_anonymous' This comes from a custom context-processor that is added after the auth processor This has gotten me really stumped -
is django good for future career [closed]
is Django is good for a future career. actually, I want to become a full-stack developer please guide me -
AllValuesFilter shows data from other than the user, even when provided a queryset (Django-filters)
I'm trying to apply a AllValuesFilter to filter on a tag-field, such that the user can filter on the tag the given user has provided. I want only the logged-in user to be able to see its own tag. Right now I have the following: #filters.py import django_filters class Filter(django_filters.FilterSet): #zip(NICK_NAME_CHOICES,NICK_NAME_CHOICES) tag = django_filters.AllValuesFilter(field_name = "tag", label="Tag") and in my view.py from .filters import Filter def my_view(request): user = request.user user_products = MyModel.objects.filter(user=user).all() #Products added by the user filter = Filter(request.GET,queryset = user_products) . . context = {"filter":filter} return render(request,"my_html.html",context = context) the issue is that the choice-menu shows tags created by all users, and not just the one logged in. I thought the queryset was to avoid exactly this behaviour? -
DRF serialization - many-to-many field with through
How to serialize data from many-to-many field with through parameter? I have 3 models: class Ingredient(models.Model): name = models.CharField( max_length=200, ) measurement_unit = models.CharField( max_length=200, ) class Recipe(models.Model): name = models.CharField( max_length=200, ) ingredients = models.ManyToManyField( Ingredient, through='RecipeIngredientsDetails', ) class RecipeIngredientsDetails(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, ) ingredient = models.ForeignKey( Ingredient, on_delete=models.CASCADE, ) amount = models.FloatField() My serializers: class IngredientSerializer(ModelSerializer): # amount = ??? class Meta: model = Ingredient fields = ["id", "name", "amount", "measurement_unit"] class RecipeSerializer(ModelSerializer): class Meta: model = Recipe fields = ["name", "ingredients"] depth = 1 Now, I get: { "name": "Nice title", "ingredients": [ { "id": 1, "name": "salt", "measurement_unit": "g" }, { "id": 2, "name": "sugar", "measurement_unit": "g" } ] } I need amount-value in every ingredient. How can I implement it? -
Send a file as response to a post request
i m using django drf and react native, i m sending an image from the frontend and expecting to recieve a file as a response containing the OCR result of the image, However i haven't been able to acheive that i m used HttpResponseRedirect to redirect to the file url but i couldn't really figure out how to do it so i decided to currently return a json response with the file url still getting nothing: from processing.models import Uploads from rest_framework import viewsets from rest_framework.response import Response from django.http import HttpResponse , JsonResponse, response from .serializers import UploadSerializer from django.shortcuts import render from django.http import HttpResponseRedirect from digitize.models import File # Create your views here. class UploadView(viewsets.ModelViewSet): queryset=Uploads.objects.all() serializer_class=UploadSerializer def methodes(self,request,*args,**kwargs): if request.method=='POST': serializer=UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() data=File.objects.filter(id=str(File.objects.latest('created_at'))) file_data=data.values('file') response = JsonResponse(file_data, headers={ 'Content-Type': 'application/json',}) #'Content-Disposition': 'attachment; filename="foo.txt"', }) return(response) return HttpResponse({'message':'error'},status=400) elif request.methode=='GET': images=Uploads.objects.all() serializers=UploadSerializer(images,many=True) return JsonResponse(serializers.data,safe=False) -
Django overwrite validate MultipleChoiceField and remove queryset required
i'm tring to make a custom MultipleChoiceField but i have 2 problems 1st seems i can't overwrite validate function... when i try it print("i'm here") never come in my console even when that field triggers invalid_choice error class OdsTaggerlMultipleChoiceField(forms.ModelMultipleChoiceField): required=False def label_from_instance(self, obj): return obj.tag def __init__(self, *args, **kwargs): super(OdsTaggerlMultipleChoiceField, self).__init__(*args, **kwargs) self.to_field_name="tag" self.widget.attrs['class'] = 'odstagger' def validate(self, value): #azione cattiva valida la qualunque if self.required and len(value) < 1: raise forms.ValidationError(self.error_messages['required'], code='required') print("i'm here") 2nd problem is about queryset it's required to use that field, but i think resolving 1ts problem i can just use a empty choices list tags = OdsTaggerlMultipleChoiceField(queryset=Tag.objects.all()) do you know how resolve that? -
Django: how to update a user profile
I'm currently creating a workout application/blog using Django. What I'd like to do is every time the user enters in a new blog post, the program should look at the exercise fields and update their user profile with the max values for various lifts (deadlift, bench press, etc). I'm quite new to Django and it hasn't quite clicked on how models can interact with each other in this way I have the Profile class in user\models, which is the area I want to update. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') max_squat = models.FloatField(default=0.0) max_bench = models.FloatField(default=0.0) max_deadlift = models.FloatField(default=0.0) max_ohp = models.FloatField(default=0.0) squat_reps = models.IntegerField(default=0) bench_reps = models.IntegerField(default=0) deadlift_reps = models.IntegerField(default=0) ohp_reps = models.IntegerField(default=0) Then I have the blog post class, which has the variables in which the user enters for each blog post class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() workout = models.CharField(max_length=100, choices=const.WORKOUTS, default='deadlift') weight = models.CharField(max_length=200) sets = models.IntegerField(default=0) reps = models.CharField(max_length=200) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Tried something like this but no joy: profile = Profile() profile.max_deadlift = weight profile.save() Any help is appreciated. -
Calling related name models in query (Q) "Django"
I have profile model like : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) and I have a search view like : def users_search_view(request): query = request.GET.get('q') users = User.objects.filter(Q(email__icontains=query)|Q(username__icontains=query),is_superuser=False,is_staff=False) ctx = {'users':users, 'q':query} return render(request,"staff/users_search.html", ctx) I want to have search by first name and also last name from Profile model, in my search, How can I make something like Q(email__icontains=query) for related modals ? -
Why is django showing variable (DateTimeFIeld) as None, even though it exists in SqLite?
I'm brand new to django and sqlLite have the problem that the value from a variable exists in SqlLite but it doesn't exist in django, using the following code: @api_view(['GET']) def predmetiSedamDana(request): p=Podaci.objects.select_related("id_predmeta","id_sedmice","id_semestra").all() p_json=[] for i in p: p_json.append({'broj_sedmice': i.id_sedmice.broj_sedmice,'naziv': i.id_predmeta.naziv,'broj_prisutnih': i.broj_prisutnih, 'pocetak_termina': i.id_predmeta.pocetak_termina,'kraj_termina': i.id_predmeta.kraj_termina, 'pocetak_semestra': i.id_semestra.pocetak_semestra,'dan': i.id_predmeta.dan,'vrsta': i.id_predmeta.vrsta.vrsta}) print(i.id_predmeta.dan) r=json.dumps(p_json, indent=1, cls=DjangoJSONEncoder) return HttpResponse(r) All the data that I got exists, except for i.id_predmeta.dan which is none, but in SqLite the value from i.id_predmeta.dan exists. SqlLite Django But if I put in SqlLite console, the following query update podaci_predmet set dan=datetime() where id=1; and rerunning the following function it returns a date. SqlLite after running update query Does anyone else know why this keeps happening, is there any other way to fix it! Any tip is useful, and thank you in advance! -
How to resolve multiple querysets in graphene.Union?
I want to create a graphene.Union type of multiple existing types. I am able to resolve it but it is not in my required format. Schema from graphene_django import DjangoObjectType class ageType(DjangoObjectType): class Meta: model = age class ethnicityType(DjangoObjectType): class Meta: model = ethnicity class combinedType(graphene.Union): class Meta: types = (ageType, ethnicityType) class Query(graphene.ObjectType): defaultPicker = graphene.List(combinedType) def resolve_defaultPicker(self, info): items = [] age_q = age.objects.all() items.extend(age_q) ethnicity_q = ethnicity.objects.all() items.extend(ethnicity_q) return items The query I am using in the graphql admin: { defaultPicker{ ... on ageType{ id age } ... on ethnicityType{ id ethnicity } } } I want to get a output like this: { "data": { "defaultPicker": [ 'ageType': [{ "id": "2", "ethnicity": "American", "ethnicityFr": "Test" }], 'ethnicityType': [{ "id": "1", "familyPlans": "3 kids", "familyPlansFr": "3 enfants" }], ] } } I tried many things but couldn't find a way to resolve it. -
currentTime of audio not changing in js for django input
I have an input range slider <input type="range" min="0" max="100" value="0" id="duration_slider" onchange="change_duration()" > I take my audio file from HTML <audio id = "mysong"> <source src = "{{song.song.url}}" type = "audio/mp3"> </audio> So, I want to change the currentTime of the audio on changing the slider (seeking). For this I have written so far let slider = document.querySelector('#duration_slider'); var mysong = document.getElementById('mysong'); function change_duration(){ mysong.currentTime = mysong.duration * (slider.value / 100); console.log(mysong.duration * (slider.value / 100)); console.log(mysong.currentTime); } And to update the slider as the music progresses, I have function range_slider(){ let position = 0; if(!isNaN(mysong.duration)){ slider_position = mysong.currentTime * (100 / mysong.duration); slider.value = slider_position; } if(mysong.ended){ play.innerHTML = '<i class="fa fa-play" aria-hidden="true"></i>'; } } From console, I can see that the value of mysong.currentTime is not changing and always returns to 0. Eg of a value on console 40.22376 and 0 respectively. And every time I try to seek the slider, the song restarts. Edit: The code seems to work fine if I directly take audio input from HTML. But not when I use song from django. -
Django Mixin, Python Inheritance behaviour - Returning old values for multiple classes
I wanted to clarify a behavior in python Here's a snippet written in django from django.shortcuts import render from django.views.generic import CreateView, UpdateView, TemplateView from testapp.models import TestCategory # Create your views here. class xMixin: someVal = {} def get_someval(self): return self.urlVal def get_value(self): return get_someval() class TestCategoryCreateView(xMixin, TemplateView): model = TestCategory template_name = "test_cat.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["urlv"] = self.get_value() return context class TestCategoryUpdateView(xMixin, TemplateView): model = TestCategory template_name = "test_cat.html" def get_someval(self): urlval = super().get_someval() urlval['123'] = 'abc' return urlval def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["urlv"] = self.get_value() return context I was expecting the context["urlv"] getting their respective values.. for TestCategoryUpdateView, it should be { '123': 'abc' } and for TestCategoryCreateView, it should be {} But, when i do the following steps, it results differently Visit create view url -> urlv is {} Visit update view url -> urlv is { '123' : 'abc' } Visit create view url again -> urlv is { '123' : 'abc' } Visit create view url anytime from this point -> urlv is { '123' : 'abc' } What would be a good way to avoid this behaviour ? -
To calculate the number of days between two specified days in Django?
I'm a student studying Django. I want to calculate the number of days between the two specified dates. Currently, View has specified two variables and attempted a subtraction operation, but the following error is being output: Could not parse the remainder: ' - today' from 'product.due_date|date:"Ymd" - today' How should I solve this problem? I would appreciate it if you could give me an answer. Attached is models.py and View.py below. models.py def product_detail(request, id, product_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) designated_object = Designated.objects.filter(rep_price='True') element_object = Element.objects.all() value_object = Value.objects.all() today = DateFormat(datetime.now()).format('Ymd') return render(request, 'zeronine/detail.html', {'product':product, 'products':products, 'current_category': current_category, 'categories':categories, 'designated_object': designated_object, 'element_object':element_object, 'value_object':value_object, 'today':today}) views.py class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() Created as {product.due_date|date:"Ymd" - today}}. -
Change text color when clicking Nav-link
I am a student learning Django. The code I wrote is as follows, but when I run it, the text becomes bold only when I select the text margin, and when I click the text, there is no change in the text. I want the text to be bold when I click on it. What should I do? I'd appreciate it if you could tell me how. code : <style> .menu-wrap li{ display: inline-block; padding: 10px;} .menu-wrap li.selected{ color:green; font-weight: 600; } </style> <ul class="menu-wrap"> <li class="nav-link"><a href="#">link1</a></li> <li class="nav-link"><a href="#">link2</a></li> <li class="nav-link"><a href="#">link3</a></li> <li class="nav-link"><a href="#">link4</a></li> </ul> <script> const menuWrap = document.querySelector('.menu-wrap'); function select(ulEl, aEl){ Array.from(ulEl.children).forEach( v => v.classList.remove('selected') ) if(aEl) aEl.classList.add('selected'); } menuWrap.addEventListener('click', e => { const selected = e.target; select(menuWrap, selected); }) </script>