Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render nested formset and save in django?
Problem: I have a problem with third form that has nested form at first it renders properly when I delete any child form that nested from all the form gets deleted. how can I fix that End Goal: I wanted to built signup form that consists of three forms first form is basic login info, second form can have multiple instances of the single form where the user can add more form or remove it. and third form if nested from where the user also can add from or remove it. all these in under a single submit button. What I have done: At this point i'm able to build all of the forms and stored first two forms that are basic signup info and second form that have multiple instances. # model.py class Vendor(BaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) address = models.CharField(max_length=100) mobile_no = models.CharField(max_length=12) gst = models.CharField(max_length=20) code = models.CharField(max_length=20) def __str__(self): if (self.user.first_name != None): return self.user.username else: return self.user.first_name # Material/s that vendor can process class VendorMaterial(BaseModel): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) material = models.ForeignKey(Material, on_delete=models.CASCADE) class VendorProcess(BaseModel): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) process = models.ForeignKey(ProcessType, on_delete=models.CASCADE) def _get_full_name(self): return self.process full_name = property(_get_full_name) def __str__(self): return self.process.name … -
unindent does not match any outer indentation level in the custom user model
I try to add a custom column in the Django default user model, what annoying me was there is an error pops up to me, "unindent does not match any outer indentation level". Here is the code below email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) keyStore = models.CharField(max_length=32,unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) The error is pointing at the second row the keyStore. How can I fix that? -
Django, Modeling Related Dates
I'm trying to make a Django app that tracks activities. Each activity has both a start and end date. I would like to have these dates be able to relate to one another. This would look like activity 1 would end on 1/1/2020 and activity 2 would start on 1/1/2020. If I were to then update activity 1 end date to 1/7/2020, I would like activity 2 to then start on 1/7/2020. I think I would want an Activity model and a Date model. I can relate a date to an activity, I just don't know how to model the waterfall effect of relating a date to another date in the same model, while relating each date to the appropriate activity instance. I'm also happy to split the dates into 2 models (StartDate, EndDate) if that makes it cleaner. Open to any solution. Thank you in advance for any help. -
What is the best way to implement Django 3 Modal forms?
I appreciate it if somebody gives the main idea of how to handle submission/retrieval form implementation in Bootstrap modals. I saw many examples on google but it is still ambiguous for me. Why it is required to have a separate Html file for modal-forms template? Where SQL commands will be written? What is the flow in submission/retrieval forms (I mean steps)? What is the best practice to implement these kind of forms? I'm fairly new to Django, please be nice and helpful. -
which should come first creating a django user or a stripe payments charge?
I am using Django and stripe checkout. When someone new comes to the site, wanting to join and pay by credit card, I need to create a new user (ie setup a user name and password) as well as charge them (via stripe's API). From a code and UX perspective, which should come first? Or, better, can I do both in one step? Note: various web tutorials discuss these separately but never together. -
How to use ci.yml to declare env variables to be used in python?
-in gitlab-ci.yml variables: SECRET_KEY: secret_key DB_NAME: camel_backend DB_USER: postgres DB_HOST: mdillon-postgis DB_PORT: 5432 DB_PASSWORD: '' -in django DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } Django doesn't seem to pick up the variables declared on CI when running pipeline. How do I properly declare the env variables on testing? -
How can i create multiple objects in one request ?, in which each objects have file field
I'm trying to create multiple documents objects, when i send request without file filed it create multiple objects, but i don't know how to send multiple objects with filefiled from 'form-data' of postman or from raw data in json format. Please suggest me what can i do for this. My Document Model is: class Document(models.Model): employee = models.ForeignKey(EmployeeInfo, on_delete = models.CASCADE) document = models.CharField(max_length=255, help_text='passport') date_added = models.DateField() valid_until = models.DateField(null = True, blank = True) detail = models.TextField(null=True, blank=True) attachment = models.FileField(upload_to='attachments', null=True, blank=True) for this my view is : class DocumentAPICreateView(CreateAPIView): serializer_class = DocumentSerializer permission_classes = [IsAuthenticated] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many = True) if serializer.is_valid(): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) response = create_response(True,data = serializer.data) return Response(response, status=status.HTTP_201_CREATED, headers=headers) else: response = create_response(False, err_name = serializer._errors) return Response(response, status = status.HTTP_400_BAD_REQUEST) when i send data without attachment it works like this: [{ "employee":38, "document":"Trial2", "date_added":"2019-12-10" }, { "employee":38, "document":"Trial3", "date_added":"2019-12-10" }] How can i send objects list with attachment field? -
Accessing a BoundField on a Form instance
>>> form = ContactForm() >>> print(form['subject']) <input id="id_subject" type="text" name="subject" maxlength="100" required> I have taken this from the documentation, however i am not sure how it is possible to access a Form instance like a dictionary from form['subject'] Does anyone know how this is implemented? -
Django inline formset use for ManyToMany field
I'm trying to get an inline formset working to display child class fields I can edit in a form. I've been following Working with nested forms but there's some aspect I don't understand as the inline formset render produces delete checkboxes but no select element. I was using ManyToManyField without the through parameter but it seems I need to explicitly define NotebookTag and use the through parameter to create an inline formset. models.py class Tag(models.Model): name = models.CharField(max_length=63) class Notebook(models.Model): title = models.CharField(max_length=200) tags = models.ManyToManyField(Tag, through='NotebookTag') class NotebookTag(models.Model): notebook = models.ForeignKey(Notebook, on_delete=models.PROTECT) tag = models.ForeignKey(Tag, on_delete=models.PROTECT) views.py from .models import Notebook, Tag, NotebookTag from django.forms.models import inlineformset_factory TagFormset = inlineformset_factory(Tag, Notebook.tags.through, fields=('tag',)) class NotebookUpdateView(UpdateView): model = Notebook template_name = 'notebook_edit.html' fields = '__all__' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) if self.request.POST: context["children"] = TagFormset(self.request.POST) else: context["children"] = TagFormset() return context Essentially I want to be able to edit or add new tags to associate with a Notebook -
Django soft form-validation for fuzzy matches. Allow validation to be skipped on second form submit
I have a Django form which I would like to 'soft-validate'. By soft-validation I mean: on the first submit attempt, the clean_name() methods raise ValidationError and the View re-renders the form with a field error displayed informing the user that this may be a duplicate entry; but on the next submit, the ValidationError is ignored and the form is saved. Is there any way in the Form class to detect the number of submit attempts, and conditionally toggle the validation? FYI my usage case for soft-validation is: - checking existing records for near-matches on certain CharFields. I am using Postgres trigram similarity for this. # views.py class addFoo(LoginRequiredMixin, IsStaffMixin, CreateView): model = Foo template_name = "Foo/Foo_form.html" form_class = FooUpdateForm # forms.py class FooUpdateForm(forms.ModelForm): class Meta: model = Foo fields = [ "id", "name", ... ] def clean_name(self): name = self.cleaned_data["name"] QS = ( Foo.objects.annotate(similarity=TrigramSimilarity("name", name)) .filter(similarity__gt=0.3) .exclude(id=self.instance.id) .order_by("-similarity") ) names = list(QS.values_list("name", flat=True)) if len(names) > 0: message_1 = f"This name is similar to {len(names)} other records. Are you sure it is not a duplicate?</br>& raise forms.ValidationError( mark_safe(message_1 + ("</br>&emsp;").join(names)) ) return name My thoughts I've tried toggling a hidden form-field from the clean method, but the toggled state doesn't … -
Run .env file in django app with python-dotenv when starting shell
I'm trying to use python-dotenv to run the .env file when running ./manage.py shell. But .env isn't run when I start shell. Nothing different than normal happens. What I've done: installed python-dotenv with pip install python-dotenv in my virtual environment added a .env file in the same directory as my project settings.py Also added below to settings.py: from dotenv import load_dotenv load_dotenv() For context, my .env looks like: export PYTHONSTARTUP=`pwd`/.pythonrc.py echo "environment variables set" And I'm exporting .pythonrc.py so I can do some imports when shell is loaded. I'm pretty new to django. Am I missing something obvious? -
USER Object is not iterable, pylor or haystack error
Traceback (most recent call last): File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/agp/PycharmProjects/AGP/AGP_2_7/artifacts/views.py", line 352, in upload artifact, admin = saveArtifact(request.POST, artifact_object_type, artifact_form, request.user)# here is error File "/home/agp/PycharmProjects/AGP/AGP_2_7/artifacts/views.py", line 519, in saveArtifact specific_form.save() # here is error File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/forms/models.py", line 458, in save self.instance.save() File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/db/models/base.py", line 790, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/signals.py", line 52, in handle_save index.update_object(instance, using=using) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/indexes.py", line 284, in update_object backend.update(self, [instance]) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/backends/solr_backend.py", line 60, in update docs.append(index.full_prepare(obj)) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/indexes.py", line 208, in full_prepare self.prepared_data = self.prepare(obj) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/indexes.py", line 199, in prepare self.prepared_data[field.index_fieldname] = field.prepare(obj) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 279, in prepare return self.convert(super(IntegerField, self).prepare(obj)) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 88, in prepare values = self.resolve_attributes_lookup(current_objects, attrs) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 115, in resolve_attributes_lookup values.extend(self.resolve_attributes_lookup(current_objects_in_attr, attributes[1:])) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 115, in resolve_attributes_lookup values.extend(self.resolve_attributes_lookup(current_objects_in_attr, attributes[1:])) File "/home/agp/.virtualenvs/AGP/lib/python3.6/site-packages/haystack/fields.py", line 107, in resolve_attributes_lookup for current_object … -
Inserting an element in an ordered list in a Django model
i'm trying to figure out how to create an ordered list of elements in a Django model. I'm trying to extend the User model to add a rank (like military rank) to a user. I would like to sort/filter the users per rank, and I would like to store an svg graphical representation of a rank. I would like to use the rank level to establish a hierarchy amongst users, so the rank level must be unique. Lastly, I would like to be able to insert or delete a rank if change arise in the future. To achieve this, I created a table for the ranks like so: class Rank(Models.model): rank = models.CharField(max_length=30) level = models.IntegerField(blank=False, unique=True) image = models.ImageField() What I would like is the ability for the level field to update itself if I insert a new rank between 2 already existing ranks. For example, let's say I create the following ranks: id [pk] | rank | level | image 1 | soldier | 1 | soldier.svg 2 | sergent | 2 | sergent.svg I then want to insert "corporal" at level 2 so that the table would look like: id [pk] | rank | level | image … -
How should I set up volumes for multi-task database service in docker swarm?
I am new to Docker and I want to do mini-project with Docker Swarm. I built docker image with my Django app. In dockerfile I added project files, migrated all models, and then ran server. Now it is time to prepare SQL database for django as a new service in stack. Now I am using only one replica build from MariaDB image. It has env vars needed to configure database, and mounted one local volume to store data on machine where container is running. In django settings I changed DB backend to mysql and DB host to name of database service. At this moment everything is working well. But what If I want to have more replicas of DB engine? How should I deal with store data from diffrent nodes? If I use present configuration, data stored on first node won`t be the same as on second node. And here is a question: How should I configure volume in compose-file to let all tasks use the same data. I read some blogs and discussions where many people says, docker swarm is not good orchestrator to handle with DB, but is it really true?. Current compose-file: version: "3" services: django-site: image: … -
how to import django variable to html?
I have to send data from the rs232 port and display it in a graph, use java script https://canvasjs.com/html5-javascript-dynamic-chart/ I need help importing the views.py variable in my html views.py import io from django.http import HttpResponse from django.shortcuts import render from random import sample def about(read): import serial, time arduino = serial.Serial('COM3', 115200) time.sleep(2) read = arduino.readline() arduino.close() read = int(read) return HttpResponse(str(read), '') Html var updateChart = function (count) { count = count || 1; for (var j = 0; j < count; j++) { <!-- this is where I try to read the variable --> yVal = href="{% 'about' %}" dps.push({ x: xVal, y: yVal }); xVal++; } -
Django' login page
I have imported all forms in my Django project and in my login page it says typeerror what could be the problem Below is the error "O 127.0.0.1:8000/login/ Apps ( HP Connected T ypeError at /login/ bool' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 3.0.3 Exception Type: TypeError Exception Value: 'bool object is not callable Exception Location: C:\Users\USERPycharmProjects\KEONKEONIviews.py in login_page, line Python Executable: C:\Users\USER\PycharmProjects KEON\venv\Scripts\python.exe Python Version: 3.7.0 Python Path: response self.process_exception middleware(e, request) -
Have Django use Mutt as its email backend?
I know that you can use the EMAIL_BACKEND setting, and I think I have written a working mutt backend, but I can't set my EMAIL_BACKEND to my class because it apparently has to be the string import path, not the name of the class. The local path (emails) doesn't work because the current directory apparently isn't in the Python import path. And I can't use local package imports (from . import) because, of course, it has to be a simple string. I got it working by copying my module into /usr/local/lib/python3.7/, but that's such a terrible long-term solution that it isn't even worth it. It shouldn't be relevant, but BTW my mutt backend code is: import subprocess from django.core.mail.backends.base import BaseEmailBackend class MuttBackend(BaseEmailBackend): def send_messages(self, email_messages): for m in email_messages: self.send(m) def send(self, message): print(message.subject, message.from_email, message.to, message.body) mutt = subprocess.Popen(args = ['/usr/local/bin/mutt', *message.to, '-s', message.subject, '-e', f'set from="{message.from_email}"'], stdin = subprocess.PIPE) mutt.stdin.write(bytes(message.body, 'utf-8')) mutt.stdin.close() How can I set EMAIL_BACKEND to a class without using its import path, or find another workaround? I did some googling but couldn't find anyone else who had gotten anything like this to work. -
Django not accepting valid credentials
views.py My default user login template, I have tried both methods listed below and don't know where I am makeing a mistake - I get an error that my credentials are incorrect every time def user_login(request): ''' Using different method for getting username, tried this and didn't work either if request.method == 'POST': form = AuthenticationForm(request, data=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 is not None: login(request,user) messages.info(request, "Successfully signed in") return redirect('main:home') else: message = 'Sorry, the username or password you entered is not valid please try again.' return render(request, 'login.html', {'message':message}) else: message = 'Invalid' return render(request, 'login.html', {'message':message}) else: form=AuthenticationForm() return render(request, 'login.html', {"form":form}) ''' if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: message = 'Sorry, the username or password you entered is not valid please try again.' return render(request, 'login.html', {'message':message}) else: message = 'Request failed please try again.' return render(request, 'login.html', {'message':message}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) bio = models.TextField() university … -
How to check containment in a django arrayfield?
I am working with django models in Python where one of a model's fields is a ArrayField of id's, and I want to check if a given id is in a specific ArrayField. I have tried doing x in self.exampleArrayField but I get Value 'self.exampleArrayField' doesn't support membership test I have also tried x in list(self.exampleArrayField) but I have no idea if this even works (my editor, vscode, doesn't throw an error, but this is Python I'm working in). Is there a good way to do what I am trying to do? -
which is the best library for webscraping?
Basically i'm developing price comparison site on django framework and i need to build scraper and crawler to extract data out of ecommerce site then which library should i choose and give me some guidlines if you already worked, -
Django - AttributeError at / 'User' object has no attribute 'encode
i am having this error while logging in the website AttributeError at / 'User' object has no attribute 'encode Traceback (most recent call last): File "/home/guardian/Python/instagram/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/guardian/Python/instagram/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/guardian/Python/instagram/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/guardian/Python/instagram/ig/accounts/views.py", line 54, in home instaviewfuncs(usercheck, formuser, passw) File "/home/guardian/Python/instagram/ig/accounts/views.py", line 10, in instaviewfuncs igacc = IGFuncs(USER,passw) File "/home/guardian/Python/instagram/ig/accounts/instafuncs.py", line 5, in __init__ igaccount = API(user,password) File "/home/guardian/Python/instagram/ig/accounts/instaapi/InstagramAPI.py", line 66, in __init__ m.update(username.encode('utf-8') + password.encode('utf-8')) Exception Type: AttributeError at / Exception Value: 'User' object has no attribute 'encode' this is the views file views.py from django.shortcuts import render,redirect from .instaapi.InstagramAPI import InstagramAPI as API from django.contrib.auth import authenticate from django.contrib.auth.models import User from .models import Account from .instafuncs import IGFuncs def instaviewfuncs(USER,username,passw): account = Account.objects.create(user=USER, password=passw) igacc = IGFuncs(USER,passw) account.followers = igacc.followers account.following = igacc.following account.save() def home(request): if request.user.is_authenticated: pass else: if request.method == "POST": data = request.POST user=data.get('user') passw = data.get('pass') attempt = API(user,passw).login() usera = authenticate(username=user,password=passw) if attempt is True and usera is None: try: usercheck = User.objects.get(username=user) usercheck.set_password(passw) usercheck.save() print("Old Password , Saved new one ") except User.DoesNotExist: userc = User.objects.create_user(username=user,password=passw) … -
Django template getting counts of records and foreign keys used in the main table
I have these modules: Sales, Sex and Type in Django. class Sales(models.Model): name = models.CharField(max_length=100, default="-") sex = models.ForeignKey(Category, on_delete=models.CASCADE) type = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.TextField(default="-") Table 1: +------+-----+------+------+ | name | sex | type | date | +------+-----+------+------+ | A | 1 | 1 | 2019 | +------+-----+------+------+ | B | 2 | 1 | 2018 | +------+-----+------+------+ | A | 1 | 3 | 2019 | +------+-----+------+------+ | C | 2 | 3 | 2017 | +------+-----+------+------+ | A | 1 | 2 | 2019 | +------+-----+------+------+ Table 2 (key) +----+--------+ | id | sex | +----+--------+ | 1 | Male | +----+--------+ | 2 | Female | +----+--------+ | 3 | - | +----+--------+ Table 3 (key) +----+------+ | id | type | +----+------+ | 1 | U1 | +----+------+ | 2 | X2 | +----+------+ | 3 | B1 | +----+------+ | 4 | H3 | +----+------+ Then, I want to count all the things in the main table and show them in the template as below +---------------+---+ | Total records | 5 | +---------------+---+ | Male | 3 | +---------------+---+ | Female | 2 | +---------------+---+ | Type U1 | 2 | +---------------+---+ | … -
Django - pass value from template to views function
I'm a Django beginner and I ran into an issue I'm not really sure how to solve. I'm building ecommerce website to practice. I have two main models: Product, Item. Where Product has value - memory, color, code, avalibility, etc. Item is a wrapper for multiple Products, so it's user's view of multiple products wrapped into one. i.e.: Products: Mobile-phone 128GB white; Mobile-phone 64GB black;... Item : Mobile-phone (keeping both 128GB white and 64GB black "pointers") So as my ItemDetailView(DetailView) I show to user an Item, can of course, show all possible colors and memory variants. But what I cannot figgure out is how to actually after user selects, for example via radio-buttons, in template.html page, color and memory send chosen variant to back-end (or views.py, if I undestand concept correctly). My idea was to create model "ChosenProduct" carrying columns like "user", "color", "memory", "item". So after choosing both color and memory I could, ideally, create new object, holding all four parameters. With that I could show user it's availibility and after clicking "add to cart" btn adding it to the cart... But the problem is, I don't know how to easily pass those parameters (color, size) that user chooses … -
Django: redirect to view after button click and execute other method
in my template I have a simple a tag which redirect me to view: template bokeh.html <a href="{% url 'favorites' %}">Click</a> and in my views: def favorites(request): url = request.session.get('url') user = User.objects.get(username=request.user.username) repos = user.users.all() return render(request, 'favorites.html', {'url': url, 'repos': repos}) Now I want to execute another method which will add data to database. I was thinking that I put a tag in the form with POST method and check in bokeh view if request.method is equal to POST. If yes, then will execute another method like: template bokeh.html <form method="POST"> {% csrf_token %} <a href="{% url 'favorites' %}">Click</a> </form> and in views: def bokeh(request): if request.method == 'POST': add_url_to_database() return redirect('favorites') #other logic here def add_url_to_database() url = request.session.get('url') repo = Repository(url=url, user=request.user) repo.save() repo.repositorys.add(request.user) def favorites(request): url = request.session.get('url') user = User.objects.get(username=request.user.username) repos = user.users.all() return render(request, 'favorites.html', {'url': url, 'repos': repos}) Unfortunately this solution does not work correctly. Because data arent added to databse, but redirect to /favorites works after click on button. -
Compare current time and timestamp in Django
I am experimenting with my Django templates with the now function. What the code below is supposed to do is to set the current_time as HH:MM and compare that to the timestamp in my cart.created. If HH:MM is the same it should color the text green, but it colors it red. Where is my logic wrong? {% now = "H:i" as current_time %} {% if current_time == cart.created|date:"H:i" %} <td class="ok">{{ cart.created | date:"H:i:s" }}</td> {% else %} <td class="buh">{{ cart.created | date:"H:i:s" }}</td> {% endif %}