Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django testing - test the view which handles an ajax call
In testing Django, the view is returning 200 code but not sending any error message related. def ajax_view(request): msg = '' if request.is_ajax(): username = request.POST['username'] user = User.objects.get(username=username) msg = 'user exists' return HttpResponse(msg) In tests.py response = self.client.post(reverse('ajax_view'), data={'username': 'hello'}) self.assertEqual(200, response.status_code) self.assertContains(response, 'exist') It seems it is not going through the request.is_ajax().. How can I mock the ajax call in Django testing? -
Js or Django? Opinions please.
Seeking opinions. I just want to say that in no way am I over looking the amount of work that would need to be put in to even become decent in any of these disciplines, I'm trying to understand if my logic of this road map is technologically feasible and appropriate. Started down the road of learning python for ease of learning and wanted to tinker with ardiuno's, rasp pi's other IOT's. Also emerging fields python seems to be strong in, blockchain (smart contracts) A.I., machine learning and robotics all seem challenging but interesting. But being realistic I found it maybe a "faster" road if I learned web development to get a job as a dev while I increase my skills in those other area's mentioned. That's where I came across Django. Knowing my interests stated above I figure it be beneficial to learn HTML5/CSS and Django instead of JS to become that web developer since Django is a framework for python logic for websites. So because I've been learning Python, it seems to me, time wise, that Django would allow me to be a web developer while still being able to hone my python foundation for projects ahead as … -
Custom user model and table in django
I know that the django default table to store username and password is in auth_user table. I currently want to use my own table named SysUser, so I've created user model and user manager. Here is my code: model.py class MyUserManager(BaseUserManager): def create_user(self, username, name,role,accesslevel, passwd=None): if not login: raise ValueError('Users must have an username') user = self.model( username=username, name=name, role=role, accesslevel=accesslevel, ) user.set_password(passwd) user.save(using=self._db) return user def create_superuser(self, username, name,role,accesslevel, passwd): user = self.create_user( login, passwd=passwd, name=name, role=role, accesslevel=accesslevel, ) user.is_admin = True user.save(using=self._db) return user class SysUser(AbstractBaseUser): user_id = models.IntegerField(db_column='User_Id', primary_key=True) username = models.CharField(db_column='Username', max_length=50,unique=True) name = models.CharField(db_column='Name', max_length=100) passwd = models.CharField(db_column='Passwd', max_length=30, ) role = models.IntegerField(db_column='Role' ) accesslevel = models.IntegerField(db_column='AccessLevel') objects = MyUserManager() USERNAME_FIELD = 'username' class Meta: db_table = 'SysUser' As we can see, the attributes in my new table are different with the default table. But I get an error when I create a user and get all user. Here is my code to create user: >>> from test.models import SysUser >>> user = SysUser.objects.create_user(username='simon',name='Simon',role='1',accesslevel='1',passwd='simon123') Here is my code to get all user: user = SysUser.objects.all() print(user) Here is the error return: Traceback: File "C:\Python\Python36\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (column … -
HTML : Django Form validation and loading gif "onclick"
I have a django html form where I am taking a name and submitting it. The form works fine when input data is filled in. I want to add additional form validation before loading the gif. Please find below the code. The problem is when I add the form.valid() the gif is not loaded but validation works fine. I am trying add both form validation and gif loading at the same click event. I tried an if condition with form.valid() but that again is not loading the gif post validation. <script> function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10) seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { timer = duration; } }, 1000); } jQuery(function ($) { var threeMinutes = 60 * 3, display = document.querySelector('#time'); startTimer(threeMinutes, display); }); </script> <div class="row"> <p></p> <h5>Form</h5> <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <div><span class="error-msg" id="Name"></span><div> <center><button type="submit" onclick="$('#loading').show();">Submit</button></center> </form> <div id="loading" style="display:none; text-align: center;">{% load … -
Django : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
I don't know how to fix the error : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty django-celery/ proj/ init.py celery.py settings.py/ init.py: from __future__ import absolute_import, unicode_literals import app as celery_app __all__ = ('celery_app',) celery.py: from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings.py: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Seoul' CELERY_BEAT_SCHEDULE = { 'send-summary-every-hour': { 'task': 'summary', 'schedule': 3600.0, 'args': "HELLO" }, # Executes every Friday at 4pm 'send-notification-on-friday-afternoon': { 'task': 'my_app.tasks.send_notification', 'schedule': 10, }, } INSTALLED_APPS = ( 'django_celery_beat', ) I get error : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. How can I fix this. celery -A proj worker --loglevel=info -
Django: python manage.py createdb Library not loaded: libmysqlclient.20.dylib
I'm almost new with django. When I sent to the terminal on the django project with python manage.py createdb, I had an error. Traceback (most recent call last): File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 26, in <module> import MySQLdb as Database File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so, 2): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.20.dylib Referenced from: /Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/db/models/base.py", … -
Django template tag, making my list empty or I'm not pass anything
Thanks for reading my post okay, I'm currently working on Django project that displays data in a dashboard; I manage to display and draw charts with Chart JS, great but now I need to limited number data in Django database to be displayed on charts and display the most recent data put into the database. I use Django built-in tag to display the most recently is "last" and limiting the display data, the tag is "length_is". Here are my HTML codes for using the "last" tag and index page <div class = "containor"> <div class = "float-right my-4 chartjs-render-monitor" id="chartContainerPH" style="width: 49%; height: 400px;display: inline-block; background-color:#FDFDFD;"> <center> <a class="title-link" href="{%url 'ph' %}">PH:</a> <p>{{tank_system.ph|last}}</p> </center> {%include 'FrounterWeb/includes/PHchart.html'%} </div> This is the result I get Last Tag result in my index Here' my code for chart HTML which I use the length_is tag {%block PHchart%} <canvas class = "my-4 chartjs-render-monitor" id="PHchart" ></canvas> <script> var ctx = document.getElementById("PHchart"); var PHchart = new Chart(ctx, { type: 'line', data: { labels: [ {%for tank_system in tank%} "{{tank_system.datetime}}", {%endfor%} ], //x-Axis datasets: [{ //y-Axis label: 'PH1', data: [ {%for tank_system in tank%} {{tank_system.PH|length_is:"3"}}, {%endfor%} ], backgroundColor: "rgb(249, 24, 24,0.2)", borderColor: "rgb(249, 24, 24,0.2)", fill: true, }] … -
LinkedIn OAuth2 redirect url is not working
With social-auth-app-django, I set up the settings as follows: INSTALLED_APPS = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ...] TEMPLATES = [{ ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', .... }] MIDDLEWARE_CLASSES = [ 'social_django.middleware.SocialAuthExceptionMiddleware', ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.linkedin.LinkedinOAuth2', 'django.contrib.auth.backends.ModelBackend', ) And the callback/redirect url is https://localhost:8000/auth/linkedin/callback as the linkedIn dev says, but it is not working. What's wrong here? -
Bash script to create a scheduled task
I wrote a bash script to create a scheduled task and run a django app. I am using Git Bash as my terminal, and I have been able to manually run the commands in the snippet posted below with success. However, when I run bash script with these same commands, the scheduled task and the django app are never run. Why is there a discrepancy in behavior and how can I correct this in my bash script? #!/usr/bin/env bash // Create scheduled task echo schtasks //create //tn my-task //tr '"python app/manage.py loaddata /resources/output.json"' //sc daily //st 09:30 //ri 60 //et 16:00 // Run app echo python app/manage.py runserver echo "TERMINATED" $SHELL -
Make Django query result as a linked list
I have a Django model which has 4 fields including id, from_id, name, project_id. It presents a transaction record about this project. For example: id from_id name project_id 1 null A 1 2 1 B 1 3 null B 2 4 2 C 1 5 3 A 2 So how can I get a linked list likes A->B->C for project 1 or B->A for project 2? (A->B->C and C->B->A are both great, I just want to get the transaction by query) -
Django: how to change label for a form dynamically
is it possible to change the labels of a formset dynamically depending on a variable? Here is my views.py : def ctest(request): c_test_tokens, gaps, tokenindexe = generate_c_test(beispieltext()) # Here I want to give CTestform another variable which includes a list # gaps is an Integer ctestformset = formset_factory(CTestform, extra=len(gaps)) return render(request, 'ctest.html', {'form': ctestformset}) while creating the formset I want to give it another variable with which I can specify the names of the labels of each form. Is this possible and how do I do it or should I search for an alternative? Here is my forms.py: class CTestform(forms.Form): hello = forms.CharField(widget=forms.TextInput(attrs={'size': '5'}), required=False, label='hallo', label_suffix='') -
Django QuerySets, Annotate Sum of Filtered Related Objects field without returning NoneType
Is there a way to perform annotation sum on filtered related model fields without returning None when all the related results have been filtered out? For example, with the models below, I would like to have the yearly and monthly donation sums but excluding donations that were not successful or were refunded. I started using Case/When to avoid the problem of receiving None rather than 0 for users with no donations. But I still need to excluded unsuccessful and refunded donations. Reading Django's docs, I found you can set a custom _base_manager, but then it says "Base managers aren’t used when querying on related models". Is there another approach I could take? models.py class Profile(Model): user = OneToOneField( User, on_delete=CASCADE, related_name='profile' ) has_donor_access = BooleanField( default=False ) ... objects = Manager() account_objects = AccountManager() def __str__(self): return "{0} :: {1}".format( self.user.get_full_name(), self.user.get_username()) class Donation(Model): user = ForeignKey( User, blank=True, null=True, on_delete=SET_NULL, related_name='donations', verbose_name=_('donor') ) creation_date = DateTimeField( auto_now_add=True ) amount = DecimalField( decimal_places=2, max_digits=9 ) is_success = NullBooleanField( default=True ) is_refunded = NullBooleanField( default=False ) ... def __str__(self): user_profile = self.user.profile if self.user else "Anonymous" return "{0} :: ${1} :: {2}".format( user_profile, self.amount, self.creation_date) managers.py class AccountQuerySet(QuerySet): def with_donation_stats(self): a_month_ago … -
Paginator object has no attribute 'get_page'
I am trying to use paginator for the first time on my django project. I am having problems getting it to work. When i run it I get the error AttributeError: 'Paginator' object has no attribute 'get_page'. I have played around with it but cannot seem to resolve it. Can somebody help me please? The error seems to be o the line " babysitters = paginator.get_page(page) " View.py File from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import Babysitter, Education, Reference, Work from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from .choices import numbers_choices, minder_choices, county_choices # Create your views here. def all_babysitters(request): babysitters = Babysitter.objects.all() paginator = Paginator(babysitters, 3) page = request.GET.get('page') babysitters = paginator.get_page(page) return render(request, "babysitters.html", {"babysitters": babysitters}) -
Django Rest Framework - POST request invokes GET request (localhost)
When I try to access http://localhost:8000/api/articles/ it works fine. When I try to access http://localhost:8000/api/articles/1 it works fine. When I try to access http://localhost:8000/api/articles/create Django thinks that I am trying to perform a GET request ('get': 'retrieve'). What am I doing wrong? errors invalid literal for int() with base 10: 'create' urls.py app_name = 'articles' urlpatterns = [ path('', ArticleViewSet.as_view({'get': 'list'}), name='list'), path('<pk>/', ArticleViewSet.as_view({'get': 'retrieve'}), name='detail'), path('create/', ArticleViewSet.as_view({'post': 'create'}) ,name='create'), views.py class ArticleViewSet(ViewSet): queryset = Article.objects.all() def list(self, request): articles = query_filter(request, ArticleViewSet.queryset) serializer = ArticleSerializer(articles, many=True) articles = formatter(serializer.data) return Response(articles) def retrieve(self, request, pk=None): article = get_object_or_404(ArticleViewSet.queryset, pk=pk) serializer = ArticleSerializer(article, many=False) article = formatter([serializer.data]) return Response(article) def create(self, request): articles = ArticleViewSet.queryset articles.create(title=request.data['title'], body=request.data['body']) article = articles.last() serializer = ArticleSerializer(article, many=False) article = formatter([serializer.data]) return Response(article) -
Inline block not being applied
Im kinda new to HTML/CSS and im trying to align images side by side. I'm trying to use inline block but it's not being applied. Could someone please point out where i am going wrong. Parent class; <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="/static/Css/Parent.css"> <meta charset="utf-8"> </head> <body> <div class="AllCardViews"> {% block Movies/Shows %}{% endblock Movies/Shows %} </div> </body> </html> Child Class; {% extends "Movies/Parent.html" %} {% block Movies/Shows %} {% for Movie in Movies %} <div class="CardView"> <img src= '{{ Movie.Image }}' align = "middle" alt=""> </div> {% endfor %} {% endblock Movies/Shows %} Corresponding Css; .AllCardViews { width: 170px; text-align: center; max-width: 80%; margin: 5px 20px; margin-left: 300px; margin-right: 300px; margin-top: 300px } .AllCardViews .CardView img { display: inline-block; } Above you can see that i'm trying to specify where i want to use inline block as im selecting both classes yet it doesn't seem to work. -
Making list of model into field of another model in django
I am totally newbie in django and I am trying to make a restaurant app. I have two models: component and meal, and i want to make a field in meal model that contains a list of components models. Is there any way to do such a thing ? For example sandwich contains bread, cheese and ham. Thanks for your help -
Uploading Json to django model database results in Key Error
I have a custom manage.py command which I am using to upload a json file (a list of dictionaries) to my model. It appears to upload two records fine, but then throws a key error: KeyError: 'headline' My code is as follows: class Command(BaseCommand): def handle(self,*args,**options): filename = '/DoJ_Data_01-12-18.json' newpath = str(Path(home))+filename with open(newpath) as json_file: data = json.load(json_file) for d in data: q = doj(headline=d['headline'],topics=d['topics'],text=d['text'],url=d['url'],date=d['date']) q.save() As far as I can tell the json is valid. What am I missing? -
Python: Deserializing an object of type 'str' to OrderedDict
I'm sending my json to Django server but the problem lies when I want to send a list of dictionaries to it. I have a Load namedtuple which has a legs attribute that is a list. I have a Leg namedtuple that takes in strings. def test_upload_load(self): from collections import namedtuple load_attributes = 'reference miles rate legs' leg_attributes = 'ref f_code f_date t_code t_date' Load = namedtuple('Load', load_attributes) Leg = namedtuple('Leg', leg_attributes) f_date, t_date = str(datetime.now()), str(datetime.now()) load = Load(miles=234.3, rate=432.4, reference='112FR3XSR', legs=[]) leg1 = Leg(ref='1112222', f_code='SSS', f_date=f_date, t_code='XXX', t_date=t_date) load.legs.append(leg1._asdict()) res = self.client.post('/post/create_load/', js) Here's the function that receives the data, but legs is of type str. If I do print(type(legs)), it says type str, when it should be OrderedDict. I tried deserializing it by using json.loads but I get the following error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Here's the code that makes the error: @api_view(['POST']) def save_load(request): reference = request.POST.get('reference') miles = request.POST.get('miles') rate = request.POST.get('rate') legs = request.POST.get('legs') print(json.loads(legs)) return Response(status=status.HTTP_200_OK) I pretty much want legs to be turned into an actual dictionary which I can retrieve values from. -
Error while installing mysqlclient in django project
I've been trying to figure this out for a couple days. I am trying to make a django project in a virtual environment and install mysqlclient on it. Process went like this: In my project path: virtualenv pyvenv1 Then I activated it: source /pyvenv1/bin/activate Then I installed django: pip install django Then I made a new project: django-admin startproject djangop1 Then inside that project I try to install mysqlclient pip install mysqlclient I get back this: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command /Users/daniel/Documents/Python/DjangoP1/py1/bin/python3.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/1h/dg482p2x2bz7n46_px8nphf40000gn/T/pip-install-xgahev5_/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /private/var/folders/1h/dg482p2x2bz7n46_px8nphf40000gn/T/pip-wheel-4_cp0769 --python-tag cp37: running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 copying _mysql_exceptions.py -> build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb creating build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.macosx-10.9-x86_64-3.7 gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common … -
Django: Get all object and return it to view
im new in python and Django also I was searching for answer but can't find it :( I have 3 class in my app first one class in my app is Exam, Question, Answer. models.py class Egzam(models.Model): name = models.CharField(max_length=200, default='kolokwium ') date = models.DateField('date publish') code = models.CharField(max_length=200) def __str__(self): return str("%s %s" % (self.date, self.name)) class Question(models.Model): egzam = models.ForeignKey(Egzam, on_delete=models.CASCADE) name = models.CharField(max_length=200) # nazwa pytania def __str__(self): return self.name class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=200) #treść odpowiedzi correct = models.BooleanField(default=False) def __str__(self): return self.answer_text So Egzam class can handle few Question and Question class can handle few Answers. What i want to do is list all exam's on index page and after i clicked on one of them, my app should open new page where I see all Qestion and Answers to this specyfic Exam. Here is rest of my code urls.py app_name = 'kolos' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.EgzamView.as_view(), name='view'), ] views.py class IndexView(generic.ListView): template_name = 'kolos/index.html' context_object_name = 'egzam_list' def get_queryset(self): return Egzam.objects.all() class EgzamView(generic.DetailView): model = Egzam template_name = 'kolos/egzam.html' def get_queryset(self): return Answer.obects.filter() -
Django using NGINX, WSGI and gunicorn give 404 on all pages except root
I'm trying to get a production server running for my Django app, but am having issues with 404 errors on every page except the root webpage. I can access it through the url or the ip address and get the main page to render, but any of the other pages don't work. I had the page working on a sandbox server, and the 404 pages are nginx, not django 404 pages, which makes me think it's something to do with how I've configured my nginx sites-available file. server { listen 80; server_name <url> www.<url> <ip_address>; location = /favicon.ico {access_log off;log_not_found off;} root /home/ubuntu/<directory>/mysite; location = /static/ { root /home/ubuntu/<directory>/mysite/; } location = /media/ { root /home/ubuntu/<directory>/mysite/; } location = / { include proxy_params; proxy_pass http://unix:/home/ubuntu/<directory>/mysite/mysite.sock; } } For the page that returns properly, I get all the static files (css,img) that are expected. I've looked at the nginx error log and get this: 2018/12/02 20:50:11 [error] 11506#11506: *3 open() "/home/ubuntu/<directory>/mysite/about.html" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: <url>, request: "GET /about.html HTTP/1.1", host: "www.<url>.com", referrer: "http://www.<url>.com/" 2018/12/02 20:55:41 [error] 11577#11577: *2 open() "/home/ubuntu/<directory>/mysite/about.html" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: <url>.com, request: "GET /about.html … -
DjangoREST get object from IntegerField
So I'm doing a little project in Django REST, and I'm still getting used to the ORM. I'm dealing with the following Django model: class Session(models.Model): date = models.DateTimeField(default=now, blank=False) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='efforts', on_delete=models.CASCADE) I'm particularly interested in the number of session each owner has, given a specific month. As follows: Session.objects.filter(date__gte=start, date__lt=end).values('owner').annotate(num_sessions=Count('owner')).order_by("owner") This query produces results of the following structure: (owner, count) In the serializer, I'd like to use the owner to retrieve the user name, as to structure the response. I'm having absolutely no luck in doing so. My serializer looks like this at the moment: class SessionAggregateSerializer(serializers.ModelSerializer): num_sessions = serializers.IntegerField(read_only=True) owner = serializers.IntegerField(read_only=True) class Meta: model = Session fields = ('id', 'owner', 'num_sessions') Anyone any suggestions on how to approach this? For regular queries, I'm using the following line to retrieve the users' name, but this is no longer applicable in the current setting: owner = serializers.ReadOnlyField(source='owner.username') -
Keep instance of files when there's validation error on post
I'm having some problems with the instance of these gallery files and other on my project. When I have validation errors, the files uploaded disappear. In this case I wanted to force the user to input at least 3 images to the gallery, but if he only chose one, and sent the form, after the POST the image will appear there, but if he only fill the rest and press send, it will say that he didn't fill the first one he sent last time, because it was only showing, but didn't send that instance again to the form for some reason... The objective is to keep the images uploaded on memory even if the user press the save button again and again with the errors so that he can only fill the ones remaining. attachments.form.html <div class="form-group"> <div class="col-sm-3 control-label"> <label class="">Gallery</label> <br><br> <small>Add photos to your project</small> </div> <div class="col-sm-9"> <div class="row"> {{ gallery.management_form }} {% for form_gallery in gallery %} <div class="col-lg-10 gallery-formset"> <p class="file-description"> {% if form_gallery.file.value %} {% if gallery.non_form_errors %} <span class="filename"> <a class="text" href="#">{{ form_gallery.post_file_name }}</a> <span class="btn-delete glyphicon glyphicon-remove"></span> </span> {% else %} <img width="150" class="media" src="/media/{{ form_gallery.file.value }}"> {% endif %} … -
Issue with images in Django
Have an issue with images form in Django. Upload of images is working correctly and displayed in admin page also right. But if I want to use this image in my templates or go direct by the link from admin console, receiving 404 error, why? Django : 2.1.1 Python : 3.6.6 models.py from art.settings import STATICFILES_DIRS import os def get_image_path(instance, filename): return os.path.join(STATICFILES_DIRS[0], 'collections', filename) class ArtCollections(models.Model): title = models.CharField(max_length=200) content = models.TextField() class ImagesList(models.Model): collection_id = models.ForeignKey(ArtCollections, on_delete=models.CASCADE, default=1) images = models.ImageField(upload_to=get_image_path, blank=True, null=True) From admin console, uploading the file, and its doing in correct folder, exx /static/image.jpg file is exist : -rw-r--r-- 1 www-data www-data 438930 Dec 2 /static/image.jpg but still getting 404 P.S. on folder give full grants and for apache also -
Django: Why are my static files not showing up and always giving me a 404 error when DEBUG=False?
I am working on my Windows Machine, trying to develop multiple apps for a project called "portal". After working on it, I have set DEBUG=False, and now all my static files are giving me a 404 error after loading any page. When running python manage.py runserver in CMD, I get this when loading a page: [02/Dec/2018 14:10:14] "GET /account/sign-in HTTP/1.1" 200 6249 [02/Dec/2018 14:10:14] "GET /static/fonts/fonts.css HTTP/1.1" 404 96 [02/Dec/2018 14:10:14] "GET /static/css/argon.css HTTP/1.1" 404 94 [02/Dec/2018 14:10:14] "GET /static/branding/logo.png HTTP/1.1" 404 98 I have looked at over 20+ posts about this which were mostly the same and I have followed all of their steps, such as: I have set these in my settings.py file: STATIC_URL = '/static/', STATICFILES_DIRS = ['portal/static/'] (I have a static folder in the folder that holds files like settings.py), and STATIC_ROOT = os.path.join(BASE_DIR, "static") I have called python manage.py collectstatic I have even created a new Django test project and did all these steps above, and they ARE working for that new test project. I have even removed all files in __pycache__ and reset my migrations, and database files. Are there any other possible secure (I have seen others use cheats such as --insecure) solutions …