Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different url path than pk in Django Generic View
I am using DetailView to display a template with the information about my object from my model. I used int:pk as the path for my object, but now I want to access the view from something like detail/XX-ABC (where XX-ABC stands for a unique field from my model). I didn't find a way to pass this slug and display the object. path(r'detail/<int:pk>/', views.DetailClientsView.as_view(template_name='clients/clients_details.html', context_object_name='client'),name='details_client'), And this is my View. class DetailClientsView(DetailView, UpdateView): model = Clients form_class = InspectionForm def get_success_url(self): return reverse('search:search') -
How to block/override djoser user/me endpoint?
I would like to know if there is a chance to block the djoser's user/me endpoint for specific request methods. I don't see this in the docs. Problem: Now when I have two users { email: 'a@exa.com' }, and { email: 'b@exa.com' }. I can use the first user to change his email to match the 2nd user's email, so both will have the same email, and the second one will be blocked cos of that. Is there an elegant way to check if the email exists from the djoser's level? -
Configure Highcharts JS within Django template
I am working with HighCharts for the first time in Django and ran into two issues. It's a column chart which groups transactions per month, but the months on the X-axis is being named to 0, 1, 2 etc instead of Jan, Feb, Mar. The second issue originates from a solution I tried for issue number one, I tried to manually add xAxis to my JS script located in the template file as below, but this breaks my chart. So how do I modify the Highchart JS properly? For example I have added StyleMode: True in my views.py file, but it doesn't seem like I can modify the chart when it comes to the months for the X-axis in that way. <script> Highcharts.chart('container', { xAxis: { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep' ] } {{ chart|safe }}}); </script> My template which contains my highcharts JS <script src="https://code.highcharts.com/highcharts.src.js"></script> <script> Highcharts.chart('container', {{ chart|safe }}); </script> My views.py # Bar chart - Transactions per month month = [] total_entries = [] for entry in transactions_per_month: month.append('%s Class' % entry['month']) total_entries.append(entry['total_entries']) total_entries = { 'name': 'Month', 'data': total_entries, 'color': 'green' } chart = { 'chart': {'type': 'column', 'styleMode':'true'}, 'title': … -
Get content from meta in external website
I need to extract the meta description of an external website. I've already searched and maybe the simple answer is already out there, but I wasn't able to apply it to my code. Currently, I can get its title doing the following: from urllib.request import urlopen from lxml.html import parse url = "https://technofall.com/how-to-report-traffic-violation-pay-vehicle-fines-e-challan/" page = urlopen(URL) p = parse(page) print (p.find(".//title").text) I am getting title from here However, the description is a bit trickier. It can come in the form of: <meta name="og:description" content="blabla" <meta property="og:description" content="blabla" <meta name="description" content="blabla" So what I want is to extract the first one of these that appears inside the Html. -
Whole page refreshing after AJAX success in Django
I am new to Django and trying to use AJAX for entering and showing a data form a simple form. Here is the html code for form. Task.html <!DOCTYPE html> {% load static %} <script lang="en"></script> <head> <meta charset="UTF-8"> <title>Task</title> </head> <body> <div id="div_yo"> <form method="post" id="form_1"> {% csrf_token %} {{ form }} <button type="submit" name="Submit" class="btn yoyo">Submit</button> </form> {% for items in item %} <h4 class="heading">{{ items.id }} . {{ items }}</h4> <br> {% endfor %} </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% block scripts %} <script src="{% static 'home.js' %}"></script> {% endblock %} </html> Javascript file **home.js** console.log("i am working here"); //$(document).on('submit','#btn' ,function(e){ $('#form_1').submit(function (e){ //e.preventDefault(); var form_data = document.getElementById('form_1').value; console.log(form_data); //alert("Working"); $.ajax('', { type: 'POST', data: { item: form_data, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: alert("added to backend"), } ) }); Python file views.py from django.shortcuts import render, redirect from . import models from .models import * from .forms import * from django.http import HttpResponse # Create your views here. def homepage(request): form = to_do_form() if request.method == 'POST': form = to_do_form(request.POST) if form.is_valid(): form.save() return redirect('homepage') else: form = to_do_form() item = to_do_task.objects.all() mess = "success" context = {'form': form, 'item': item, 'mess': mess} return render(request, 'task.html', context) The problem here … -
Django - Cannot query "email@wp.pl" : Must be "User" instance
Im working on simple registration and login application in Django, but unfortunately when im trying to send request via Postman, its respond with 500 Code and long error at the end with Cannot query "email@wp.pl" : Must be "User" instance.. Here is my models.py from Account without headers: class MyAccountManager(BaseUserManager): def create_user(self,email,username,password = None): if not email: raise ValueError("User must have email") if not username: raise ValueError("User must have name") user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.model.objects.create( email = self.normalize_email(email), password = password, username = username, ) Token.objects.create(user=instance) user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(max_length=60, verbose_name="email",unique=True) username = models.CharField(max_length=30, unique=True) REQUIRED_FIELDS = ['username',] def __str__(self): return self.email @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender,instance=None,created=False,**kwags): if created: Token.objects.create(user=instance) -
Django email Mailbox cannot be accessed
I have the following configuration for sending email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@mydomain.com' EMAIL_HOST_PASSWORD = '**********' from Django shell I send the mail like this >>> from django.core.mail import send_mail >>> send_mail('Test','test message','myemail@mydomain.com',['destinationaccount@gmail.com'],fail_silently=False) but i get the following error smtplib.SMTPAuthenticationError: (550, b'5.2.1 Mailbox cannot be accessed [BN1PR12CA0001.namprd12.prod.outlook.com]') -
How do I model tables from an existing database if they belog to different schemas in python models.py (Django)?
Fox example , I have 3 tables users, sales both from sales_deparment schema, and I have another one called invoices in a schema payments in a database called sample_enterprise. How do I map these there tables with the models.py -
Heroku Django: ValueError: Missing staticfiles manifest entry
Hi I am getting an Internal server error when I run my website and I get the above error: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) 2020-09-07T16:55:13.210685+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'css/main.css' Now my project is called register and the file tree is: --register ----register ------wsgi.py ------settings ----------common.py ----------production.py ----------development.py ----static ----manage.py In my production.py file I have: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) STATIC_ROOT = os.path.join(BASE_DIR, 'static') and in my common.py file I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') #STATIC_DIR = os.path.join(BASE_DIR,'static/') MEDIA_DIRS = [ os.path.join(BASE_DIR,'media') ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' I tried running python manage.py collectstatic however I get the following error: No such file or directory: '/Users/apple/Documents/Project/main/register/register/static' How can I resolve this issue as in development settings it seems to run correctly but in production it gives me a server 500 error. EDIT According to WhiteNoise documentation: I have set: WHITENOISE_USE_FINDERS=True In my commony.py file however, now I am getting an error: for entry in os.scandir(path): 2020-09-07T17:11:40.454766+00:00 app[web.1]: FileNotFoundError: [Errno 2] No such file or directory: '/app/register/static' : -
Granting a user access to view data based on their permissions
I have a basic CRUD web application in Django using a database with Postgres 12 that simply displays articles based on a search. I need to implement a system such that the articles returned from a user's search are articles that the user only has access to. For example, if my articles table article is populated id|title|summary|source |category --+-----+-------+--------+-------- 0 |... |... |NYTimes |politics 1 |... |... |BBC |environment 2 |... |... |BBC |politics 3 |... |... |Wired |technology 4 |... |... |NYTimes |fashion If a user makes a search, but only was granted access to view sources NYTimes and BBC as well as only categories politics, then the the user would only see id|title|summary|source |category --+-----+-------+--------+-------- 0 |... |... |NYTimes |politics 2 |... |... |BBC |politics Right now I implemented this schema. |user_group| |data_permission| |id |-----|group_id | |name | |column | |value | and use this raw query to filter the results. SELECT * FROM article a INNER JOIN data_permission p0 ON p0.group_id = %s AND p0.column = 'source' AND p0.value = a.source INNER JOIN data_permission p1 ON p1.group_id = %s AND p1.column = 'category' AND p1.value = a.category; It's a simple problem, but I'm having trouble understanding if … -
Django/PyCahrm. Relocation project to another PC with /venv can`t find `dotenv` module and can`t to install it
I relocate my Django project (mysite) with /venv to another Computer. On first computer it works good. And where was istalled 'dotenv' module. In PyCharm i set my Project Interpreter as: Python 3.7 (mysite) C:\Users\User\mysite\venv\Scripts\python.exe But 'python manage.py runserver' in new computer raises: ModuleNotFoundError: No module named 'dotenv' But in ../mysite/venv/Scripts presence file dotenv.exe. And sobfolder ../venv/lib/site-packages/dotenv/ too. In PyCharm-Settings-Project Interpreter in Package list presense python-dotenv 0.14.0 Ok. I try to install dotenv by pip, but it raise error: C:\Users\User\mysite\mysite>pip install dotenv Collecting dotenv Using cached https://files.pythonhosted.org/packages/e2/46/3754073706e31670eed18bfa8a879305b56a471db15f20523c2427b10078/dotenv-0.0.5.tar.gz Complete output from command python setup.py egg_info: Command "python setup.py egg_info" failed with error code 1 in C:\Temp\pip-wheel-4a1x88l2\distribute\ Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\site-packages\setuptools\installer.py", line 126, in fetch_build_egg subprocess.check_call(cmd) File "C:\Users\User\Anaconda3\lib\subprocess.py", line 347, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['C:\\Users\\User\\Anaconda3\\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\\Temp\\tmpz_ip4m3r', '--quiet', 'distribute']' returned n on-zero exit status 1. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Temp\pip-install-07by3weo\dotenv\setup.py", line 23, in <module> scripts=['scripts/dotenv'] File "C:\Users\User\Anaconda3\lib\site-packages\setuptools\__init__.py", line 152, in setup _install_setup_requires(attrs) File "C:\Users\User\Anaconda3\lib\site-packages\setuptools\__init__.py", line 147, in _install_setup_requires dist.fetch_build_eggs(dist.setup_requires) File "C:\Users\User\Anaconda3\lib\site-packages\setuptools\dist.py", line 676, in fetch_build_eggs replace_conflicting=True, File "C:\Users\User\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 766, in resolve … -
Translating URL patterns in Django
I am trying to internationalize a dictionary Django web application and I am having problems with translating URLs. Here is my project's urls.py: from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = [] urlpatterns += i18n_patterns( path(_('dictionary/'), include('dictionary.urls')), ) Here is my app's urls.py: from django.utils.translation import gettext_lazy as _ app_name = "dictionary" urlpatterns = [ path("", views.index, name="index"), path(_("define"), views.define, name="define"), path(_("define/<slug:headword_slug>"), views.headword, name="headword"), ] I have translated and compiled all the necessary files in my locale folders for both the project and app. When I change the language prefix in the URL, templates, forms, and various error messages are all translated very successfully. However, even though the language of the content changes, my URL patterns are always displayed in English. What am I doing wrong? -
UnboundLocalError at /index/register/ .local variable 'context' referenced before assignment
local variable 'context' referenced before assignment.I need a explaination Views.py from django.shortcuts import render from memoster.forms import UserForm, UserProfile from django.http import HttpResponseRedirect, HttpResponse # ----LOGIN---- # from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.urls import reverse def home_index(request): return render(request, 'home_index.html') def index(request): return render(request, 'index.html') def register(request): if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfile(data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() else: print(user_form.errors, profile_form.errors) else: user = UserForm() profile = UserProfile() context = {'user': user, 'profile': profile} return render(request, 'registration.html',context) def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('memoster:index')) else: return HttpResponse("Account Not active") else: print("username{} and password {}".format(username, password)) print("Invalid credentials") else: return render(request, 'login.html') @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('home_index')) traceback enter image description here Request Method: POST Request URL: http://127.0.0.1:8000/index/register/ Django Version: 3.1.1 Exception Type: UnboundLocalError Exception Value: local variable 'context' referenced before assignment Exception Location: C:\Users\Faris\PycharmProjects\djangoProject3\memoster\views.py, line 40, in register Python Executable: C:\Users\Faris\PycharmProjects\djangoProject3\venv\Scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\Users\Faris\PycharmProjects\djangoProject3', 'C:\Python38\python38.zip', 'C:\Python38\DLLs', 'C:\Python38\lib', 'C:\Python38', 'C:\Users\Faris\PycharmProjects\djangoProject3\venv', 'C:\Users\Faris\PycharmProjects\djangoProject3\venv\lib\site-packages'] -
SMTP Connection failed unexpectedly Django Email Message
I am using trying to send emails to 500 contacts by iterating over each. The reason is send_mass_mail won't work for over 100 emails. Below is my code for e in data: email = EmailMessage( 'subject', 'body', 'myemail@gmail.com', e, headers={'Message-ID': 'foo'}, ) email.send() While it works perfectly for around 100 emails, I get this error when I tried 500 emails Exception while running run() in 'inventory_management.scripts.many_load' 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 "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\email_notifications.py", line 65, in run_from_argv super().run_from_argv(argv) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\email_notifications.py", line 77, in execute super().execute(*args, **options) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\utils.py", line 62, in inner ret = func(self, *args, **kwargs) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\commands\runscript.py", line 283, in handle run_script(script_mod, *script_args) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\commands\runscript.py", line 161, in run_script exit_code = mod.run(*script_args) File "D:\Work\Others\BTech\SCode\emporium_apparel\inventory_management\scripts\many_load.py", line 48, in run print(email.send()) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\mail\message.py", line 276, in send return self.get_connection(fail_silently).send_messages([self]) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\mail\backends\smtp.py", line 69, in open self.connection.login(self.username, self.password) File "D:\Tools\Anaconda\envs\heroku_env\lib\smtplib.py", line 698, in login self.ehlo_or_helo_if_needed() File … -
django - How can I add different AppConfigs for testing different apps?
In my project I have two apps: main_app and reusable_app. reusable_app is supposed to be independent and reusable in other projects. It has its own models and signals. And I connected a lot of these signals to receivers in main_app. Doing ./manage.py test runs tests for both main_app and reusable_app. But the tests for reusable_app break when the signals are called because data needed for main_app to process these signals is not there. I don't want to have to load/setup data for main_app in reusable_app's tests. So, the solution would be to disconnect the signal receivers. Also, reusable_app tests should not have to know about disabling any signal receivers. I can create different AppConfigs that selectively connect or not these signal receivers. But how do I change the AppConfig depending on which app I'm running the test for? -
How to display Foreignkey Data in Django html page?
I want to get data from related foreign-key models, but I am unable to get data from the related model, Please let me know how I can do it. I want to display name value from Model2 table.. here is my models.py file... class Model1(models.Model): name=models.Charfield(blank=True) class Model2(models.Model): name=models.CharField(default=None) model1=models.Foreignkey(Model1, related_name='model_one', on_delete=models.CASCADE) here is my views.py file... def display_data(request, id): test_display=Model1.objects.filter(pk=id).first() return ender(request, 'page.html', {'test_display':test_display}) here is my test.html file where i am displaying name from Model2 table <p>{{test_display.model_one.name}}</p> -
Dynamic price range filter in Django
I have a product model with attributes name, price, description, category. I want to create a dynamic price range filter with check boxes in the view. for example if I query my product like below: get_products = Product.objects.filter(category='Men') Now if the above query has a list of products with min_price = 500 and max_price=5000 then I would like to have 4 set of price range filters like below: 1)500-1500 2)1501-2500 3)2501-3800 4) 3801-5000 But the above should be dynamic based on min and max price value. I have tried to use range(min,max,steps) but it is very difficult to generate a dynamic price range filter. Any help is highly appreciated. -
How to use mailgun post for callback
I am trying to retrieve MailGun event data into my Django application but when I try and parse this I keep getting a type error or None object error. What is the correct way of parsing this? I have tried the below but it returns a TypeError: 'NoneType' object is not subscriptable: def mailgun(request): event_data = request.POST.get('event-data')['event'] This is an image of a postbin that receives a webhook request: What is the correct way of using a mailgun response? -
Heroku Django Celerey: raised unexpected: ValueError Server 500 error
I am trying to schedule some tasks one Django celery on my Heroku application however, I have got an error: raised unexpected: ValueError('Redis URL must specify one of the following schemes (redis://, rediss://, unix://)',) Now for your reference, I have three settings files for my production and development environment with a common one. My app is called register and the file containing the wsgi.py is: register -settings ----common.py ----production.py ----development.py -celery.py -wsgi.py Now in my production.py file I have: from register.settings.common import * import os from urllib.parse import urlparse import django_heroku DEBUG = False ALLOWED_HOSTS = ['mysite.herokuapp.com','wwww.mysite.com','mysite.com'] #EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') #EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') redis_url = urlparse(os.environ.get('REDISTOGO_URL', 'redis://localhost:6959')) CACHES = { 'default': { 'BACKEND': "django_redis.cache.RedisCache", 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'DB': 0, 'PASSWORD': redis_url.password, } } } CELERY_BROKER_URL=os.environ.get('REDISTOGO_URL') CELERY_RESULT_BACKEND=os.environ.get('REDISTOGO_URL') CELERY_BROKER_TRANSPORT_OPTIONS = { "max_connections": 2, } STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals(),logging=False) And in my celery.py file I have: from __future__ import absolute_import import os from celery import Celery from django.conf import settings import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'register.settings.production') app = Celery('register') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) I do not know what is causing this error as when I do heroku config I can see that the config vars are set correctly. This is also … -
How to deal with duplicate apps in Django project?
I downloaded a django project folder and am trying to run the project. I created a virtual environment, installed the requirements.txt and tried the python manage.py runserver command but it returned with populate() isn't reentrant error. After looking at some other answers on stack overflow, i got proper traceback and got this instead: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin But these are my installed apps and there are no duplicates: `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_user_agents', 'haystack', 'home', #'TNI', #'analytical']` How do I fix this? Am I missing some steps? -
Django ModuleNotFoundError: No module named 'mysite.settings' when trying to host application with wsgi server
So I wanted to deploy my first django application on a cherryPy webserver using wsgi. And I have issues with os.environ['DJANGO_SETTINGS_MODULE']. When trying to run application callable it throws error, that module is not found. Project structure: ResourceManager ResourceManager ResourceManager __init__.py cherryserver.py settings.py urls.py wsgi.py SimpleResourceManager migrations __init__.py admin.py apps.py models.py serializers.py tests.py urls.py views.py manage.py wsgi.py file: import os import sys from django.core.wsgi import get_wsgi_application BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,BASE_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'ResourceManager.settings' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ResourceManager.settings') application = get_wsgi_application() cherryserver.py: import cherrypy from ResourceManager.ResourceManager.wsgi import application if __name__ == '__main__': # Mount the application cherrypy.tree.graft(application, "/") # Unsubscribe the default server cherrypy.server.unsubscribe() # Instantiate a new server object server = cherrypy._cpserver.Server() # Configure the server object server.socket_host = "0.0.0.0" server.socket_port = 8080 server.thread_pool = 30 # Subscribe this server server.subscribe() cherrypy.engine.start() cherrypy.engine.block() Application works fine when using command runserver 8080, but when i tried to run it on different server. It says ModuleNotFoundError: No module named "ResourceManager.settings". So i tried: Change where cherryserver.py is located in directory, I have added additional lines of code to wsgy.py file and I'm running out of ideas what is wrong when I'm deploying my app on different server. Why I'm using cherryPy, well I have … -
nginx/django/uwsgi: can't load admin static css files
I have searched extensively and found many similar/related questions, none of the answers/suggestions solve my problems. I'm trying to describe my problems as in details as possible. Please bear with me for my lengthy post. I'm following the steps in the document https://docs.djangoproject.com/en/3.1/intro/ to create the polls app under mysite project and the app works as expected when I run "python manage.py runserver 0:8000" (accessed as http://hostname:8000/) to serve the pages. But I get problems when I run nginx and uwsgi (use port 80 and socket) to serve pages. There're no errors and I can access all pages. But the admin page (http://hostname/admin/) doesn't display properly as if no css files in effect. My project root is /data/webapps/mysite and I have the following codes in nginx.conf. location /static { alias /data/webapps/mysite/static; # your Django project's static files - amend as required } Under the project root directory, I have directories mysite, polls, static, templates and some other files, such as manage.py (all according to the document at the link above). In mysite/settings.py, I have the following lines. STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATIC_URL = '/static/' Under the directory static, I have directories admin and polls and under static/admin, I have directories … -
Cannot get is_valid() to go back to template with bound form
In the Django docs, it says "We call the form’s is_valid() method; if it’s not True, we go back to the template with the form. This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required." I am trying to get this behaviour to work. In views.py: def test(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): return redirect('auctions/test.html') else: form = TestForm() return render(request, 'auctions/test.html', {'form': form}) In forms.py: class TestForm(forms.Form): testnumber = forms.DecimalField(max_digits=1) In test.html: <form action="{% url 'auctions:test' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> Now, when I submit the form with a number that is more than 1 digit, is_valid() evaluates to False. When that happens, the docs says the template should be rendered with the bound form and the error. Instead, nothing happens, and I get ValueError: The view auctions.views.test didn't return an HttpResponse object. It returned None instead. -
Python Django saved posts computed method
Assuming im using the default django model, a Post model (code below) and a SavedPost model that links a User to a Post (if the certain user with the certain post exists then that post is saved for that user) and a Follower model that links 2 user (similar to SavedPost). What im trying to do: An API that for a user, they get all posts for the users they follow, in addition each of these posts has an extra 'field' to say if that post is saved or not. class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_type = models.CharField(max_length=1, choices=[('B', 'Blog'), ('V', 'Video')], default='B') file_path = models.URLField(null=True) title = models.CharField(max_length=255) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class SavedPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: # A user can save a post only once. unique_together = ('user', 'post') class Follower(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") created_at = models.DateTimeField(auto_now_add=True) class Meta: # A user can follow another user only once unique_together = ('user', 'follower') API View: @permission_classes([IsAuthenticated,]) @api_view(['GET']) def get_following(request): user = request.user following = Follower.objects.filter(follower=user).values('user') # saved_posts = SavedPost.objects.filter(user=user, post__user__in=following).order_by('-post__created_at') posts = Post.objects.filter(user__in=following).order_by('-created_at') serializer = PostSerializer(posts, … -
The include tag in Django isn't working properly
so I have a lot of repeated code in my templates and one of them are the link tags for CSS in my html templates. Since they are all similar i put them in a separate file and used the include method like this {% include 'path to file' %} the problem is when running the website is that the page is not using any of the CSS and what's confusing even more is that if i view the page source on chrome it shows that all of the CSS link tags are there. so how can i fix this ?