Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to edit intermediate table Django?
So i'm trying to make 2 models like so class Product(models.Model): name = models.CharField(max_length=70) availability = models.ManyToManyField(Store) class Store(models.Model): name = models.CharField(max_length=150) location = models.CharField(max_length=150) and the problem is somewhere in database i need to store amount of concrete goods containing in each store. Like Product#1 - Store#1(23), Store#2(12) and etc. Is there any possibility to store it in intermediate table (from ManyToManyfield) or is there something easier. -
change database engine on Django from SQLite to MySQL and get django.db.utils.DataError: (1265, "Data truncated for column 'massenger_name' at row 1")
i have a project was in SQLite and changed it to MySQL , i got some errors like "django.db.utils.DataError: (1265, "Data truncated for column 'massenger_name' at row 1") " and when i render the index the index doesn't render and i get "GET / HTTP/1.1" 200 0 with empty page , so what i should do and what's the problem ? setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_p', 'HOST': 'localhost', 'PORT': '3306', 'USER': 'root', 'PASSWORD': '', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1", 'charset': 'utf8mb4',}, } } models.py from django.db import models # Create your models here. class Name(models.Model): massenger_name = models.CharField(max_length=255) action_time = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.massenger_name) views.py from django.shortcuts import render from .models import Name from django.shortcuts import redirect # Create your views here. def Home(request): name_input = request.POST.get('user_name') name_in_model = Name(massenger_name=name_input) name_in_model.save() return render(request , 'eror.html') -
How to check if an object is in another queryset
I need to check if a user has liked a post on a page that displays all posts, I am passing the posts and user's likes below def index(request): if request.method == "POST": text = request.POST["post-text"] Post.objects.create( entity = Entity.objects.create( user = request.user, text = text ) ) return HttpResponseRedirect(reverse("index")) return render(request, "network/index.html", { "posts" : Post.objects.all().order_by('-entity__date', '-entity__id'), "likes" : Like.objects.filter(user = request.user) }) this is the model class Entity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") text = models.TextField() date = models.DateTimeField(default=datetime.now()) class Like(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="likes") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="likes") class Post(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="post") Template: {% for post in posts %} <div> <div>{{post.entity.user}}</div> <div>{{post.entity.text}}</div> <div>{{post.entity.date}}</div> <div class="like-btn d-inline" data-id="{{post.entity.id}}"> {% if post.entity in likes %} <p>yes</p> {%else%} <p>no</p> {%endif%} <div class="d-inline">{{post.entity.likes.count}}</div> </div> <br /> <a href="#">Comment</a> <hr /> </div> {% endfor %} I don't know how to write the if condition, I've tried this {% if post.entity in likes %} but it doesn't work. Any help is greatly appreciated I'm kind of stuck -
Why the data base is not populated even after successful form rendering and submission of form in my django app?
I am beginner in django and making a simple Book registration form to populate sql3 database. I think i did everything right, and the the form is rendering properly and when hit submit it even sends POST request but database don't get populated. I researched on this problem my entire weekend, went to bootstrap documentation and also studied about is_valid() function. It shows error like "book_nameThis field is required. ". I don't know how to deal with it and what should i do?? My models.py from django.db import models class Book(models.Model): #Create your models here book_name = models.CharField(max_length=200) page =models.CharField(max_length=20) authors =models.CharField(max_length=200) registration = models.CharField(max_length=200) #email = models.EmailField(max_length=100) def __str__(self): return self.book_name ``` views.py ``` from django.shortcuts import render from django.http import HttpResponse from . models import Book from .forms import BookForm def say_hello(request): if(request.method=="POST"): #if Post request is made :do something form = BookForm(request.POST or None) if form.is_valid(): print("New Book Object is created") #Book.objects.create(**form.cleaned_data) form.save() else: print(form.errors) print("Invalid Form data") return render(request,'join.html',{}) #Add all things posted to the Bookform else: #otherwise just reder a normal web page return render(request,'join.html',{}) def index(request): all_books=Book.objects.all return render(request,'index.html',{'all':all_books}) # Create your views here. ``` forms.py ``` from django import forms from . models … -
How to communicate completion percentage from backend to front end
Ok so I have a Django backend that performs some tasks and one of the queries computes a complex calculation that can take from a couple of seconds up to 15 minutes based on the entered data. The point is, I have a loop that I can calculate the completion percentage from however I cant figure out how to send an update query saying something like {'completion':20} every loop iteration. Frontend is Node hosted on a separate server. -
Django app NameError however the app is installed
I'm trying to modify Django's built-in authetnication system by adding a custom user model. The customized model is defined inside an app named accounts: from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings # Create your models here. COUNTRIES = settings.COUNTRY_CHOICES class CustomUser(AbstractUser): zip_code = models.PositiveSmallIntegerField(blank=True, null=True) city = models.CharField(blank=True, null=True, max_length=64) address_street = models.CharField(blank=True, null=True, max_length=64) address_number = models.CharField(blank=True, null=True, max_length=32) country = models.CharField(blank=True, null=True, choices=COUNTRIES, max_length=8) I updated the settings.py file this way: AUTH_USER_MODEL = "accounts.CustomUser" I added accounts as an installed app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'store', 'cart', ] When I try to run the python manage.py makemigrations command in terminal to apply changes made to the user model Django's throwing this error: Traceback (most recent call last): File "C:\Users\uhlar\Dev\ecommerce\manage.py", line 22, in <module> main() File "C:\Users\uhlar\Dev\ecommerce\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\uhlar\.virtualenvs\ecommerce-vU6zMECh\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\uhlar\.virtualenvs\ecommerce-vU6zMECh\lib\site-packages\django\core\management\__init__.py", line 386, in execute settings.INSTALLED_APPS File "C:\Users\uhlar\.virtualenvs\ecommerce-vU6zMECh\lib\site-packages\django\conf\__init__.py", line 87, in __getattr__ self._setup(name) File "C:\Users\uhlar\.virtualenvs\ecommerce-vU6zMECh\lib\site-packages\django\conf\__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "C:\Users\uhlar\.virtualenvs\ecommerce-vU6zMECh\lib\site-packages\django\conf\__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\uhlar\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import … -
Django Specific Request URL fails after working properly on a localhost
I have been working on a Django python application which I recently published to a public domain. Beforehand, I had tested my code, including a bit of code which records a user's signature after they draw it on a canvas, sends the signature to the server through the URL encoded in base64, and decodes it on the otherside. After publishing, I am having some trouble sending this long encoded base64 URL. First, I overcame the Apache2 issue 'Request URI Too Long' by editing my apache2.conf: AccessFileName .htaccess LimitRequestLine 50000 Now I simply get '404 Not Found - The request URL was not found on the server'. The URL should be fine, in fact, it finds the URL just fine when I delete some of the length at the end of the URL. Of course, it can then no longer decode the URL. As you can see from my Django error log, there is no POST or GET request, although I am POSTing the code from a form on the page. I feel that is might be the underlying issue. I tried using javascript to POST as shown here. <form action="/UserDashboard/SaveSignature/" id="FormSignature" method="POST" style="width: 60%; margin-left: 20%; margin-right: 20%; height: 60%;"> … -
Instructions on how to fix Internal Server Error in Heroku
I run the Project in Heruku and got an error like this: Internal Server Error The server encountered an unexpected internal server error (generated by waitress) I checked with heroku logs -t and it looks like this: 2022-07-03T17:19:39.609825+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner 2022-07-03T17:19:39.609825+00:00 app[web.1]: response = get_response(request) 2022-07-03T17:19:39.609826+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/deprecation.py", line 134, in __call__ 2022-07-03T17:19:39.609826+00:00 app[web.1]: response = response or self.get_response(request) 2022-07-03T17:19:39.609826+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner 2022-07-03T17:19:39.609826+00:00 app[web.1]: response = response_for_exception(request, exc) 2022-07-03T17:19:39.609826+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 139, in response_for_exception 2022-07-03T17:19:39.609826+00:00 app[web.1]: response = handle_uncaught_exception( 2022-07-03T17:19:39.609827+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 183, in handle_uncaught_exception 2022-07-03T17:19:39.609827+00:00 app[web.1]: callback = resolver.resolve_error_handler(500) 2022-07-03T17:19:39.609827+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 710, in resolve_error_handler 2022-07-03T17:19:39.609827+00:00 app[web.1]: callback = getattr(self.urlconf_module, "handler%s" % view_type, None) 2022-07-03T17:19:39.609827+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__ 2022-07-03T17:19:39.609827+00:00 app[web.1]: res = instance.__dict__[self.name] = self.func(instance) 2022-07-03T17:19:39.609828+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 689, in urlconf_module 2022-07-03T17:19:39.609828+00:00 app[web.1]: return import_module(self.urlconf_name) 2022-07-03T17:19:39.609828+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module 2022-07-03T17:19:39.609828+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-07-03T17:19:39.609828+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1050, in _gcd_import 2022-07-03T17:19:39.609831+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1027, in _find_and_load 2022-07-03T17:19:39.609831+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked 2022-07-03T17:19:39.609831+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 688, in _load_unlocked 2022-07-03T17:19:39.609831+00:00 … -
How to push object from available groups to choosen groups using a model form
Django provides a default model Group in the Django admin dashboard. What is the best way of grouping an object from the model form? I have used both forms.SelectMultiple widget and forms.Select but they are not pushing the selected objects. Or is it only done by signals. -
collectstatic is missing from manage.py commands in Django 4.0.5
I recently switched from windows to WSL ubuntu for development on Django. I'm currently setting up my project for production and I'm stuck because the 'collectstatic' command is missing from manage.py commands. Entering './manage.py collectstatic' in the shell gives me this error Unknown command: Unknown command: 'collectstatic' Type 'manage.py help' for usage. so I check './manage.py help' and I get this response: Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runserver sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver As you can see 'collectstatic' is missing from the list, how can I correct that? thanks and have a nice day! -
I need the total counts of likes to be displayed on my html page but instead i get this or the count is counted only to specific user
posted by {{ participant.user.username }} CONTEST : {{ participant.contest_id }} {{ participant.image_desc }} {% csrf_token %} --> vote Buy for Rs.400 votes:{{ participant.likes }} vote--> -
IntegrityError: NOT NULL constraint failed:
from django.db import models from django.contrib.auth.models import User class TaskList(models.Model): manage = models.ForeignKey(User, on_delete=models.CASCADE, default=None) task = models.CharField(max_length=300) done = models.BooleanField(default=False) def __str__(self): return self.task + " - " + str(self.done) I keep getting this error: NOT NULL constraint failed: new__todolist_app_tasklist.manage_id after I "python manage.py migrate". Any suggestions? -
ModuleNotFoundError: No module named 'grappellidjango'
I've installed "grappelli" according to the instructions(https://django-grappelli.readthedocs.io/en/latest/quickstart.html#installation) But when I try "python manage.py collectstatic", I get this: Traceback (most recent call last): File "/home/golovinss/PycharmProjects/test_platform_001/manage.py", line 22, in main() File "/home/golovinss/PycharmProjects/test_platform_001/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/dist-packages/django/core/management/init.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/dist-packages/django/core/management/init.py", line 420, in execute django.setup() File "/usr/local/lib/python3.10/dist-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.10/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.10/dist-packages/django/apps/config.py", line 228, in create import_module(entry) File "/usr/lib/python3.10/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'grappellidjango' How to fix it? -
ValueError at /post/politics Field 'id' expected a number but got 'politics'
I have a template posts.html {% extends 'base2.html' %} {% block posts %} <div class="row"> <div class="leftcolumn"> <div class="cardpost"> <h1>{{posts.title}}</h1> <h5>{{posts.created_at}}</h5> <div class="fs-4">{{posts.body | safe}}</div> </div> </div> </div> {% endblock %} posts.html extends base2.html, because I want the posts.html to have nav bar functionality <nav id="navbar" class="navbar"> <ul> <li><a href="about">About</a></li> <li><a href="guestposting">Guest Posting</a></li> <li class="dropdown"><a href=""><span>Categories</span> <i class="bi bi-chevron-down dropdown-indicator"></i></a> <ul> <li><a href="tech">Tech</a></li> <li><a href="bizconomics">Bizconomics</a></li> <li><a href="politics">Politics</a></li> <li><a href="religion">Religion</a></li> <li><a href="sports">Sports</a></li> </ul> </li> <li><a href="contactform">Contact</a></li> </ul> above is a section of the nav bar which is on base2.html, and also on the index.html. It works perfectly in the index.html. But when the user is on the posts.html-> path('post/str:pk', views.post, name='post') and they click politics category for instance, I get this error: ValueError at /post/politics Field 'id' expected a number but got 'politics'. Here are my url routes path('', views.index, name='index'), path('post/<str:pk>', views.post, name='post'), path('politicalpost/<str:pk>', views.politicalpost, name='politicalpost'), path('bizconomicspost/<str:pk>', views.bizconomicspost, name='bizconomicspost'), path('techpost/<str:pk>', views.techpost, name='techpost'), path('sportspost/<str:pk>', views.sportspost, name='sportspost'), path('religionpost/<str:pk>', views.religionpost, name='religionpost'), path('subscribe', views.subscribe, name ='subscribe'), path('contactform', views.contactform, name='contactform'), path('about', views.about, name='about'), path('guestposting', views.guestposting, name='guestposting'), path('bizconomics', views.bizconomics, name='bizconomics'), #These are the caregory urls path('tech', views.tech, name='tech'), path('sports', views.sports, name='sports'), path('politics', views.politics, name='politics'), path('religion', views.religion, name='religion'), path('culture', views.culture, name='culture'), path('culturepost/<str:pk>', views.culturepost, name='culturepost'), So how can … -
Django: Image not saving on django update view?
I am trying to update a model, every other information in the model get updated but the image does, i cannot really tell what is wrong the view that is updating the models. views.py @login_required def UpdateRoom(request, pk): room = Chatroom.objects.get(id=pk) if not room : return redirect("chats:message") form = ChatRoomForm(instance = room) if request.user != room.host : messages.error(request , "You are not allowed to Edit Room Settings !") return redirect("chats:message") if request.method == "POST": room.roomname = request.POST.get("roomname") room.topic , created = Topic.objects.get_or_create(name = request.POST.get("topic")) room.description = request.POST.get("description") room.image = request.FILES.get("image") room.save() return redirect("chats:chat-room" , pk=room.id) context = {"form": form, "button_value": "Update" , "room" : room } return render(request, "chat/room_update_form.html", context) -
change field type in django forms
I have a model for a group that has two fields: leader and description. models.py class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() forms.py class GroupForm(forms.ModelForm): class Meta: model = Group fields = ('leader', 'description') My issue is that I want to change the field type for leader. Right now the default is a drop down/select with all the available Users in my database. I don't want Users to be able to make Groups in other Users' names. I want instead for the leader field to be a TextInput field and use javascript to change the leader value to whatever the Users.username value is. So, the I added a widget, but now there's more problems: forms.py class GroupForm(forms.ModelForm): class Meta: model = Group fields = ('leader', 'description') widgets = { 'leader': forms.TextInput(attrs={'id': 'leader', 'type': 'hidden', 'value': ''}) } My goal was to use a script tag on my django template to getElementById('leader') and change it's value to user.username all the while keeping it hidden from the current user. However I keep hitting snags, the main one being I can't seem to change the field type for leader from a select to a TextInput, so every time I try and … -
Fetching Django Objects using the __str__ method
I have this Django model called Clause and I have a __str__ method defined for it. Now I have a form that displays a dropdown for the clauses, but when I POST that form, it converts those clauses to strings, whereas I need the Clause objects. Is there a way to get the clause if I have it's .__str__()? -
Deploy Error: Non-Zero Exit Code - Django app on digital ocean
Hi, I'm trying to upload a django app on digital ocean. The build ran fine but I've no idea why it says this. Deploy Error: Non-Zero Exit Code Please help! Thanks in advance :) -
AttributeError: type object 'StaffFilter' has no attribute '_meta'
When i try to access the urls , it kept return AttributeError: type object 'StaffFilter' has no attribute '_meta'. However, i already declared _meta in filters.py but the error kept returning. Is there any way to solve this problem ? filters.py from django_filters.rest_framework import FilterSet from django_filters import DateTimeFilter, BaseInFilter, CharFilter from .models import Staff class StaffFilter(FilterSet): department__in = BaseInFilter(field_name="department", lookup_expr='in') job_grade__in = BaseInFilter(field_name="job_grade", lookup_expr='in') class Meta: model = Staff fields = [ 'job_grade__in', 'department__in',] -
Cannot get polls to show in url
I am following the django tutorials and so far whilst on task 3, I cannot get the polls to show on the url. If I have followed the instructions properly and carefully, it should look like this: models.py: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) views.py from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) urls.py: from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are … -
Put request.path to a url parameter in Django template
I want to create a back button to a page which can be accessed with a link from another page. To do this, I want to put the first page's path to the link, and on the next page I can put it to the back button. I have this anchor tag: <a href="{% url 'page' path=request.path %}">Go to page</a> When I try to go to the site I get the following error: Reverse for 'page' with keyword arguments '{'path': '/my_site/'}' not found. 1 pattern(s) tried: ['notifications\\/(?P<path>[^/]+)\\Z'] -
How to build a django queryset in order to show all related objects grouped and show in the render template
Achieve: Show the data into the template as example bellow: PLan 1: ABC - General Objective 1 - Sub-Objective-1 - Task 1 - Task 2 - Sub-Objective-2 - Task 1 PLan 2: ZZZ - General Objetivo General 1 - Sub-Objetivo-1 - Tarea 1 PLan 3: DDD - General Objetivo General 1 - Sub-Objetivo-1 - Tarea 1 - Sub-Objetivo-2 - Tarea 1 This means that: A plan can have many general objectives and this general objective can have several sub-objectives and each of its objectives can have one or several tasks. My actual models and all relations: class ActionPlan(models.Model): description = models.CharField ( max_length=250, null=False, default='' ) class PlanObjective(models.Model): actionplan = models.ForeignKey ( ActionPlan, on_delete=models.CASCADE ) description = models.TextField ( max_length=1750, null=False, default='') class PlanSubObjective ( models.Model ) : actionplan = models.ForeignKey ( ActionPlan, on_delete=models.CASCADE ) planobjective = models.ForeignKey ( PlanObjective, on_delete=models.CASCADE ) description = models.TextField ( max_length=1750, null=False, default='' ) class PlanSubObjectiveTask ( models.Model ) : actionplan = models.ForeignKey ( ActionPlan, on_delete=models.CASCADE ) planobjective = models.ForeignKey ( PlanObjective, on_delete=models.CASCADE ) plansubobjective = models.ForeignKey ( PlanSubObjective, on_delete=models.CASCADE ) description = models.TextField ( max_length=1750, null=False, default='' ) This is my actual query: plans = PlanSubObjectiveTask.objects.filter(period=period).select_related( 'plansubobjective', 'planobjective', 'actionplan') I was reading the … -
Serving Django`s static/media files via IBM Cloud Foundry
Greetings to everyone! Need some help to figure out proper deployment concept of simple Django app related to serving static/media files. The goal is to use IBM Cloud Foundry capabilities, so the question is probably more platform specific. The problem is Django in DEBUG=False mode does not take care of static files any more, so its time for some fancy webserver config to take into action. As with IBM Cloud Foundry, I cant find proper way to serve my media links, so images are not visible. For example I get '/media/...' instead of '/static/media/...' with my configuration. The solution should be relatively obvious, but I cant figure it out. For IBM Cloud Foundry my manifest.yml: applications: - name: onlinecourse routes: - route: $HOST.$DOMAIN memory: 128M buildpack: python_buildpack - name: onlinecourse-nginx routes: - route: $HOST.$DOMAIN/static memory: 64M buildpack: staticfile_buildpack So actually there are two apps: 'onlinecourse' manages Django files and 'onlinecourse-nginx' serves static. This is kind boilerplates that leverages use of pre-configured staticfile_buildpack with nginx start up somewhere inside, so probably that is a 'devil' here. First things first, my model is: class Course(models.Model): ... image = models.ImageField(upload_to='course_images/') ... In template I try to render image as follows: <img src="{{ course.image.url … -
how to make an AutoField start from 1000 in Django?
i created a Django model this way in models.py: class Contact(models.Model): id = models.AutoField(primary_key=True, auto_created=True) mail = models.EmailField() and i want the id to start auto generating from 1000 not starting from 1. -
how to dont save a empty input django and why is not showing data on admin page?
how to don't save a empty input django and why is not showing data on admin page ? because when i try to click on myhtml page is save the empty column every click and save it on my data base , how to stop saving the empty input or don't allow user input the empty input ? and why i cant see the datetimefield on admin page ?? this my views.py from django.shortcuts import render from .models import Name from django.shortcuts import redirect # Create your views here. def Home(request): if request.method == 'POST': Name.objects.create(massenger_name=request.POST['user_name']) return redirect(Home) return render(request , 'index.html') and this mosels.py from django.db import models # Create your models here. class Name(models.Model): massenger_name = models.CharField(max_length=50) action_time = models.DateTimeField(auto_now_add=True,null=True, blank=True) def __str__(self): return str(self.massenger_name)