Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create, update and delete forms in the same template?
I intend to update, create and delete on the same template, as shown below. I currently have the following on my models class Customer(models.Model): TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) STATUS = ( ('Active', 'Active'), ('On hold', 'On hold'), ) GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) ROLE = ( ('Customer', 'Customer'), ('Admin', 'Admin'), ) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) country = CountryField() birth_year = models.CharField(max_length=4, null=True) gender = models.CharField(max_length=200, null=True, choices=GENDER) email = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200, null=True) status = models.CharField(max_length=200, null=True,choices=STATUS) date_created = models.DateTimeField(auto_now=True, null=True) profile_pic = models.ImageField(null=True, blank=True, default='images/default.png') role = models.CharField(max_length=200, null=True, choices=ROLE) and my forms is as follows class CustomerProfileForm(forms.ModelForm): class Meta: model = Customer fields = [ 'title','first_name','middle_name','last_name','phone','country','birth_year','gender'] Currently I have my views showing to update each customer, as shown below. @login_required(login_url='login') def CustomerProfile(request, pk): customer = Customer.objects.get(id=pk) formie = CustomerProfileForm(instance=customer) if request.method == 'POST': formie = CustomerProfileForm(request.POST, instance=customer) if formie.is_valid(): formie.save() return redirect('/') context = {'formie':formie} return render(request, 'accounts/customer_profile.html', context) In another template i have a list of customers, with each having an … -
How to use images on database(django admin) in lightbox or modal
i am trying to use images on my django database as a lightbox image but not getting it even in modal gallery too. it only displays the first image when clicked and blanked when next button is pressed. when the user upload an image to the database, the image is displayed on the webpage as modalpopup or lightbox when clicked, i achieved this by using images on my local drive. here is what i have tried {% extends 'base.html' %} {% load static %} {% block title %} G.F. Cakes {% endblock %} {% block content %} {% include 'nav.html' %} {% for post in post.all %} <link rel="stylesheet" href="{% static 'css/cakes.css' %}"> <div class="main"> <div class="row"> <div class="column"> <div class="content"> <img src="{{post.cake_image.url}}" style="width:100%" onclick="openModal();currentSlide(1)" class="hover-shadow cursor"> <div class="imgcaption"> <h3>{{post.cake_name}}</h3> </div> </div> </div> </div> <div id="myModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content"> <div class="mySlides"> <div class="numbertext">1 / 4</div> <img src="{{post.cake_image.url}}" class="modal-img" style="width:100%"> <!-- <br /><p>{{post.cake_name}}</p> --> </div> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <div class="caption-container"> <p id="caption"></p> </div> </div> </div> </div> {% endfor %} {% include 'foot.html' %} {% endblock %} javascript code function openModal() { document.getElementById('myModal').style.display = "block"; } function closeModal() { document.getElementById('myModal').style.display = "none"; } var slideIndex … -
Django can't map url to view using include method
I have the following urls.py in my project dir, Main project urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.render_calculator, name='render_calculator'), path('calculator/', views.render_calculator, name='render_calculator'), path('disclaimer/', views.render_disclaimer, name='render_disclaimer'), path('cookiepolicy/', views.render_cookiepolicy, name='render_cookiepolicy'), path('privacypolicy/', views.render_privacypolicy, name='render_privacypolicy'), path('dashboard/', views.render_dashboard, name='render_dashboard'), path('about/', views.render_about, name='render_about'), path('admin/', admin.site.urls), path(r'^', include('accounts.urls')) ] Now I created a new app accounts (I added it to my apps in settings.py) where I would like to store the urls of that app in its own dir like so: Accounts app urls.py from . import views from django.urls import path urlpatterns = [ path('register/', views.render_register, name='render_register'), ] Accounts app views.py: from django.shortcuts import render def render_register(request, template="register.html"): return render(request, template) However, this configuration throws me this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/register Using the URLconf defined in CFD.urls, Django tried these URL patterns, in this order: [name='render_calculator'] calculator/ [name='render_calculator'] disclaimer/ [name='render_disclaimer'] cookiepolicy/ [name='render_cookiepolicy'] privacypolicy/ [name='render_privacypolicy'] dashboard/ [name='render_dashboard'] about/ [name='render_about'] admin/ ^ The current path, register, didn't match any of these. Where is the missing piece? -
What is the easiest way to require the user to fill in default fields of the User model like first name and last name in Django in UserCreationForm?
I am using Django built-in authentication views and form to create a registration/login system, and I'm using the UserCreationForm to register a user but only the username is required. I only want to make other User fields required as well. What is the simplest way to do that without creating a new user model? -
get() takes from 2 to 3 positional arguments but 4 were given
Why am i getting this error? I am supposed to declare the author and article details at the same time but the django does not let me do that . Anybody knows how to solve this code problem? class ArticleCreateView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def create(self, request): serializer_context = { 'request': request } serializer_data = request.data.get('article','author',{}) serializer = self.serializer_class( data=serializer_data, context=serializer_context ) serializer.is_valid(raise_exception=True) serializer.save() response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'User registered successfully!', } status_code = status.HTTP_200_OK return Response(serializer.data, status=status.HTTP_201_CREATED) Here is the problem serializer_data = request.data.get('article','author',{}) TypeError: get() takes from 2 to 3 positional arguments but 4 were given [10/May/2020 18:52:28] "POST /api/createpost/ HTTP/1.1" 500 98933 Other positional arguments are 2 arguments that are called "caption,details". -
How to modify Page model view in wagtail admin?
Background: I would like to enhance a page instance during an admin page view with some admin request related information (some pre-population in general). Basically I would need some function like "get_queryset", but not for list view, just for edit view. In my older question related to a similar problem: Wagtail - how to preopulate fields in admin form? I was provided with instructions to use something called CreatePageView However, I cannot import it. Furthermore, I cannot even found any mention about that in google if I search: Wagtail +CreatePageView The closest thing I found is https://docs.wagtail.io/en/v2.1.1/reference/contrib/modeladmin/create_edit_delete_views.html but the page also states: NOTE: modeladmin only provides ‘create’, ‘edit’ and ‘delete’ functionality for non page type models (i.e. models that do not extend wagtailcore.models.Page). If your model is a ‘page type’ model, customising any of the following will not have any effect I am quite confused. What should I do if I need to customize the admin view for Page model extension? I studied the wagtail source codes for Model.admin and Page and I have not found any way. Any ideas? The related code simplified: wagtail hooks: class ItemAdmin(ModelAdmin): pass # some function override here maybe? models: class ItemPage(Page): pass # … -
Unable to connect to gmail smtp linode django apache2 setup
Hello im having difficulties connecting to google smtp server. The context is that whenever a user fills in a form , my program will automatically email me the feedback to my gmail account. Everything is working except for the fact that the program is stuck within the send_mail function. I have tried doing this : telnet smtp.gmail.com 25 Trying 2404:6800:4003:c03::6c... Which will eventually result in a time out. Here is some of my code: settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'xxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxx' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = DEFAULT_FROM_EMAIL As per out of the box from wagtail(django cms package) I thought it might have to do with my UFW blocking it , however i have tried disabling the UFW and restarting apache2 . This unfortunately does not help. ufw status Status: active To Action From -- ------ ---- 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 443/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) I am really lost! Please help . Thanks -
Django can't find Arabic Slug in real host
I have a Django project. This project have Arabic slugs. When i opened my project in localhost , all URLs and slugs worked. But when i uploaded my project in real host, when i opened Arabic slugs i got 404 error. -
ImageField url attribute
Django 3.0.6 models.py class Image(models.Model): def image_tag(self): return mark_safe('<img src="{}" width="150" height="150" alt={} />'.format(self.image_300_webp_1.url, self.alt)) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' Test: >>> from image.models import Image >>> i = Image.objects.first() >>> i.image_tag() '<img src="/media/home/michael/PycharmProjects/pcask/pcask/media/image/1/1_300_1x.webp" width="150" height="150" alt=asdf />' The problem: Real path is /media/image/1/1_300_1x.webp. Could you tell me why it is: media + absolute path to the image? And how to get the correct path? -
Django-admin error: no such table auth_user
I am trying to login to my sites admin panel. However it always throws no such table: auth_user. There are neither migrations to apply nor changes detected to migrate. I have no forms/models yet in my application, I just installed Django-admin. I also tried it by reinstalling django-admin, without success. Any solution to this? Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 100, in handle default_username = get_default_username() File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\management\__init__.py", line 140, in get_default_username auth_app.User._default_manager.get(username=default_username) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 411, in get num = len(clone) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 258, in __len__ self._fetch_all() File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1151, in execute_sql cursor.execute(sql, params) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, … -
Postgres+django on kubernetes: django.db.utils.OperationalError: could not connect to server: Connection timed out
My Django app can't connect to the Postgres server on Kubernetes. All other pods are able to connect to this Postgres server and creds are valid as well, any idea why not this Django app django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "postgres-postgresql" (10.245.56.118) and accepting TCP/IP connections on port 5342? -
No function matches the given name and argument types. You might need to add explicit type casts. Django Postgresql
I am trying to get the average of a field in my model but I keep getting this error: Exception Type: ProgrammingError Exception Value: function avg(character varying) does not exist LINE 1: SELECT AVG("home_course"."course_difficulty") AS "course_dif... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. This is my model field I am getting an average on: class Difficulty(models.TextChoices): EASY = '1', 'Easy' MEDIUM = '2', 'Medium' HARD = '3', 'Hard' FAILED = '4', 'Failed' course_difficulty = models.CharField( max_length=2, choices=Difficulty.choices, default=Difficulty.MEDIUM ) And I am using this query: avg = Course.objects.filter(course_code=self.course_code,course_university=self.course_university).aggregate(Avg('course_difficulty')) (course_code and course_university are both CharFields) Now after searching I came to realize that it's possibly because course_difficuly is a CharField, how can I convert it to integer without losing my text choices? Can I simply change it to IntegerField? -
Django allauth error for missing argument?
Erros appear when I tried to submit register form, the problem is that I don't know how to debug code, which is not mine, like packages (allauth in this case): AttributeError at /users/signup/ 'bool' object has no attribute 'get' Request Method: POST Request URL: http://localhost:8000/users/signup/ Django Version: 2.2.4 Exception Type: AttributeError Exception Value: 'bool' object has no attribute 'get' signup.html: {% extends 'index.html' %} {% block 'head-title' %} <title>Вход</title> {% endblock %} {% block 'body' %} {% load i18n %} {% block content %} <div id="dialog_signin_part" class="zoom-anim-dialog"> <div class="small_dialog_header"> <h3>Регистрирай се</h3> </div> <p>{% blocktrans %}Вече имаш акаунт? <a href="{{ login_url }}">Логни се тук</a>.{% endblocktrans %}</p> <div class="utf_signin_form style_one"> <div class="tab_container alt"> <div class="tab_content" id="tab1" style=""> <p>test</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> </div> </div> </div> </div> {% endblock %} {% endblock %} Any advice how to debug it is welcome. I'm open to provide more information, files etc. -
How to display signup errors so they are not in a list django
Hello i am doing a school project in django. I want to display signup errors. I have tried with {{form.errors}} but it shows a list with where it went wrong and what went wrong. How can i get only the thing that went wrong? I have tried with a foor loop on {{form.erros}} but it only shows where it went wrong and not what went wrong. How do i get the sub list ? def register(request): #form za registracijo form = CreateUserForm() #če je gumb pritisjen oz post if request.method == 'POST': #vnesemo podatke v form form = CreateUserForm(request.POST) #če so podatki pravilni if form.is_valid(): #form shranimo form.save() #dobimo ime uporabnika user = form.cleaned_data.get('username') #izpišemo da je uspešno narejen račun messages.success(request, 'Account was created for %s' %(user)) #vas vrnemo na prijavo return redirect('login') #context za vnos forma v template context = {'form': form} #naložimo stran ob zahtevi return render(request, 'accounts/register.html', context) -
How to get class name from custom_exception_handler in django
I m implementing custom_exception_handler in django here is the code.. from rest_framework.views import exception_handler def custom_exception_handler(exc, context): response = exception_handler(exc, context) ... ... return response_set I get a function name by implementing this context['view'].__class__.__name__ Similarly i want a class name, from which class this exception are occur/trigger. I tried various way but didn't work, I didn't get class name! If you know, Then please write your solution in comment section. -
Application error: hosting django blog app
error detail o I'm seeing Application error enter image description here -
Why javascript doesn't detect the elements that are added after a django for loop?
So it's all in the title, I'll put my code right here: {% extends "list/base.html" %} {% block content %} <main class="site-main" style="background-color: black;"> <!--Banner Area--> <section class="site-banner pb-5" style="background-color: black; overflow: hidden; position: relative; color: white;"> <div class="container"> <h3>Liste</h3> <p class="total" style="color: black; display: none;">{{ total }}</p> {% for movie in movies %} <div class="c"> <img src="https://via.placeholder.com/1000x1481" alt="Avatar" class="image"> <div class="overlay"> <a data-modal-target="#cont" class="icon" title="User Profile" style="display: block;"> <i class="fa fa-play" aria-hidden="true"></i> </a> </div> </div> <div class="cont{{movie.id}}" id="cont{{movie.id}}"> <div class="row"> <div class="col-lg-4"> <img src="https://via.placeholder.com/1000x1481" alt="Avatar" class="image"> </div> <div class="col-lg-8"> <div class="modal-header"> <div class="title">{{ movie.title }}</div> <a data-close-button class="close-button">&times;</a> </div> <span>Sorti en {{ movie.date_released|date:"Y" }}</span> <span>avec {{ movie.author}}</span> <span class="id">{{movie.id}}</span> <p>{{movie.synopsis}}</p> </div> </div> </div> {% endfor %} <div id="ov"></div> </div> </section> </main> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> const openModalButtons = document.querySelectorAll('[data-modal-target]'); const closeModalButtons = document.querySelectorAll('[data-close-button]'); const overlay = document.getElementById('ov'); var d = document.querySelector('.total').innerText; function popup() { for (i=1, c = d; i<c; i++) { const cont = addEventListener(document.querySelector(".cont"+i)); console.log(cont); cont.style.background = "red"; cont.style.color = "white"; cont.style.width = "75%"; cont.style.transform = "translate(-50%, -50%) scale(0)"; cont.style.position = "fixed"; cont.style.top = "50%"; cont.style.left = "50%"; cont.style.padding = "20px"; cont.style.zindex = "10"; cont.style.overflow = "hidden"; cont.style.maxWidth = "80%"; cont.style.borderRadius = "30px"; const contAct = document.querySelectorAll(".cont"+i+".active"); contAct.style.transform … -
Vectorizing Function using Pandas Dataframe result in KeyError
I am still new to Pandas dataframe and I'm trying to vectorize the following loop functions because while it gets the job done, iterating a 30,000 rows dataframe using iterrows() is not viable at all header = data_reader.columns.values.tolist()[1:] series_list = [] # New row in Timeseries table for datetime_index, row in data_reader.iterrows(): for i in range(0, len(row)-1): metrics = Metrics.objects.get(name=header[i]) print(metrics) try: val = float(row[i]) series_list.append(Timeseries(timestamp=datetime_index, parameter=metrics, float_val=val, status=None, device_id=metadata)) except ValueError: series_list.append(Timeseries(timestamp=datetime_index, parameter=metrics, float_val=None, status=row[i], device_id=metadata)) Timeseries.objects.bulk_create(series_list) Thus I've looked up on Pandas/NumPy Array Vectorization and how it can shorten the time complexity of a function. I am trying to convert the above function into the vectorized version and this is what I've got so far header = data_reader.columns.values.tolist()[1:] series_list = [] data_reader = data_reader.reset_index() for i in range(1, len(header)): series_list.append(insertion(header, series_list, data_reader['datetime'].values, data_reader[i].values, metadata)) Timeseries.objects.bulk_create(series_list) def insertion(header, series_list, datetime, df_col, metadata): metrics = Metrics.objects.get(name=header[i]) print(metrics) try: val = df_col series_list.append(Timeseries(timestamp=datetime, Parameter=metrics, value=val, status=None, device_id=metadata)) except ValueError: series_list.append(Timeseries(timestamp=datetime_index, Parameter=metrics, value=None, status=val, device_id=metadata)) return series_list However when I try to run the code I always get KeyError: 1 error message. Any idea on how I can vectorize my function and the cause of the error message? -
Django custom context processor passes incorrect data to home template only
I'm working on a project which I require to show category menu on every page. So I decided to use a context processor for that as shown below: import logging logger = logging.getLogger(__name__) def product_categories(request): from shopadmin.models import ProductCategory categories = ProductCategory.objects.all() logger.info(f'CATEGORIES ARE: {categories}') return {'product_categories': categories} And I show the categories with following code in base.html {% if product_categories %} <div class="categories_menu_toggle"> <ul> {% for category in product_categories %} {% if category.is_root_category %} <li class="menu_item_children categorie_list"><a href="#"><span><i class="zmdi zmdi-desktop-mac"></i></span>{{ category.title }}<i class="fa fa-angle-right"></i></a> {% if category.sub_categories.all %} <ul class="categories_mega_menu"> {% for sub_category in category.sub_categories.all %} <li class="menu_item_children"><a href="#">{{ sub_category.title }}</a> {% if sub_category.sub_categories %} <ul class="categorie_sub_menu"> {% for child_category in sub_category.sub_categories.all %} <li><a href="">{{ child_category.title }}</a></li> {% endfor %} </ul> {% endif %} </li> {% endfor %} </ul> {% endif %} </li> {% endif %} {% endfor %} <li id="cat_toggle" class="has-sub"><a href="#"> {% trans 'More Categories' %}</a> <ul class="categorie_sub"> <li><a href="#"><span><i class="zmdi zmdi-gamepad"></i></span> {% trans 'Hide Categories' %}</a></li> </ul> </li> </ul> </div> {% endif %} home.html, products.html, product.html, invoice.html and almost all other templates extend base.html template. But something happens here that I can not understand. When I open the homepage (index), the result of the logger.info(...) from … -
Django Admin Models. Foreign Key Pop Up Window Full Screen
There is a foreign key in one of my models. In the add model page, when I click on the + button next to foreign key a pop up window appears. I want this window to be Full screen. -
Django Views has an issue not allowing all Context Variables to appear in template
I have made a Slider Model which contains 3 images and Texts related to it to slide in a Carousel My issue is that I want these images to be shown as per the order assigned as per the model but only one appears. If I remove the {% if sliders %} {% for slider in sliders %} the latest image only appears because in the views it is filtered by .latest('timestamp') I have also tried to replace .latest('timestamp') in the views with .all() it still didn't work This is the model: class Slider(models.Model): title = models.CharField(max_length=60) image = models.ImageField(blank=False, upload_to='Marketing') order = models.IntegerField(default=0) header_text = models.CharField(max_length=120, null=True, blank=True) middle_text = models.CharField(max_length=120, null=True, blank=True) footer_text = models.CharField(max_length=120, null=True, blank=True) button_text = models.CharField(max_length=120, null=True, blank=True) active = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) class Meta: ordering = ['order'] def __str__(self): return self.title def get_image_url(self): return "%s/%s" % (settings.MEDIA_URL, self.image) This is the view: class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['marketing_message'] = MarketingMessage.objects.filter( active=True).latest('timestamp') except MarketingMessage.DoesNotExist: context['marketing_message'] = None try: context['slider'] = Slider.objects.filter( active=True).latest('timestamp') except Slider.DoesNotExist: context['slider'] = None return context This is the template: {% if sliders %} {% … -
Cannot connect to localhost:8000/admin page, Django
I'm a Django newbie. I'd created a superuser for my site, but when I start the server and try to connect to localhost:8000/admin page, the site refuses to connect and I get a ERR_CONNECTION_REFUSED (site cannot be reached) error. -
Flask-Admin page not found on production
I have built a flask app and deployed it to production using Vercel(formerly zeit now). Everything works except the flask admin. It returns url not found when accessing example.com/admin . Some suggested this move admin.Admin() initialization block away from the main function . But I don't know what that means can somebody help me ? Everything works perfect on local machine -
Reverse Foreign Key in filter of QuerySet in Django
Let's say I have two models: class Human(models.Model): name= models.CharField(#... class Jacket(models.Model): owner = models.ForeignKey(Human, #... So, thanks to this Question I was able to figure out that I could get all Jackets of a Human by doing: human_object.jacket_set Now I want to get a Queryset with all Humans that own a jacket. Inspired by this Question, I tried something like this, Human.objects.exclude(jacket__set=None) but I wouldn't be here if that had worked. Thx for helping and stay healty! -
Can not create media folder in Django Project
Media folder is not getting created when I run the server. I am working in localhost. You can see the urls.py and settings.py code below. I added 'django.template.context_processors.media' to the templates. My Django Version is 2.0.3 and I am using Python 3.6.8. When I run the code, media folder should be created automatically. How can I fix that issue? MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #settings.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name = "index"), path('about/', views.about, name = "about"), path('articles/', include("article.urls")), path('user/', include("user.urls")), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #urls.py