Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I modify this script so that all changes are deployed to django GAE (Google App Engine)?
Background: I have this script called run_fabric that runs at the end of a Github action pipeline and deploys changes in my Django app. I didn't write this code but I think it must only copy the html files from repo to the nginx server and then restarts the server. Unfortunately I try to change python files and I never see my code changes deployed. I think it's because it only copies html files over (I'm trying to make changes to IPN paypal gateway in the hooks.py file so I can update the price on checkout but I don't see this change reflected) Is there a way I can modify this script below to include all python files as well as html so I can see code changes deployed to my Django app hosted on GAE? I've replace ipaddress with my static ip address of GAE for security reasons. Code is below: from fabric import Connection import os import glob x = glob.glob("./web/templates/*.html") c = Connection("ipaddress", port=22, user="fady", connect_kwargs={'look_for_keys': False,'key_filename':'priv'}) for i in x: out =i.split("/")[-1] c.put(f"{i}",f"/home/fady/soild/web/templates/{out}") res = c.run("sudo service uwsgi restart") res = c.run("sudo service nginx restart") print("Done") My project structure is like /root ./run_fabric.py (script above) ./manage.py … -
'list' object has no attribute 'startswith' with Django and scrapy integration
I am getting this peculiar error after I try to runserver once I have finished web-crawling as my web-crawler is connected to django : Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/usr/opt/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Users/usr/opt/anaconda3/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 107, in check_url_settings value = getattr(settings, name) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 93, in __getattr__ val = self._add_script_prefix(val) File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 140, in _add_script_prefix if value.startswith(("http://", "https://", "/")): AttributeError: 'list' object has no attribute 'startswith' It seems to be an error located in one of the django files rather than from my script. However, I am strongly convinced something in my script is causing this. Here's my script: from django.db import models class Cruises(models.Model): title = models.CharField(max_length=200) views.py: from django.shortcuts import render from .models import Cruises def basic(request): long_list = Cruises.objects.values('title') return render(request, 'cruise_control/basic.html', context = {'long_list':long_list}) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.basic, name = 'basic') ] -
Heroku can not find generated file
I have a Django project which generates a PDF file. This below is the corresponding code: def createPDF(name): current_path = os.path.dirname(os.path.dirname(__file__)) template = get_template(f'src.tex') context = { 'content': name, } rendered_tpl = template.render(context).encode('utf-8') process = subprocess.Popen( ['pdflatex', '-output-directory', f'{current_path}/templates'], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) When I run the local server and run my function the PDF is saved in my templates directory. However, after deploying on Heroku, and generating the PDF the PDF is not found. I tried to look for it in the bash, but it is just not there. What is wrong? -
CORS headers not showing up in my request/response on Django
I've made the following CORS implementation on my Django project using django-cors-headers. CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', .... ] INSTALLED_APPS = [ ... 'corsheaders', ] For some reason, I don't see the effect of these headers (I don't have Access-Control-Allow-Origin in my headers). I print out the request and response headers in my view. This is my view: def payment(request, *args, **kwargs): print(request.headers) params_in = json.loads(request.body.decode('utf-8')) headers_in = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer key, } response = requests.post('https://url.com/v1/endpoint', headers=headers_in, data=params_in) resp_out = Response(response.json()['value']) print(resp_out.headers) return resp_out My request headers are ['Host', 'Connection', 'Content-Type', 'Origin', 'Accept-Encoding', 'Cookie', 'Accept', 'User-Agent', 'Referer', 'Accept-Language', 'X-Request-Id', 'X-Forwarded-For', 'X-Forwarded-Proto', 'X-Forwarded-Port', 'Via', 'Connect-Time', 'X-Request-Start', 'Total-Route-Time', 'Content-Length'] and my only resp_out header is 'Content-Type'. Why could this be? What am I missing? -
Changing language in Django i18n
I was working on an ecommerce website and it has two language options. I am fetching data using an sql code I found on youtube. Let me describe how it works; When a vendor adds a product, he must fill the forms on both languages. If the vendor fills only the English form, his product will be seen if a user uses English. If the user switches the language his product disappears. How can I correct this? What I want is, If the 2nd language is filled, bring that. If the English form is only filled, it should bring the English form not make it disappear. Here is the sql code in my views: defaultlang = settings.LANGUAGE_CODE[0:2] currentlang = request.LANGUAGE_CODE[0:2] if defaultlang != currentlang: setting = SettingLang.objects.get(lang=currentlang) products_lat = Product.objects.raw( 'SELECT p.id, p.price, p.is_featured, l.title, l.description,l.slug ' 'FROM product_product as p ' 'LEFT JOIN product_productlang as l ' 'ON p.id = l.product_id ' 'WHERE l.lang=%s ORDER BY p.id DESC LIMIT 50', [currentlang]) prod = Product.objects.raw( 'SELECT p.id,p.price, l.title, l.description,l.slug ' 'FROM product_product as p ' 'LEFT JOIN product_productlang as l ' 'ON p.id = l.product_id ' 'WHERE p.is_featured=%s and l.lang=%s ORDER BY p.id DESC LIMIT 20', [True, currentlang]) Thanks in … -
Requested setting LOGGING_CONFIG when using scrapy with django
I am new to scrapy and django integration, however I am trying something simple to get things going in my career with the two. Essentially, I want to grab the titles from a website, models will read this and views will upload this to a basic html template. However, I get this error when I run scrapy crawl test django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here's my tree: ── cruise_control ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── admin.cpython-38.pyc │ ├── apps.cpython-38.pyc │ ├── models.cpython-38.pyc │ ├── urls.cpython-38.pyc │ └── views.cpython-38.pyc ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-38.pyc │ └── __init__.cpython-38.pyc ├── models.py ├── templates │ └── cruise_control │ └── basic.html ├── tests.py ├── urls.py └── views.py ── cruises ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── settings.cpython-38.pyc │ └── urls.cpython-38.pyc ├── asgi.py ├── scraper │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ └── settings.cpython-38.pyc │ ├── items.py │ ├── middlewares.py │ ├── pipelines.py │ ├── settings.py │ └── spiders │ ├── __init__.py │ └── test.py … -
operator does not exist: bigint = uuid in django
I want to use uuid field as my id (primary key) but there is something wrong with it and i can't fix it this is my model class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE , related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() class Meta: unique_together = [['cart'], ['product']] This Is MY Serializer.py class CartItemSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = ['id', 'product', 'quantity'] class CartSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) items = CartItemSerializer(many=True) class Meta: model = Cart fields = ['id', 'items'] And My Views.py is class CartViewSet(CreateModelMixin, RetrieveModelMixin, GenericViewSet): queryset = Cart.objects.prefetch_related('items__product').all() serializer_class = CartSerializer My database Is postgres Sql My Error when I browse my api my guid -
Access data from one model and use that in another model
I have a website that generates a page for each database entry. Each page generates its own form so a user can submit data for the owner of that page. I want to be able to have a value in my UserInfo class that looks at the Page class to see the PageOwner that is associated with that Page class. I want see which page (database entry) that user came from. class Page(models.Model): address = models.CharField(max_length=150) slug = models.SlugField(unique=True, ) page_owner = models.ForeignKey(Agent, on_delete=models.SET_NULL, null=True, related_name='page') class PageOwner(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=20) def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name() This is my ModelForm. The page_agent_name is not shown to the user using the: (class Meta: exclude statement) class UserInfo(models.Model): user_name = models.CharField(max_length=100, default='', ) user_email = models.CharField(max_length=100, default='', ) # I want these values to get the owner name, phone, email page_owner_name = models.CharField(max_length=100, default='', ) page_owner_phone = models.CharField(max_length=100, default='', ) page_owner_email = models.CharField(max_length=100, default='', ) -
In Django, how do I get the corresponding key for a value passed in through the url?
Here is my models.py: SHOW = ( (0,"Ballers"), (1,"Silicon-Valley") ) class Show(models.Model): show = models.IntegerField(choices=SHOW, blank=True, null=True) Here is from my urls.py: urlpatterns = [ path('<str:show>/', views.ShowList.as_view(), name='show-list'), ] I want to be able to have the url look like this: https://www.mywebsite.com/ballers, but when I try to run it, I get this error: Field 'show' expected a number but got 'ballers'. I know I can fix this by calling the url https://www.mywebsite.com/0, but I don't want the url to look like that. -
why do my django forms stop working when I put them all in the same view?
I create 4 different multiple choice form in the same pages, the problem start when the forms stay togheter, the single form work but when i render all the forms in the views doesn't save and not write in the models, in the views I put messages and the code doesn't open the second if the view. form: countries = forms.ModelMultipleChoiceField(queryset=Nation.objects.filter(id__in= [1,4,8]), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model=CountriesUser fields=['countries'] Views @login_required def CountriesNordView(request): if request.method=='POST': messages.success(request, 'first If') form_nord = CountriesNordForm(request.POST) form_center = CountriesCenterForm(request.POST) form_south= CountriesSouthForm(request.POST) form_topics=TopicsForm(request.POST) if form_nord.is_valid() and form_center.is_valid() and form_south.is_valid() and form_topics.is_valid(): messages.success(request, 'Second If') instance=form_nord.save(commit=False) instance2=form_center.save(commit=False) instance3=form_south.save(commit=False) instance4=form_topics.save(commit=False) instance4.accounts=instance2.accounts=instance.accounts=instance3.accounts=request.user.id instance.save() instance2.save() instance3.save() instance4.save() else: messages.success(request, 'else') form_nord = CountriesNordForm(request.POST) form_center=CountriesCenterForm(request.POST) form_south=CountriesSouthForm(request.POST) form_topics=TopicsForm(request.POST) messages.success(request, 'out of condition ') con={'form_nord' : form_nord, 'form_center': form_center, 'form_south': form_south, 'form_topics': form_topics } return render(request, 'users/preferences.html', context= con) -
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)