Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: docs not found
Django 2.0.1 DRF 3.7.7 I am using automatically generated documentation provided by DRF. My urls.py: from rest_framework.documentation import include_docs_urls urlpatterns = [ ... path('docs/', include_docs_urls(title='My API')), ... ] This used to work just fine in the past, but recently it stopped working (I don't know why). When I try to access the docs at http://localhost:8000/docs/, it gives me the DRF 404 error: Error {'detail': 'Not found.'} Additional Information Note: You are seeing this message because DEBUG==True. Seeing this page is usually a configuration error: are your DEFAULT_AUTHENTICATION_CLASSES or DEFAULT_PERMISSION_CLASSES being applied unexpectedly? Your response status code is: 404 401 Unauthorised. Do you have SessionAuthentication enabled? Are you logged in? 403 Forbidden. Do you have sufficient permissions to access this view? Is you schema non-empty? (An empty schema will lead to a permission denied error being raised.) Most commonly the intended solution is to disable authentication and permissions when including the docs urls: url(r'^docs/', include_docs_urls(title='Your API', authentication_classes=[], permission_classes=[])), Overriding this template If you wish access to your docs to be authenticated you may override this template at rest_framework/docs/error.html. The available context is: data the error dict above, request, response and the debug flag. This is very strange. I have no idea … -
How do I put a task on hold/defer in Celery until a condition has been met?
I need help with celery. I'm creating a web service to send vouchers which are in three categories thirty,fifty and hundred. Each of these vouchers are stored in their own models. The payment gateway sends an Instant Payment Notification to my website which I then process and filter the amount and phone number from the JSON. The logic I would like to implement is if the amount == 30, An unused voucher(boolean) is picked from model thirty and sent via an SMS gateway to the phone number from the Payment Notification. The same case for 50 and 100. I would like the SMS sending function be done with celery. Now here is my biggest challenge, if the amount is not equal to any of those three values, the task is put on hold until one of the conditions is satisfied and the sender receives a notification of insufficient amount via the SMS gateway. Can you help with that? -
Django Serializers related models POST from angular 4 in single JSON
My requirement - I have two models TravelReq and TravelReqDetails as below class TravelReq(models.Model): empid= models.CharField(max_length=7) startdate= models.DateField() enddate= models.DateField() remarks= models.CharField(max_length=30) missionname= models.CharField(max_length=30) def __str__(self): return str(self.id) class TravelReqDetails(models.Model): travelReqID = models.ForeignKey(TravelReq ,related_name = 'req_details' , on_delete=models.CASCADE ); travelDate= models.DateField() lfrom = models.CharField(max_length=30) to= models.CharField(max_length=30) remarks = models.CharField(max_length=30) def __str__(self): return str(self.id) My serailizer from .models import TravelReq ,TravelReqDetails from rest_framework import serializers class TravelReqSerializer(serializers.ModelSerializer): class Meta: model = TravelReq fields = ('empid' , 'startdate' , 'enddate' , 'remarks' , 'missionname' ,'req_details')code here My view from .models import TravelReq from rest_framework import viewsets from .serializers import TravelReqSerializer class TravelReqViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = TravelReq.objects.all() serializer_class = TravelReqSerializer From Angular I will be receiving below JSON as POST / PUT request . What is the best way to insert the master(TravelReq) and child records (TravelReqDetails) from a single serializer. please advice. If this is not the best approach ,please suggest a better / standard approach [ { "empid": "32432", "startdate": "2017-11-16", "enddate": "2018-03-17", "remarks": "asd", "missionname": "asd", "req_details": [ { "id": 1, "travelDate": "2017-07-18", "lfrom": "indiaemarks", "to": "pakistan", "remarks": "r", "travelReqID": <<need to get from parent travel request>> }, { … -
Check and clear filters with django-filter
I am using django-filter to filter a ListView and would like to display a "Clear all filters" link if any filters are applied. Due to the generic nature of the filtering system I haven't yet found a straightforward way to achieve this. The only thing I came up with so far is to return the regular queryset in the get_queryset method of the view if a "clear" flag is present in the request, however this doesn't actually clear the filters - it just returns all the data. Does anyone have a solution/idea for this? -
Django error 500 when Debug=False - allowed hosts set to *. nothing in console
when im setting Django to Debug=False, I am getting an error 500 when running via gunicorn or via manage.py. when running via manage I do not get any errors in console. my settings file has the allowed hosts set to ['*']. As soon as I change Debug=True everything works again. where would I get the output of the 500 if not from the console when running manage.py? here is my settings file: ''' Django settings for itapp project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ ''' # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import ldap BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = *********** # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'home.apps.HomeConfig', 'oncall.apps.OncallConfig', 'tools.apps.ToolsConfig', 'sites.apps.SitesConfig', 'maintenance.apps.MaintenanceConfig', 'service.apps.ServiceConfig', 'monitoring.apps.MonitoringConfig', 'mgmt.apps.MgmtConfig', 'config.apps.ConfigConfig', 'circuits.apps.CircuitsConfig', 'storages', 'imagekit', 'django_celery_results', 'debug_toolbar', 'simple_history', 'crispy_forms', ) MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', ] ROOT_URLCONF … -
maximum recustion depth exceeded requests
Currently new to python/django so forgive me if this is a simple question. I am using requests to download a json file and am trying to parse/display the values in a template. I receive the following error: maximum recursion depth exceeded while calling a Python object Code is below: def get_pinterest_pins(): req = requests.get(URL) req_json = json.loads(req.content)` for key, value in req_json.items(): print (key, value) This loops through the URL ok but continously until a point that it times out. -
is an open cassandra cqlsh cluster/session in python usable for making other queries?
I'm new on apache cassandra. im using a django program that needs to work with cassandra and im using cassandra-driver as it's recommended on documentations. when i use this code it creates a connection session to cassandra named "default". from cassandra.cqlengine import connection connection.setup([settings.CASSANDRA_SERVER], default_keyspace=settings.CASSANDRA_KEYSPACE) i wanted to get sure if it's ok to use this session as long as it's open or not? in my test i wrote a function that checks if session is closed then creates another session. def checkConnection(): try: connection.get_connection("default") except: connection.setup([settings.CASSANDRA_SERVER], default_keyspace=settings.CASSANDRA_KEYSPACE) i use this functoin before making cqlengine queries. is it rational for production or not? -
Could not find a version that satisfies the requirement for all the packages
I have recently configured python3 for other application and running on the same machine where python 2.7 was running.. I see python3 applications are working fine with command python -m pip install package-name and python3 manage.py runserver command But I am facing trouble with my existing application and new application with following issue while installing package You are using pip version 7.1.0, however version 9.0.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command. Collecting django-allauth==0.27.0 Could not find a version that satisfies the requirement django-allauth==0.27.0 (from versions: ) No matching distribution found for django-allauth==0.27.0 This is the command I used, pip install django-allauth==0.27.0 Anybody know how to resolve it? -
Unable to migrate aldryn in my pc
please help regrading this issue and below in mention what kind error i getting (env) PS C:\Users\ZeroZilla\Desktop\zdc> ./manage.py migrate Traceback (most recent call last): File "C:\Users\ZeroZilla\Desktop\zdc\manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\ZeroZilla\Desktop\env\lib\site-packages\django\core\management_init_.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\ZeroZilla\Desktop\env\lib\site-packages\django\core\management_init_.py", line 338, in execute django.setup() File "C:\Users\ZeroZilla\Desktop\env\lib\site-packages\django_init_.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ZeroZilla\Desktop\env\lib\site-packages\django\apps\registry.py", line 89, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: djangocms_text_ckeditor (env) PS C:\Users\ZeroZilla\Desktop\zdc> i 'm unable to access aldryn plagins -
Optimal way to chain reverse foreign key lookups in Django
We have a DB model that looks something like this, where each arrow represents a many to one relationship in the direction of the arrow: A --> B --> C --> D < -- E For most models, we have a property called D. For C, that method returns D. For B, that method calls C.D() and so on. These we can use for FK lookup. The problem arises for reverse lookups, since these chained properties are unavailable when generating SQL statements, meaning we would have to load the entire QuerySet into memory to filter on those properties. Ideally, we could do something like A.objects.filter(D=someD). What we instead do is lookup based on relations and chain a bunch of joins. The syntax is nice for one join, but it quickly becomes hard to maintain. If we want to get all A objects related (indirectly) to D, we have to doA.objects.filter(B__C__D=someD). Having to write code like this in multiple places is obviously not ideal. We have looked into F annotations and a custom manager for each model without much luck. TLDR: What's the optimal way to chain reverse lookups? Thanks in advance! -
How to reassign object id's in Django?
I am developing a Polling application in which i had created bunch of questions and their respective options , one has to choose and vote for the question. In the process i had deleted few questions in between , now the ID's of the questions are missing in between. For example When i created Questions Q1,Q2,Q3..etc they had ID's 1 , 2 , 3 etc but then i deleted few of the questions in between, Now i am facing a problem while traversing the questions as the ID's are not in the sequence ! is there a way to fix it ? or reassign the ID's as per my choice? -
Django Form Does Not Find Right ID int Increment on Production vs LH
For some reason on Localhost (LH) everything works fine but on my Production server, my form does not add a new user submission properly. The error I am getting is: duplicate key value violates unique constraint "..." DETAIL: Key (id)=(8) already exists. Is there some sort of production "sudo systemctl restart gunicorn" I need to run (I have already tried the example above)? Maybe it's only working on LH because there I have tested there more and the increment naturally fell on the same level as the total amount of users? I really am out of ideas here. models.py class Lead(models.Model): username = models.CharField(max_length=15, blank=True, null=True) email = models.CharField(unique=True, max_length=150, validators=[validate_email]) created = models.DateTimeField(auto_now_add=True) ... forms.py class LeadCaptureForm1(forms.ModelForm): birth_date = forms.DateField(widget=SelectDateWidget(years=range(1999, 1910, -1))) class Meta: model = Lead widgets = { 'email': forms.TextInput(attrs={'class': 'form-control'}), } fields = ('email', 'birth_date',) views.py def iframe1(request): ip = get_real_ip(request) created = timezone.now() if request.method == 'POST': form = LeadCaptureForm1(request.POST) if form.is_valid(): # Save lead lead = form.save() lead.id = Lead.objects.get(all).count() print(lead.id) lead.created = created lead.birth_date = form.cleaned_data.get('birth_date') lead.ipaddress = get_real_ip(request) lead.joinmethod = "Iframe1" lead.save() print(lead) -
Django - Populating data from database in a dropdown select tag
I've been trying to create an edit option in the frontend for the users to be able to change different settings. At the moment I am bit stuck with the dropdown showing the options that are already saved in the database. I don't know what I'm missing, I hope you can help me out. -- This is what I have in my models.py STATUS_CHOICES = ( ('4', 'Interview'), ('5', 'Rejected'), ('2', 'Following'), ) class StatusType(models.Model): status = models.CharField(max_length=90, choices=STATUS_CHOICES) def __str__(self): return self.status class JobStatus(models.Model): job_application = models.ForeignKey(JobApplication, on_delete=models.CASCADE) def __str__(self): return self.status_type.status -- This is what I have in my index.html {% with object.jobstatus_set.all|first as status %} <form action='' method="post"> <select class="dropdown" type="dropdown" name='job_status'> <option value={{ status }}> {{status}} </option> </select> </form> {% endwith %} Right now it works if I login into the database and assign the value for the job, otherwise the dropdown menu is empty. What I want is to be able to see all the options when clicking on the select menu, so that the users set it to their own choice and then save it. Thank you, any help is very much appreciated. -
Distinct command in django
what will be the ORM queries for the following situation: Count of child accounts(account_child_id) Count the number of accounts won(stage=Won). Count the number of distinct accounts with potential=’HP’ Count the number of distinct accounts with pipeline=’HP’ -
Django admin - edit user, 'str' object has no attribute 'date' builtin user model
ive just gone onto edit a user in django admin and have been hit with the error 'str' object has no attribute 'date'. As this is Django code in the built in user model im not sure where or what I need to rectify here. I have migrated from a sqlite DB to a MySQL DB so im thinking it might be something there but Im not sure what field its referring to this is the traceback Environment: Request Method: GET Request URL: http://0.0.0.0:8000/admin/auth/user/1/change/ Django Version: 1.11.9 Python Version: 3.5.2 Installed Applications: ('home.apps.HomeConfig', 'oncall.apps.OncallConfig', 'tools.apps.ToolsConfig', 'sites.apps.SitesConfig', 'maintenance.apps.MaintenanceConfig', 'service.apps.ServiceConfig', 'monitoring.apps.MonitoringConfig', 'mgmt.apps.MgmtConfig', 'config.apps.ConfigConfig', 'circuits.apps.CircuitsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'storages', 'imagekit', 'django_celery_results', 'debug_toolbar', 'simple_history', 'crispy_forms') Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'simple_history.middleware.HistoryRequestMiddleware'] Template error: In template /home/ubuntu/.local/lib/python3.5/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 'str' object has no attribute 'date' 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 … -
Django filter multiple fields with same choices
I have a model that looks like this: field_1 = models.IntegerField(choices=FIELD_CHOICES, blank=True, null=True) field_2 = models.IntegerField(choices=FIELD_CHOICES, blank=True, null=True) I would like to create a filter with django_filters, to combine these 2 separate fields into 1 single ChoiceFilter. How can I do that? -
Ajax call time to load in django application
I am developing a django app using the Django Rest Framework with chart.JS in order to render some chart. My ajax call is taking a long long long time and I am on local.. Is there a way to check what is taking so long in order to know where to look in order to refactor ? it takes on average on local between 10 and 15 second each time.. Here is my code for example: <script> var endpoint = 'api/chart/data2' $('.ajaxProgress').show(); $('.dashboard-container').hide(); function getAvg(grades) { return grades.reduce(function (p, c) { return p + c; }) / grades.length; } $.ajax({ method: "GET", url: endpoint, success: function(data){ console.log(data) complete_data = data.team_complete, info_data = data.team_info_score, motiv_data = data.team_motiv_score, action_data = data.team_action_score, behaviour_data = data.team_behaviour_score, user_list = data.users, user_dist = data.user_dist, info_dist = data.info_dist, motiv_dist = data.motiv_dist, action_dist = data.action_dist, behav_dist = data.behav_dist, info_label = data.info_label, motivation_label = data.motivation_label, action_label = data.action_label, behav_label = data.behav_label, complete_label = data.complete_label, cohesiveness_score = data.cohesiveness_score var bar_color = [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 220, 89, 0.2)', 'rgba(255, 192, 35, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, … -
Whether there is a way to encode the request url?
Whether there is a way to encode the request url? Such as, I can use the url to request the Django/Django-Rest-Framework provides image: https://localhost:8000/images/icon.png whether I can use a Middleware or whatever to encode the url? because if the icon.png is a 你好.png, I want to encode the url to utf-8. Whether this is feasible? -
Passing CSRF Token/Authenticating a POST request to Django-Rest-Framework from a React Form
I'm trying to post data from a form built in React over a Django-Rest-Framework API and have run into an issue with the authentication. I can post fine if I turn off authentication on the API View, so I think I've narrowed it down to how I'm passing the data in the form. My DRF view looks like this: class PropertyListCreate(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication,) permission_classes = (IsAuthenticated,) queryset = models.Property.objects.all() serializer_class = serializers.PropertySerializer The handler for the Submit is below. handleSubmit = e => { e.preventDefault(); const { name, type, address, city, state, zip_code } = this.state; const property = { name, type, address, city, state, zip_code }; const conf = { credentials: 'include', method: 'POST', body: JSON.stringify(property), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': cookie.load('csrftoken') } }; fetch(this.props.endpoint, conf).then(response => console.log(response), console.log(conf) ); }; When I attempt to post with the above code, I get a 400 Error - and if I remove the 'X-CSRFToken': cookie.load('csrftoken'), I get a 403 Error (Forbidden). My understanding of a 400 Error is that the request was badly formatted, so I'm thinking that I'm sending the csrf token incorrectly? This is the output from console.log(response): Response {type: "basic", url: "http://127.0.0.1:8000/api/properties/", redirected: false, status: … -
Automatically save a foreign key in Django admin;
I have 2 models A and B; When a B instance is created in django Admin, I want the foreign key to be automatically added. In the examples below I try to use a custom form, but I tried also to use the save in the model, but there a ValidationError is not raised I have the following code: in models: class A(models.model): content = models.TextField() Class B(models.model): a = models.ForeignKey(A, related_name='bs', on_delete=models.CASCADE) content = models.TextField() in form: class AdminBModelForm(forms.ModelForm): class Meta: model = B fields = ['content'] def save(self, commit=True): obj = super().save(commit=False) obj.a_id = A.objects.first() if obj.a_id is None: raise ValidationError('You first need to set A') obj.save() return obj in admin: class BAdmin(admin.ModelAdmin): model = B form = AdminBModelForm The error: IntegrityError - null value in column "_id" violates not-null constraint -
Getting error when trying to run server having django -channels
I am trying to use django-channels in my django-project and getting this error while trying to run the server. I am following this tutorial to build chatting application. https://gearheart.io/blog/creating-a-chat-with-django-channels/ Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fb7aa2b1e18> Traceback (most recent call last): File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/channels/apps.py", line 6, in <module> import daphne.server # noqa File "/home/praneet/pral/jagrit/newenv/lib/python3.4/site-packages/daphne/server.py", line 192 async def handle_reply(self, protocol, message): ^ SyntaxError: invalid syntax -
django get unexpected keyword argument
I tried get id from my basedate and make something like article/1 1 is my id my article but it didnot work views.py def article(request, article_id): return render_to_response('article.html', {{'article': Articles.objects.get(id=article_id)}}) my urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('showall/', views.articles, name='articles'), path('<int:article_id>/', views.articles, name='article'), ] and i get TypeError at /article/1/ articles() got an unexpected keyword argument 'article_id' I also include image of my datebase Datebase Thx -
Django with bootstrap4 and modal
Currently I am researching a project that has a form where some users can add their thoughts and other users can comment (the comments are divided in categories by user group in Django). I am facing a problem with not receiving the pk of the template and the django.urls.exceptions.NoReverseMatch: Reverse for 'user3_comment' with no arguments not found. 1 pattern(s) tried: ['posts/comments/user3/( ?P\d+)/$']. My model is like this: models.py class Post(models.Model): post_title = models.CharField(max_length=200) author = models.ForeignKey('auth.User', on_delete=models.PROTECT) post_date = models.DateField(blank=True, null=True) post_time = models.TimeField(blank=True, null=True) post_text = models.TextField() def __str__(self): return self.post_title class User3_comment(models.Model): commented_post = models.ForeignKey(Post, on_delete=models.PROTECT, blank=True, null=True, related_name='user3_comment') comment = models.TextField(blank=True) (some lines skipped) forms.py class User3_comment_form(forms.Form): class Meta: model = User3_comment fields = ['comment','commented_post'] views.py def user3_comment(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = User3_comment_form(request.POST) if form.is_valid(): instance = form.save(commit=False) notikums.commented_post = post return redirect('post_detail', pk=post.pk) else: form = User3_comment_form() return render(request, 'myapp/user3_comment.html', {'form': form}) urls.py url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), url(r'^post/comments/user3/(?P<pk>\d+)/$', views.user3_comment, name='user3_comment') post_detail.html The post detail has a button: {% if request.user|is_authorized:"user3" %} <div class="modal fade" id="modal"></div> <button type="button" class="btn btn-primary open-modal" data-toggle="modal" data-target="#modal">Add user3 comment</button> {% endif %} as well as modal code: <script> $('#modal').on('show.bs.modal', function (event) { var modal = … -
django heroku when debug is false and allowed host is set i get still a 500 page - how i have to set my settings that i come to my Startpage
i load a new app to heroku and then i made a customer domain www.buchfink.de. if i let in my settings.py the DEBUG on TRUE everything work fine, but in production thats not so good. if debug is flase and i set the ALLOWED_HOSTS = ['www.buchfink.de'] but i get then a 500 page. Why? (see in my code) So how i have to change my settings.py or heroku that the page work. Thank you for your help! import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['www.buchfink.de'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Website', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'gettingstarted.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'gettingstarted.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Cant get environ variables on settings file after set them on WSGI
I use django 1.11 and this is my wsgi.py file # -*- coding: utf-8 -*- import os import sys from django.core.wsgi import get_wsgi_application PATH = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)))) if PATH not in sys.path: sys.path.append(PATH) os.environ['DJANGO_SETTINGS_MODULE'] = 'cms.settings.qa' ENV_VARIABLES_TO_PASS = ['VAR_1', 'VAR_2'] _application = get_wsgi_application() def application(environ, start_response): # pass the WSGI environment variables on thzrough to os.environ for var in ENV_VARIABLES_TO_PASS: os.environ[var] = environ.get(var, '1') return _application(environ, start_response) and when i try to get the env on settings file its allways return None. os.getenv('VAR_1') = None & os.getenv('VAR_2') = None why is that happend? thanks a lot.