Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'path' with no arguments not found. 1 pattern(s) tried.
So I have recently started learning Django, after finishing the tutorial I decided to create my own website and have run into an error that I honestly just don't understand. The error is: Error during template rendering In template /home/phil/Projects/mysite/homepage/templates/_partial.html, error at line 13 Reverse for 'bio' with no arguments not found. 1 pattern(s) tried: ['$bio/'] homepage/templates/_partial.html <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="{% url 'home:index' %}">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="{% url 'home:bio' %}">Bio</a> <!--Attention--> <a class="nav-item nav-link disabled" href="{% url 'home:index' %}">Technologies</a> </div> </div> homepage/url.py from django.views import generic class IndexView(generic.ListView) : template_name = 'homepage/index.html' class BioView(generic.ListView) : template_name = 'homepage/bio.html' homepage/urls.py from django.conf.urls import url from . import views app_name = 'home' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^bio/', views.BioView.as_view(), name='bio'), url(r'^skills/', views.SkillsView.as_view(), name='skills'), ] As I said I had followed the Django tutorial and honestly can't see what the error is. Index works as expected, but when I call bio or skills it throws this exception. :( -
Viewing and parsing JSON response - djanog
I have sent a JSON rquest that i have sent. I an getting a 200 response which means that the request that was sent is accepted and that there is a response. I am trying to view the full response that was sent back from the request. I have tried 3-4 different ways of viewing the response, but no matter what i try, i cant figure out how to view the full response... Can anyone help me figure out how to see the information.. Request - def createUserSynapse(): url = 'http://uat-api.synapsefi.com' headers = { 'X-SP-GATEWAY' : 'client_id_asdfeavea561va9685e1gre5ara|client_secret_4651av5sa1edgvawegv1a6we1v5a6s51gv', 'X-SP-USER-IP' : '127.0.0.1', 'X-SP-USER' : 'ge85a41v8e16v1a618gea164g65', 'Contant-Type' : 'application/json', } payload = { "logins":[ { "email":"test@test.com", } ], "phone_numbers":[ "123.456.7890", "test@test.com", ], "legal_names":[ "Test name", ], "extras":{ "supp_id":"asdfe515641e56wg", "cip_tag":12, "is_business":False, } } print(url) print(headers) print(payload) call = requests.post(url, data=json.dumps(payload), headers=headers) print(call) return call The response that i am getting from the request (I have a line to print the request)... <Response [200]> -
Allow user to edit profile information and submit it causing page to redirect to profile page.
In django I am attempting to allow that user to edit his/her profile information, press submit, and have the the change reflect in his/her profile page. This is the code : In the views.py document in my application User is allowed to view the profile page def view_profile(request): var = { 'user' : request.user } return render(request, 'accounts/profile.html', var) User is allowed to edit the profile page def edit_profile(request): if request.method == 'POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('account/profile') else: form = UserChangeForm(instance=request.user) var = {'form' : form } return render(request, 'accounts/edit_profile.html', var) This is the urls.py document Import modules from django.conf.urls import url from . import views Defined the urls urlpatterns = [ url(r'^profile/$', views.view_profile, name = 'view_profile'), url(r'^profile/edit/$', views.edit_profile, name = 'edit_profile') ] This is the edit_profile {% extends 'base.html' %} {% block head %} <title>{{ user }}</title> {% endblock %} {% block body %} <div class = "container"> <form method = "post"> {% csrf_token %} {{ form.as_p }} <button class = "btn btn-default" type="submit">Submit</button> </form> </div> {% endblock %} When I edit user model on the edit_profile.html page and submit, it redirects from : http://127.0.0.1:8000/account/profile/edit/ To : http://127.0.0.1:8000/account/profile/edit/account/profile This latter urls is not accurate, … -
Get average of user input ratings for different model instances (Django)
Ok, so here is the deal. I'm working on this web-app that lets you create users, beers, and reviews for beers. models.py: from django.db import models from django.conf import settings class BeerModel(models.Model): user = models.ForeignKey(User, default=1) name = models.CharField(max_length=254, default="") style = models.CharField(max_length=254, default="") ibu = models.IntegerField(default="") calories = models.IntegerField(default="") abv = models.IntegerField(default="") location = models.CharField(max_length=254, default="") class Meta: verbose_name_plural = 'Beers' def __str__(self): return self.name def avg(self): return class RateModel(models.Model): FIVE_REVIEWS = ( ('5', '5'), ('4', '4'), ('3', '3'), ('2', '2'), ('1', '1'), ) TEN_REVIEWS= ( ('10', '10'), ('9', '9'), ('8', '8'), ('7', '7'), ('6', '6'), ('5', '5'), ('4', '4'), ('3', '3'), ('2', '2'), ('1', '1'), ) user = models.ForeignKey(User, default=1) beer = models.ForeignKey(BeerModel) aroma = models.PositiveIntegerField(max_length=2, choices=FIVE_REVIEWS, default="5") appearance = models.PositiveIntegerField(max_length=2, choices=FIVE_REVIEWS, default="5") taste = models.PositiveIntegerField(max_length=2, choices= TEN_REVIEWS, default= "10") class Meta: verbose_name_plural = 'Ratings' def __str__(self): return str(self.beer) As you can tell, you can create a review for different beers using different users. My goal is to have django output on the HTML, an "Average" value for "Aroma, appearance, and taste" for each beer. This is what I have in my views.py: @login_required def home(request): beers = BeerModel.objects.order_by('name') rates = RateModel.objects.order_by('user') avg = RateModel.objects.aggregate(aroma = Avg('aroma'), appearance … -
If / else in Django View
I'm trying to display a different template depending on a condition: class RouteList(ListView): model = DailyRoute template_name = 'route_list.html' def get_queryset(self): if DailyRoute.objects.filter( stage = '1').exists(): query_set = DailyRoute.objects.filter(owner=employer, stage = '1').order_by('route') else: query_set = [] return query_set If True - go to template 1.html If False - go to template 2.html The above works for template 1.html only. I can't figure out how properly use the if/else statements to return the correct template and query_set for True/False. Feeling like a dope on this one. -
Query on generic display views - Django
For the below url routing for blog app, from django.conf.urls import url, include from django.views.generic import ListView, DetailView from blog.models import Post urlPatterns=[ url(r'^$', ListView.as_view( queryset=Post.objects.all().order_by("-date")[:25], template_name="blog/blog.html", ) ) ] template blog.html is, {% extends "personal/header.html" %} {% block content %} {% for post in object_list %} <h5>{{post.date|date:"Y-m-d"}}<a href="/blog/{{post.id}}"> {{post.title}} </a></h5> {% endfor %} {% endblock %} where model for blog app is defined as, class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __str__(self): return self.title Question: post.id is internally created as primary key, for every row in the table, but, What does /blog/{{post.id}} mean in the template(blog.html)? -
Reverse for 'index' with keyword arguments '{'username': 'garrett', 'pk': 7}' not found
So I know what a reverse is, I just don't understand how the Keyword stuff fits into it. What I am trying to do is enable people to delete only their own posts. The delete button shows up properly on only the users own posts, however when you click "Delete" I'm getting an error, here is the error along with the code. The traceback doesn't highlight anything but if you want to see it or anything else let me know and I can add it. Also haven't been able to find any other questions on this site... Error: NoReverseMatch at /colorsets/delete/7/ Reverse for 'index' with keyword arguments '{'username': 'garrett', 'pk': 7}' not found. 1 pattern(s) tried: ['$'] Colorsets App views.py from django.shortcuts import render from colorsets.forms import ColorForm from colorsets import models from colorsets.models import ColorSet from django.utils import timezone from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse,reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from braces.views import SelectRelatedMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here. #def index(request): # return render(request,'index.html') class PostListView(ListView): model = ColorSet def get_queryset(self): return ColorSet.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class CreateColorSetView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'index.html' form_class = … -
How do I filter data using .date() keyword in the column name in django?
I am writing a web application using Django where I have to use date() in column name. The orignal field is datetimefield and i need filter using date only and ignore the time. Here is my code: datas = Data.objects.all() for data in datas: all = Data.objects.filter(datetime.date() = data.datetime.date()) But it gives out the following error: all = Data.objects.filter(datetime.date() = consumption.datetime.date()) SyntaxError: keyword can't be an expression Any idea how I use datetime.date() as a column name to use only date section of the datetimefield column? UPDATE Here is my model: class Data(models.Model): datetime = models.DateTimeField(auto_now=False) value = models.FloatField() -
How to call javascript function with input type "submit" in django
html file <div class="container"> <div class="row"> <div class="col-6"> <form method='POST' class='my-form' action=''>{% csrf_token %} <br/> <br/> <br/> {{ form|crispy }} <br/> <br/> <!-- <input type="button" class="btn btn-primary" value="Get Route" onclick="GetRoute()"/> --> <input type="submit" class="btn btn-primary" value="Get Route" onclick="GetRoute()"/> </form> </div> </div> <table border="0" cellpadding="0" cellspacing="3"> <tr> <td colspan="2"> <div id="dvDistance"> </div> </td> </tr> </table> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script> <script type="text/javascript"> var source, destination; var directionsService = new google.maps.DirectionsService(); google.maps.event.addDomListener(window, 'load', function () { new google.maps.places.SearchBox(document.getElementById('txtSource')); new google.maps.places.SearchBox(document.getElementById('txtDestination')); }); function GetRoute() { var mumbai = new google.maps.LatLng(18.9750, 72.8258); var mapOptions = { zoom: 20, center: mumbai }; //*********DIRECTIONS AND ROUTE**********************// source = document.getElementById("txtSource").value; destination = document.getElementById("txtDestination").value; var request = { origin: source, destination: destination, travelMode: google.maps.TravelMode.DRIVING }; //*********DISTANCE AND DURATION**********************// var service = new google.maps.DistanceMatrixService(); service.getDistanceMatrix({ origins: [source], destinations: [destination], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERIAL, avoidHighways: false, avoidTolls: false }, function (response, status) { if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") { var distance = response.rows[0].elements[0].distance.text; var uzaklyk = parseInt(distance) cikdayci = ' ' if (uzaklyk <= 100) { cikdayci = 250; } else if (uzaklyk <= 200) { cikdayci = 340; } else if (uzaklyk <= 300) { cikdayci = 430; } else if (uzaklyk <= 400) { cikdayci = 520; … -
How to delete a model instance and modify the user profile when another model instance is created django?
I'm trying to do an website where you can see differents match and vote for the team you think that will win. And I'm at the point when the match ends I'd would like to simply create an instance in the django admin with the match and the winner of the match and then delete all the votes and adding some points for every user that has the good vote. So there are my models : class Prognostic(models.Model): match = models.IntegerField() user = models.IntegerField() vote = models.CharField(max_length = 100) def __str__(self): return self.vote class MatchResult(models.Model): match = models.ForeignKey("MatchOpponents") winner = models.ForeignKey("TeamGGC") @receiver(post_save, sender=Prognostic) def voteRepartitionPoints(sender, instance, **kwargs): profil = apps.get_model("userMembers", "Profil") for prognostic in Prognostic().object.filter(match = match_id): if prognostic.vote == winner: user = profil.object.get(user_id = prog.user) user.nbGGCPoints += 50 user.save() prognostic.delete() def __int__(self): return self.match But when I do that, nothing happends, someone has a idea what i do wrong or what i should look for? Thanks! -
Python tornado Too many open files Ssl
If i have many connection on my tornado server, i se error on log Exception in callback (<socket._socketobject object at 0x7f0b9053e3d0>, <function null_wrapper at 0x7f0b9054c140>) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 888, in start handler_func(fd_obj, events) File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 276, in accept_handler callback(connection, address) File "/usr/local/lib/python2.7/dist-packages/tornado/tcpserver.py", line 264, in _handle_connection File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 517, in ssl_wrap_socket context = ssl_options_to_context(ssl_options) File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 494, in ssl_options_to_context context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None)) IOError: [Errno 24] Too many open files and disconnect my client. Tornado open ssl certificate file on ewery connect? Tornado app class VastWebSocket(tornado.websocket.WebSocketHandler): connections = set() current_connect = 0 current_user = 0 status_play_vast = False def open(self): c = Connection() c.connection = self VastWebSocket.connections.add(c) self.current_connect = c def on_message(self, msg): data = json.loads(msg) app_log.info("on message = " + msg) if not 'status' in data: return if data["status"] == "start_vast": VastWebSocket.status_play_vast = True if data["status"] == "end_vast": VastWebSocket.status_play_vast = False app_log.info("status_play_vast = " + str(VastWebSocket.status_play_vast)) if data["status"] == "get_status_vast": self.current_connect.connection.write_message({"status": VastWebSocket.status_play_vast}) return for conn in self.connections: conn.connection.write_message(msg) def on_close(self): if self.current_connect <> 0: VastWebSocket.connections.remove(self.current_connect) def check_origin(self, origin): return True Start tornado server from django command class Command(BaseCommand): help = 'Starts the Tornado … -
OperationalError at /admin/Survey/intro/add/
I was writing a simple admin form, but the error of no such table keeps showing up even though I have done the makemigration and migrate many times it shows no updates. Traceback: File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute 65. return self.cursor.execute(sql, params) File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (no such table: Survey_intro) was the direct cause of the following exception: File "C:\Python34\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Python34\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\contrib\admin\sites.py" in inner 224. return view(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in add_view 1508. return self.changeform_view(request, None, form_url, extra_context) File "C:\Python34\lib\site-packages\django\utils\decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "C:\Python34\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\utils\decorators.py" in bound_func 63. return func.get(self, type(self))(*args2, **kwargs2) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in changeform_view 1408. return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in _changeform_view 1448. self.save_model(request, new_object, form, not add) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in save_model 979. obj.save() File "C:\Python34\lib\site-packages\django\db\models\base.py" in save 806. force_update=force_update, update_fields=update_fields) File … -
How to scan image from scanner and perform ocr on that image using python's django web framework?
I want to build a website through which I can scan image from the scanner and perform OCR on it. I had searched a lot on the net and found some paid API from Asprise's Scanner.js and Dynamsoft's Dynamic Web Twain. But I don't want to use any paid API. I also found some links: How Can I Trigger a Scanner from a Browser? TWAIN Browser Plugin But it is of no help. Please help me to solve this problem. -
Upload files dynamically into different s3 buckets with django-storages boto3
I'm using django-storages to upload into an s3 bucket. But I want to be able to upload into a different s3 bucket than what I have set in my default in settings.py My app has a different web page for each bucket and can access the contents. Ideally I would want to pull the bucket name from the url and dynamically set the bucket name to where the file is being uploaded in my code. -
Django not showing updated data from database
I have a django 1.11.4 application running on mysql 5.6.16 on windows. When I add new data or update existing data, the new information does not show up until after I restart. I have tried providing the db_name as suggested here but it has not solved my case. How else can I resolve this? I am using the default web server that comes with django. My complete model is as shown below class Member(AbstractUser): first_name = models.CharField(verbose_name=_('First Name'), blank=False, max_length=100) last_name = models.CharField(verbose_name=_('Last Name'), blank=False, max_length=100) member_number = models.IntegerField(blank=False, unique=True) national_id = models.IntegerField(verbose_name=_('National ID Number'), blank=False, unique=True) phone_number = models.CharField(max_length=50, verbose_name=_('Phone Number')) email = models.EmailField(verbose_name=_('Email'), unique=True, max_length=100, blank=False) username = models.CharField(verbose_name=_('User name'), max_length=50, blank=True, null=True) position = models.CharField(verbose_name=_('Position in Society'), max_length=100, choices=( ('MEMBER', 'Member'), ('COMMITTEE', 'Committee'), ('STAFF', 'Staff'), )) employer = models.CharField(verbose_name=_('Employer'), max_length=250, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['member_number', 'national_id', 'first_name', 'last_name'] class Meta: verbose_name = _('member') verbose_name_plural = _('members') db_table = 'members_member' def get_short_name(self): return self.last_name def __str__(self): return self.get_full_name() My database connection settings are shown below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'open_db', 'USER': 'root', 'PASSWORD': 'rootpass', 'HOST': 'localhost', 'PORT': '3306', } } -
Python: assert if string matches a format
I have some unit tests for my Django API using Django Rest Framework APIClient. Different endpoints of the API return custom error messages, some with formatted strings like: 'Geometry type "{}" is not supported'. I'm asserting the status code from the client responses and error message keys, but there are cases that I'd like to figure what error message is returned to make sure nothing else has caused that error. So I'd like to validate the returned error message against the original unformatted string too. For example if I receive an error message like 'Geometry type "Point" is not supported', I'd like to check if it matches the original unformatted message, i.e. 'Geometry type "{}" is not supported'. The solutions I've thought of so far: First: replacing the brackets in the original string with a regex pattern and see if it matches the response. Second: (the cool idea, but might fail in some cases) using difflib.SequenceMatcher and test if the similarity ratio is bigger than, for example, 90%. So my question is what the other ways of doing such comparison are and whether there is any built-in feature in Python to achieve this. -
Django Multi join query
I am new to django and need to do a query. I can do in sql but I can't seem to figure it out in django. Here it is in SQL. Can someone tell me how to do it in django. select token from api_userprofile join api_userdevice on api_userdevice.user_id=api_userprofile.user_id join api_device on api_device.id=api_userdevice.device_id where api_device.serial=3 My models look like this: class UserDevice(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False) device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False) activation_date = models.DateTimeField(default=timezone.now, null=False) friendly_name = models.CharField(max_length=20, null=True, blank=True) is_owner = models.BooleanField(null=False, default=False) is_admin = models.BooleanField(null=False, default=True) class Device(models.Model): serial = models.CharField(max_length=16, null=False, unique=True) publickey = models.CharField(max_length=44, null=False) class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, null=False) token = models.TextField(null=False, blank=True) -
Django makemigration keeps recreating the same migration
I'm using Django 1.9 and I have on model that keeps generating a migration when makemigrations is called even when no change has occured. Here's two examples of two subsequent migration files: Here's 0005_auto_20170830_1841.py: # -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2017-08-30 18:41 from __future__ import unicode_literals from django.db import migrations, models import django.utils.translation class Migration(migrations.Migration): dependencies = [ ('account', '0004_auto_20170830_1801'), ] operations = [ migrations.AlterField( model_name='accounttype', name='description', field=models.TextField(verbose_name=django.utils.translation.ugettext), ), ] And here's 0006_auto_20170830_1846.py which references the previous one: # -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2017-08-30 18:46 from __future__ import unicode_literals from django.db import migrations, models import django.utils.translation class Migration(migrations.Migration): dependencies = [ ('account', '0005_auto_20170830_1841'), ] operations = [ migrations.AlterField( model_name='accounttype', name='description', field=models.TextField(verbose_name=django.utils.translation.ugettext), ), ] What could be causing this behavior? It only happens for this one model. -
Django Rest Framework -- simple GET request hits database multiple times?
Using the Django Rest Framework, I have a simple GET request that I know should only result in 16 records being returned. The GET request isn't filtered at all -- just a simple api/contacts/ and it should return 16 contacts. I am getting my 16 records as expected, but I also see that the database is being queried 12 times!? In my Contact record I do have one field that is a Foreign Key, and not each Contact has this Foreign Key set. So my guess is that I have a case of Django's "lazy querying" going on. Is that right? Is there a way to optimize this? If I have, say, 300 Contact records, I don't want to be hitting the database 500+ times. Can't I just make a single query to the DB and not do all these round trips? -
Django Rest-framework with iOS and android
I would be needing insight from everyone who is willing to support. I have a django web application and I have used the django rest framework to create the REST API and now I want to proceed to mobile development (iOS and android). The Question now is how do I use the REST API created to build an iOS or Android application because I am looking to build a native application. Any one can join the discussion. every tip is appreciated -
Why {% load staticfiles %} required in head tag?
In the below head tag, <head> ..... {% load staticfiles %} <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/> <script src="{% static 'personal/js/myscripts.js' %}"></script> ...... </head> Does link & script tag not suffice to load css styling & JS in DOM? Do we need {% load staticfiles %}? -
Python-Django Static files not being found
My settings: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/'), ) STATIC_URL = '/static/' My urls: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index), url(r'^blog/view/(?P<slug>[^\.]+)', view_post), url(r'^blog/category/(?P<slug>[^\.]+)', view_category), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My directory: website blog website __init__.py settings.py urls.py wsgi.py static css js images templates db.sqlite3 manage.py My HTML: <script src="{% static 'js/html5shiv.min.js' %}"></script> <script src="{% static 'js/respond.min.js' %}"></script> I have been struggling bringing in my static files into my Django project for hours. Now, I believe I brought them in correctly but my webpage still gets a 404 error claiming they are not found. When I go to the localhost link that my js, or css file should be in I get the error: "A server error occurred. Please contact the administrator." I set up my URL as said in the documentation https://docs.djangoproject.com/en/1.11/howto/static-files/ So I am very confused on where to go from here on out. Any help would go a long way. Thanks -
How can I display PostgreSQL database in Docker container?
I have both Django project and PotgreSQL database in Docker container. My question is how can I display my database? I was trying docker exec -ti myproject_django_1 /bin/bash and docker exec -ti myproject_db_1 /bin/bash but in both cases I can't use psql because of psql: FATAL: role "root" does not exist or bash: psql: command not found -
Django WebSocket is closed before the connection is established with wss://
Been making progress on learning Django Channels, and proxying traffic through Apache. Been using tutorial here: https://github.com/jacobian/channels-example So far, I have been successful at completing tutorial. Even provided some assistance to another question on this site: Websocket disconnects immediately after connecting (repeatedly) The problem that I have is that while I am able to proxy the traffic for http over Apache, I am unable to do the same thing with https. WebSocket connection to 'wss://example.com:8001/chat/dark-fog-0991/' failed: WebSocket is closed before the connection is established. This is the same errror I received prior to adding message.reply_channel.send({'accept':True} Adding that line fixed it for requests to ws://example.com:8001/chat/dark-fog-0991/ But, the error occurs on: wss://example.com:8001/chat/dark-fog-0991/ apache.conf <VirtualHost *:80> Servername example.com SuexecUserGroup "#1001" "#1001" ProxyPass "/chat.*" "ws://127.0.0.1:8001/" ProxyPassReverse "/chat.*" "ws://127.0.0.1:8001/" ProxyPass "/" "http://127.0.0.1:8001/" ProxyPassReverse "/" "http://127.0.0.1:8001/" </VirtualHost> <VirtualHost *:443> Servername example.com SuexecUserGroup "#1001" "#1001" ProxyPass "/chat.*" "ws://127.0.0.1:8001/" ProxyPassReverse "/chat.*" "ws://127.0.0.1:8001/" ProxyPass "/" "http://127.0.0.1:8001/" ProxyPassReverse "/" "http://127.0.0.1:8001/" SSLEngine on SSLProxyEngine on SSLCertificateFile /home/example/domains/example.com/ssl.cert SSLCertificateKeyFile /home/example/domains/example.com/ssl.key SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 </VirtualHost> I tried changing ProxyPass "/chat.*" "ws://127.0.0.1:8001/" to ProxyPass "/chat.*" "wss://127.0.0.1:8001/" Still doesn't work. Do I need to be doing anything different with my daphne interface? -
Using multiple models on user creation
I'm looking to use an Account model I created to handle financial data about a user. How do I ensure django-allauth will create this model when registering users and will link through keys both the new user and the Account model?