Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Problem with Separating the Two User Names
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I am facing a problem. When I go to http://127.0.0.1:8000/triplist/, I see this page: When I click on Trip Name: Kuala Lumpur and taken to activity.html through this link: http://127.0.0.1:8000/triplist/kuala-lumpur/: "john" and "williams" are two separate user names. They need to be separated by a comma (,). So it will look like this: Co-traveller: john, williams. How can I do it? Here are my codes in models.py: from django.contrib.auth.models import User from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Trip(models.Model): trip_name = models.CharField(max_length=100) date = models.DateField() planner_name = models.CharField(max_length=100) add_coplanner = models.ManyToManyField(User) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.trip_name def save(self, *args, **kwargs): self.slug = slugify(self.trip_name) super().save(*args, **kwargs) class Activity(models.Model): trip = models.ForeignKey(Trip, … -
How can write on two different postgres model?
Question: How can I write to two different Postgres model and read from one of them? Actually, I want to migrate some data from one Postgres database to another Postgres database. the databases schema are the same. So after migration, I want to write both databases and read from one of them. What I tried: I tried to handle it by writing a new database router in Django. from django.conf import settings class MigrationRouter: def db_for_read(self, model, **hints): return settings.READ_ALIAS_DB def db_for_write(self, model, **hints): return settings.WRITE_ALIAS_DB def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): if db in (settings.READ_ALIAS_DB, settings.WRITE_ALIAS_DB): return True return None If I put both database aliases in the db_for_write method that does not work as I expected. -
Update or create a model in django
I have a django table named Inventory Models.py class ClientInventory(models.Model): product_short_code = models.CharField(max_length=500, default=0, null=True) product_quantity = models.IntegerField(default=0, null=True) product_owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='inventory_owner') and I want to update this inventory whenever a form named Delivered Docket is filled and this is my view to do that Views.py @method_decorator([login_required, employee_required], name='dispatch') class DeliveredDocketFormView(CreateView): model = DeliveredDocket fields = "__all__" template_name = 'packsapp/employee/docketDeliveredForm.html' def form_valid (self, form): product = form.save(commit=False) product.save() data = form.cleaned_data ClientInventory.objects.update_or_create(product_short_code=data["product1"], product_quantity =data["product1_recieved_quantity"], product_owner = data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product2"], product_quantity=data["product2_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product3"], product_quantity=data["product3_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product4"], product_quantity=data["product4_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product5"], product_quantity=data["product5_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product6"], product_quantity=data["product6_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product7"], product_quantity=data["product7_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product8"], product_quantity=data["product8_recieved_quantity"], product_owner=data['created_for']) messages.success(self.request, 'The Delivered Docket was created with success!') return redirect('employee:delivered_docket_table') How can I reduce the number of ORM calls as this does not feel right?? This is the form data: {'sender': <Warehouse: Yantra Gurgaon Warehouse>, 'pending_docket_list': <AllotmentDocket: Yantra Gurgaon Warehouse::client::2019-12-04>, 'material_received_date': datetime.date(2019, 12, 4), 'pod _received': 'Yes', 'product1': 'Vipin', 'product1_alloted_quantity': 56, 'product1_recieved_quantity': 56, 'product2': None, 'product2_alloted_quantity': None, 'product2_recieved_quantity': None, 'product3': No ne, 'product3_alloted_quantity': None, 'product3_recieved_quantity': None, 'product4': None, 'product4_alloted_quantity': None, 'product4_recieved_quantity': None, 'product5': None, 'product5_alloted_quantity': None, 'product5_recieved_quantity': None, 'product6': None, 'product6_alloted_quantity': None, 'product6_recieved_quantity': None, 'product7': None, 'product7_alloted_quantity': None, 'product7_recieved_quanti ty': None, 'product8': None, 'product8_alloted_quantity': None, 'product8_recieved_quantity': None, 'created_on': datetime.datetime(2019, 12, … -
For Python2 to Python3 code conversion, Which version of Python & Django best suited?
Currently I am working in big firm where we need to convert python2 old big Django project into python3 version so I have done lots of research related but still not able to find any perfect answer related to which version of Python and Django best suited for conversion. Currently I am using Python : 2.7.16 & Django : 1.9.13 in my old version. Is there any document or reference available which can suggest me best suited version of Python & Django for above old version for python2 to python3 conversion. Thanks. -
How can I fix this error in my tutorial im working on?
I cant seem to figure this tutorial out, im studying django and python and im super stuck. My book says to update the paths like so @code TEMPLATE_DIRS = (getabspath('templates')) MEDIA_ROOT = getabspath('media') MEDIA_URL = '/media/' but when I do i get a syntax error. enter image description here -
Problem with Displaying the Output of models.ManyToManyField(User)
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I am facing a problem. I have added two activities for Kuala Lumpur through Django admin. They are "Going to Botanical Garden" and "Going to Aquaria." When I go to http://127.0.0.1:8000/triplist/, I see this page: As you can see, in the Co-planner field, the name of the user is being displayed as <QuerySet [<User: williams>]>.But it is supposed to be displayed as Co-planner: williams. Same problem occurs when I click on Trip Name: Kuala Lumpur and taken to http://127.0.0.1:8000/triplist/kuala-lumpur/: Here are my codes in models.py: from django.contrib.auth.models import User from django.db import models # Create your models here. from django.template.defaultfilters import slugify class Trip(models.Model): trip_name = models.CharField(max_length=100) date = models.DateField() planner_name = models.CharField(max_length=100) add_coplanner = models.ManyToManyField(User) slug = models.SlugField(max_length=150, default='null') … -
I m facing this prblm when I m running my django application on local host I m using atom ide
after starting my server when I open browser then this shows -
How to check whether a object is expired or not in django?
I'm trying to check whether a object is expired or not by using:- if (Token.objects.get(content=token).DatePosted-timezone.now())<'1 days': return False else: return True It is producing following error:- '<' not supported between instances of 'datetime.timedelta' and 'str' my question is hpw can i convert 0 days into a datetime.timedelta object? -
Django on docker container error when trying to connect to local mysql database
Please help me, I have django application that run on docker container with docker-compose, but i have error when trying to connect to mysql database on my local machine. The error message is like this : Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ my docker-compose.yml file is like this : version: '3' services: web: container_name: web build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" and my Dockerfile is like this : FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev -y RUN pip install pip -U RUN pip install -r requirements.txt -
ModuleNotFound error in django. PS - virtualenv misbehaving
Something had been wrong with my virtualenv. I never shut pc down nor the text editor with terminal(vs code). I just deactivated vituralenv last night and activated it today to find it's name has changed. I wasn't able to runserver so I figured out something was wrong with virutalenv because on pip freeze it shows all the packages. I installed virtualenv again and made a virtualenv with same name in same directory which overwrote previous virtualenv and now it's fine. Although while executing python manage.py runserver, it shows. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen … -
Django changes dropdown menu to Input Text Fields by itself (CODE HAS DROPDOWN!)
THIS IS THE MODEL.PY file! - class userchoice(models.Model): choice = [] choice2 = list(userdata.objects.all().values_list('key')) for x in choice2: for t in x: choice.append((t,t.capitalize())) Job_ID = models.CharField(primary_key = True, max_length=200, choices=choice, default='key') Group_ID= models.CharField(max_length=200, choices=choice, default='key') Customer_name = models.CharField(max_length=200, choices=choice, default='key') Planned_Duration = models.CharField(max_length=200, choices=choice, default='key') Worker_name = models.CharField(max_length=200, choices=choice, default='key') Job_note = models.CharField(max_length=200, choices=choice, default='key') Customer_tp_name = models.CharField(max_length=200, choices=choice, default='key') AND THIS IS THE MIGRATIONS FILE (DOES NOT MIGRATE CHOICES!!)- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('csvfileapp', '0008_userdata'), ] operations = [ migrations.CreateModel( name='userchoice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Job_ID', models.CharField(default='key', max_length=200)), ('Group_ID', models.CharField(default='key', max_length=200)), ('Customer_name', models.CharField(default='key', max_length=200)), ('Planned_Duration', models.CharField(default='key', max_length=200)), ('Worker_name', models.CharField(default='key', max_length=200)), ('Job_note', models.CharField(default='key', max_length=200)), ('Customer_tp_name', models.CharField(default='key', max_length=200)), ], ), ] PLEASE HELP!! -
Django Treebread admin AttributeError - 'Page' object has no attribute 'page_ptr_id'
Please help. Stuck and confused. Trying to use Django Treebread admin to see the tree structure of Journal objects, which inherits from class Page in wagtail. Page inherits from MP_Node in Treebread. models.py from wagtail.core.models import Page class Journal(Page): body = RichTextField(blank=True) admin.py from django.contrib import admin from treebeard.admin import TreeAdmin from treebeard.forms import movenodeform_factory from .models import Journal class MyAdmin(TreeAdmin): form = movenodeform_factory(Journal) admin.site.register(Journal, MyAdmin) In Django admin, click Jounal and get error msg as below: AttributeError at /admin/journal/journal/ 'Page' object has no attribute 'page_ptr_id' Request Method: GET Request URL: http://127.0.0.1:8000/admin/journal/journal/ Django Version: 2.2.1 Exception Type: AttributeError Exception Value: 'Page' object has no attribute 'page_ptr_id' Exception Location: C:\Users\Freedom\Anaconda3\envs\myvenv\lib\site-packages\django\contrib\admin\views\main.py in url_for_result, line 473 Python Executable: C:\Users\Freedom\Anaconda3\envs\myvenv\python.exe Python Version: 3.7.3 Python Path: ['D:\\Python\\Django\\m4ever', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\python37.zip', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\DLLs', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\lib', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\lib\\site-packages'] page_ptr_id is actually the Django auto-generated field name for the one-to-one relation from the specific Journal class to the base Page model. Tried define it explicitly in Journal as: page_ptr_id = models.OneToOneField(Page, on_delete=models.CASCADE, parent_link=True) But still get similar error msg, displaying as 'Page' object has no attribute 'page_ptr_id_id' -
Django: How to prevent form resubmission when form validation unsuccessful?
I have looked into this problem with possible duplication but it seems like mine's a different problem. So I have forms which use sessions to temporarily store data. I have also included {{ form.errors }} in my templates to display the errors upon validation. The problem is, when I try to reload the page () when form is invalid/unsuccessful and the errors were displayed, instead of just refreshing the page and clearing the fields as well as the displayed errors, a confirm form resubmission dialog appears and the errors in my form remained. How should I prevent this dialog from appearing? -
Django customize Admin login page
Would it be possible to just reuse the login page? I just want to add sign up button in the login page. But for what I have searched, it needed to customize all in order to override it. <div class="submit-row"> <input type="submit" value="Log in"> <input type="button" value="Sign up" onclick="location.href='/admin/signup'"> </div> Please help. -
Create login session in django
so i try to make a login with session , so user must logged in first before redirect to another page , so i think im doing right , but i dont know how to check if i save the session or not , here's the code views.py def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guess = User.objects.get(username=username) identity = guess.id table2 = UserProfileInfo.objects.get(user_id=identity) role = table2.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': request.session['username'] = username login(request, user) return render(request,'index.html',{"username":username}) elif role == 'Admin': login(request, user) return redirect('/manageuser/') elif role == 'Manager': login(request, user) return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) def index_view(request): if request.session.has_key('username'): username = request.session['username'] print(username) return render(request, 'index.html',{"username":username}) settings.py INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SESSION_ENGINE = "django.contrib.sessions.backends.cache" When i try to print the username , it wont show in command prompt , i thought i already save the request.session['username'] in … -
NoReverseMatch at /users/login/
'learning.logs' is not a registered namespace. Request Method: GET Request URL: http://localhost:8000/users/login/ Django Version: 2.2.7 Exception Type: NoReverseMatch Exception Value: 'learning.logs' is not a registered namespace settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # my_apps 'learning_logs', 'users', ] learning_logs\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/',include('users.urls', namespace='users')), path('',include('learning_logs.urls', namespace='learning_logs')), ] users\urls.py from django.urls import re_path, path, include from django.contrib.auth.views import LoginView from . import views app_name = 'users' urlpatterns = [ # log in page path('login/', LoginView.as_view(template_name='users/login.html'),name='login'), ] learning_logs\urls.py from django.urls import re_path from . import views app_name = 'learning_logs' urlpatterns = [ # homepage re_path('^$', views.index, name='index'), # show all topics re_path('^topics/$', views.topics, name='topics'), # show dedicated topic re_path('^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), # added new topic re_path('^new_topic/$', views.new_topic, name='new_topic'), # added new entry re_path('^new_entry/(?P<topic_id>\d+)/$', views.new_entry, name='new_entry'), # edit entry re_path('^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry, name='edit_entry'), ] login.html {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">log in</button> <input type="hidden" name="next" value="{% url 'learning.logs:index' %}" /> </form> {% endblock content %} base.html <p> <a … -
Django, static files, and horizontal scalabilty
I am making a website in Django, and I am trying my best to make sure it is horizontally scalable. Due to the application being horizontally scalable, I am unable to save Images that users upload locally, in the media folder. I was wondering what are some ways I could save the images that the users upload, in such a way that would allow my application to be horizontal scalable? I do have a MariaDB Galera Cluster that I use to store other data, but it seems like saving images in a shared database might not be the best idea due to performance reasons (Storing Images in DB - Yea or Nay?). If I attempt to use the media folder, are there any solutions that could sync storage (folder) between different instances of the application? In general, what are some good practices for serving(download/upload) static content like images for horizontally scalable websites, and does Django provide anything to assist with this matter out of the box? -
Duplicate queries with inline_formset
In my web application I managed to create an inline_formset that works well. Problem now is when I have let's say 200 rows, each field that has foreign key is called 200 times to generate the drop down menu. I tried to use prefetch but queries are still duplicated, can you please help how to make query only once to get list of dropdown menu ? in forms.py class IssueForm(forms.ModelForm): class Meta: model=Issue fields=('__all__') IssueFormset=inlineformset_factory(IssuesList, Issue, form=IssueForm,extra=0) in views.py class IssuesListUpdateView(UpdateView): model=IssuesList fields='__all__' # ovewrite get_context_data to add formset as an additionnal parameter def get_context_data(self, **kwargs): context = super(IssuesListUpdateView, self).get_context_data(**kwargs) if self.request.POST: # if Save All issues button submitted if 'save_all' in self.request.POST.keys(): formset = IssueFormset(self.request.POST, instance=self.object) # sending formset to the template context['issues_formset'] = formset # save in the DB (saves only what has changed) #https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#saving-objects-in-the-formset # if formset.is_valid(): formset.save() # re-update context with new formset, this is need to refresh table in case of deleting an object # without this, issue is deleted but still visible in the table context['issues_formset'] = IssueFormset(instance=self.object) else: # sending formset to the template issues_formset=IssueFormset(instance=self.object) for form in issues_formset: form.fields["si"].queryset=Si.objects.prefetch_related('si_issues').\ all().filter(product__name='test') context['issues_formset'] = issues_formset return context In template: <form method="post">{% csrf_token %} <!-- … -
How could I make the pop up box stay on the screen so I can press the Ok button before it exits
What I am trying to do is after user click the update button the pop up box shows up on the screen then i can click the ok button to confrim or exit it. But on my code right now it just auto matically close the box after it shows up. Here is my JS if ($(document).find("#show_pop").val() == 1){ swal.fire({ title: "Updated Successfully!", text: "", type: "success", confirmButtonText: "OK" }).then(function(i){ }) } This is from my templates. <input id="show_pop" name="show_pop" value="{{ success }}" type="hidden" readonly> This is from my views.py just on the bottom part.... employee.save() context = { "success": 1, } print(context) return render(request, "index.html", context) -
How to create a membership record for a new user with django_rest_auth and django rest framework
I'm trying to create an invite/acceptance workflow with Django Rest Framework and Django Rest Auth. I have my initial account creation working just fine. Then a user creates a team, no problem. That owner now sends invites. Cool. Email's go out and the invitee get's the email with an ID for the team that they are being invited to. Here's where I'm struggling. There is a membership model that connects a team and a member. When a user has been invited registers, I want to create that membership record. So, where do I put that membership creation method? Is it in the serializer or the view? Django Rest Auth RegistrationView calls the save method of the RegistrationSerializer here. The serializer returns the created user to the view for the response. I know I need to create the membership record AFTER the user is created otherwise there isn't a user to add to membership. But I can't figure out where to do this? I was thinking of creating a create_membership method that is fired after the create method is run, but that isn't working. Something like this: def create_membership(self): team = "6edb0a55-199a-4aae-aa40-e7313186136b" return Membership.objects.create(team__id=team, member=self.user) Then calling it like this (this … -
Logo image in the navbar displays only on home page
The image of my logo on the navbar displays only on the home page, what should I do to fix it? That's root for the image on the navbar: <a class="navbar-brand waves-effect" href="/"> <img src="media\logoBrand.png"> </a> urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('core.urls', namespace='core')) ] if settings.DEBUG: import debug_toolbar urlpatterns += [path('__debug__/', include(debug_toolbar.urls))] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And urls.py core: from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import ( ItemDetailView, CheckoutView, HomeView, OrderSummaryView, add_to_cart, remove_from_cart, remove_single_item_from_cart, PaymentView, AddCouponView, RequestRefundView ) app_name = 'core' urlpatterns = [ path('', HomeView.as_view(), name='home'), path('checkout/', CheckoutView.as_view(), name='checkout'), path('order-summary/', OrderSummaryView.as_view(), name='order-summary'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), path('add-to-cart/<slug>/', add_to_cart, name='add-to-cart'), path('add-coupon/', AddCouponView.as_view(), name='add-coupon'), path('remove-from-cart/<slug>/', remove_from_cart, name='remove-from-cart'), path('remove-item-from-cart/<slug>/', remove_single_item_from_cart, name='remove-single-item-from-cart'), path('payment/<payment_option>/', PaymentView.as_view(), name='payment'), path('request-refund/', RequestRefundView.as_view(), name='request-refund') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So when i got to homepage the image is displaying, but when I go to let say /checkout/ i get an error in the console: Not Found: /checkout/media/logoBrand.png I am not sure why does it go to this directory Settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' … -
django template timeuntil timezone
I am rendering some meetings with django templates. {% for meeting in m %} <td>{{ meeting.start|date:"j F Y, g:i A" }}</td> <td>{{ meeting.start|timeuntil }}</td> {% endfor %} and view code now = datetime.datetime.now() + datetime.timedelta(hours=-5) m = Meeting.objects.filter( start__gte=now, status=Meeting.PENDING ).order_by("-start") context = { "m": m, } return render(request, "meetings/home.html", context) produces a table like Time Requested Time Pending (hrs) 7 December 2019, 12:00 AM 2 days 5 December 2019, 12:00 AM 12 minutes 4 December 2019, 11:00 PM 0 minutes my browser is in EST time and the api is UTC. The start time is rendered in local time correctly. But the timeuntil countdown is not in the localtime. Is there a good way to achieve the desired output? So far the best thing I can think of is to compute another datetime column with the client's timezone difference applied. Then the template could simply render {{ meeting.start_local|timeuntil }}. -
Programatically create Redirects in Wagtail
Is there a way to programatically create functioning Redirect objects in Wagtail? I am trying the obvious (naively creating the object): Redirect.objects.create(old_path='/test', redirect_link='https://stackoverflow.com') This creates a Redirect that is visible in the Wagtail admin panel, however navigating to /test simply 404s without redirecting. However, if I then save the Redirect from the admin panel, it suddenly works. Is there some special post-save logic I need to run in order to activate the redirect? I looked through the source and could not find anything. -
Pagination menu changing length
I'm paginating some data from a django model. My issue is that I don't know how to control the menu for the pages. I'd like it to show maybe 10 page links at a time and gradually move across. This works to a degree, as it moves forward it will show more, so if on page 1 it will show 1-10, if on page 2 it will show up to 11. The problem is I can't control this in a static fashion. I would like to show 1-10 and then once it gets to 6, display 2-11 and so on. it works from 6 onwards, the problem is at the beginning it will show 1-5, then 1-6, then 1-7 until it gets to 6 when it will look correct. I hope this makes sense.... Here's my html: {% if contacts.has_other_pages %} <ul class="pagination"> {% if contacts.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ contacts.previous_page_number }}">Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#">&laquo;</a> </li> {% endif %} {% if contacts.number|add:'-4' > 1 %} <li class="page-item"> <a href="?page={{ page_obj.number|add:'-5' }}">&hellip;</a> </li> {% endif %} {% for i in contacts.paginator.page_range %} {% if contacts.number == i %} <li class="page-item active"> <a … -
How to have CSS border span the length of the page but have elements remain inside container?
I am trying to create a navigation bar. I have used bootstrap for the body of my site and would like the navigation bar to span the same width. However, I want the border to span the full width; so that the elements 'Home, Learn, Progress, etc' appear to be right above the things in the actual page but not so that the border is cut off. TIA <div class="navbar container"> <div class="navbar-left"> {% url 'quizapp-home' as url %} <a href='{{ url }}' {% if request.path|slice:":6" == url %} id="current" {% endif %}><i class="fas fa-home"></i> Home</a> {% url 'quizapp-learn' as url %} <a href='{{ url }}' {% if request.path|slice:":7" == url %} id="current" {% endif %}><i class="fas fa-pencil-ruler"></i> Learn</a> {% url 'progress' as url %} <a href='{{ url }}' {% if request.path|slice:":10" == url %} id="current" {% endif %}><i class="fas fa-chart-line"></i> Progress</a> </div> <div class='navbar-right'> {% if user.is_authenticated %} {% url 'profile' as url %} <a href='{{ url }}' {% if request.path|slice:":9" == url %} id="current" {% endif %}> Profile</a> {% url 'logout' as url %} <a href='{{ url }}' {% if request.path|slice:":8" == url %} id="current" {% endif %}>Logout</a> {% else %} {% url 'login' as url %} <a …