Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: pass JSON dictionary to javascript file without automatic substitution HTML of symbol code
myvar is the context variable that I pass from my views.py to the template and that I want to pass also to my javascript file. view.py: def View(request): # .... return render(request, 'myapp/template.html', 'myvar': json.dumps(serializer.data)) template.html: ... <script src="{% static 'myapp/file.js' %}">var foo="{{ myvar }}</script> ... As you can see, myvar is a JSON dictionary and in order to pass it to a .js file I assign it to foo When in my .js file I try to parse it, I get the following error: VM173:1 Uncaught SyntaxError: Unexpected token & in JSON at position 2 at JSON.parse (<anonymous>) This is file.js: $(document).ready(function () { var context = JSON.parse(foo); }); I've tried to log foo before doing parsing and it prints &quot; instead of the symbol " This is the reason why parsing operatorion fails, but I don't know why in the JSON dictionary it isn't " but there is &quot; -
CORS error when accessing Django api with Nuxtjs
I have a Nuxtjs frontend and a Django backend. I want to consume my backend api and have the follwing index.vue : <template> <div class="container"> <h1>{{ data }}</h1> </div> </template> <script> import axios from 'axios' export default { async asyncData({ params }) { // We can use async/await ES6 feature const { data } = await axios.get(`localhost:8000/api`) return { data } } } </script> My nuxt.config.js has this code: axios: { baseURL: 'localhost:8000', proxyHeaders: false, credentials: false, mode: 'no-cors' }, My Django settings.py should be fine as it has corsheaders installed : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'django_celery_results', 'django_celery_beat', 'rest_framework', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False No idea what is going on or why axios is still raising the CORS error : VM1921:1 Access to XMLHttpRequest at 'localhost:8000/api' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. (anonymous) @ VM1921:1 dispatchXhrRequest @ commons.app.js:199 xhrAdapter @ commons.app.js:33 dispatchRequest @ commons.app.js:638 Promise.then (async) request @ commons.app.js:445 Axios.(anonymous function) @ commons.app.js:455 wrap @ commons.app.js:898 _callee$ @ pages_index.js:51 tryCatch @ commons.app.js:5762 … -
Removing all Celery results from a Redis backend
Is there any way in Celery to remove all previous task results via command line? Everything I can find references purge, but that doesn't seem to be for task results. Other solutions I have found include using a Celery beat which periodically removes it, but I'm looking for a one-off command line solution. I use Celery 4.3.0. -
how to access django admin site view model page when having change permission?
When having change permission over a model we can only access editing mode when using django admin interface, How to access a record on view mode like users who have only view permissions ? -
Link two models by common user_id in Django
Is it possible to create a relationship between two models by common foreign key: class User(models.Model): id = models.AutoField(primary_key=True) class Phone(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey('user.User', on_delete=models.CASCADE) class Profile(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey('user.User', on_delete=models.CASCADE) phones = ManyToManyField ? I'd like to get phones directly from Profile so I could prefetch_related('phones') in admin. -
Trying to move the default Django admin app to another base url
Using Django 2.1, I need to point the default admin app to a database dynamically determined by a URL prefix (using a middleware+a DB router). Something like /admin/. when I tried that, the admin code complained about a missing parameter ('db' obviously). ideas? pointers? -
how to use class based views in django
How to change this code into class based views views.py def homepage(request): categories = Category.objects.filter(active=True) products = Product.objects.filter(active=True).order_by('-created') featured_products = Product.objects.filter(featured=True) return render(request,'shop/base.html',{'categories':categories,'product':products,'featured_products':featured_products}) def categories(request,slug): category = Category.objects.get(slug=slug) products = Product.objects.filter(category=category,active=True) return render(request,'shop/products_list.html',{'products':products}) -
Crontab is running but still not executing command Django
I am trying to execute a command through Django Crontab everyday. Here is what I am doing: First, I added django_crontab in INSTALLED_APPS FYI, I have written a Django command sendalerts which is working perfectly fine Now I am trying to run that command through crontab on regular intervals This is what I added in my settings.py CRONJOBS = [ ('* * * * *', 'django.core.management.call_command', ['sendalerts']), ] When I run this command through python manage.py crontab add it doesn't give any error. It also list down cronJob when I check with this command python manage.py crontab show But problem is it doesn't execute the code which is written in my sendalerts command. What can I do to check what is that I am doing wrong or what can be the error which I can fix to make it work? -
Implementing confirmation view and template in django
I have two views one that accepts inputs and the other for confirmation and execution of an action. My problem is how to confirm the inputs from another view and template. This is similar when you delete a record. That you should confirm from the user his actions. Here is the input view. PreprocessinputationView: def PreprocessInputationView(request, **kwargs): proj_pk = kwargs.get('pk') project = Project.objects.get(id=proj_pk) df = pd.read_csv(project.base_file) n_cols = df.keys context = {} context['df'] = df context['n_cols'] = n_cols context['project'] = project if request.method == 'POST': # try: checked_value = request.POST.getlist(u'predictors') method = ''.join(request.POST.getlist(u'method')) if checked_value and method: context['checked_value'] = checked_value context['method'] = method return render(request, 'projects/preprocess/confirm_inputation.html', context) return render(request, 'projects/preprocess/preprocess_inputation.html', context) The confirmation view goes here. ConfirmInputationView: def ConfirmInputationView(request, context): print('method:', context['method']) project = context['project'] df = pd.read_csv(project.base_file) n_cols = df.keys filename = project.base_file.name tmp = filename.split('/') filename = str(tmp[1:]) if request.method == 'POST': # try: checked_value = context['checked_value'] method = context['method'] if checked_value and (method=='mean'): df[checked_value].fillna(df[checked_value].mean()) # df.drop(columns=checked_values, inplace=True) new_df = df.to_csv(index=False) updated_file = ContentFile(new_df) updated_file.name = filename project.base_file = updated_file project.save() str_checked_value = ', '.join(checked_value) context['str_checked_value'] = str_checked_value if str_checked_value: messages.success(request, f'Inputation to column(s) {str_checked_value} successful!') return render(request, 'projects/preprocess/preprocess_inputation.html', context) The confirmation template. Confirm_inputation.html: {% extends "base.html" %} … -
How to export dynamically displayed data from table on html to csv or excel
I am trying to add an export button onto my HTML so that when clicked the filtered data will export. For example, if the table is filtered for names beginning with A limit of 10 names, I would want to export the first 10 names starting with A. As of now, I have an export button that works but only exports the full table completely disregarding the filter. here is my HTML <div class="show-entries"> <span>Show results</span> <select class="form-control" name="limit" id="maxRows"> <option value="5000 ">Full Table</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> </select> </div> </div> <object align= right> <div class="col-sm-5"> <div class="filter-group"> <label>Desired Role</label> <select id="mylist" onchange="myFunction()" class="form-control" > <option>None</option> <option>Assistant</option> <option>Associate</option> <option>Compliance Officer for Finance and Administration</option> <option>Compliance Officer for Legal Practice</option> <option>Consultant</option> <option>Designated Partner</option> <option>Director</option> <option>Employee</option> <option>In-house Solicitor</option> <option>Locum</option> <option>Member</option> <option>Non-member Partner</option> <option>Partner</option> <option>Professional Support Lawyer</option> <option>Prosecutor</option> <option>Role not specified</option> <option>SRA-approved manager - Director</option> <option>SRA-approved manager - Member</option> <option>SRA-approved manager - Partner</option> <option>SRA-approved manager - Sole Practitioner</option> </select> </div> </div> </object> </div> </div> <div id="hi"> <table id="tlaw" class="table table-striped"> <thead> <tr> <th>Solicitor</th> <th>Office</th> <th>Address</th> <th>Primary_Role</th> <th>Secondary_Role</th> <th>Other_Role</th> <th>Other_Role_1</th> </tr> </thead> <tbody id="tls_table"> {% block content %} {% endblock %} </tbody> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button><a href="#" type="button" class="export">Export Table data … -
Combined fields in djangos ModelForm
I want to save SSH Public Keys in an app. I'm chopping the key into its parts so I can better filter for the key content itself. My model looks something like this: class PublicKey(models.Model): key_algorithm = models.CharField(max_length=80) key_base64 = models.CharField(primary_key=True, max_length=1024) key_comment = models.CharField(max_length=80) Using a simple ModelAdmin type admin form all these fields will get their own form field. I'd like to only show one text input per key though, joining them with spaces when displaying and splitting them by spaces when parsing. Adding custom fields is straight forward but where to glue in the de-serialize logic not so much. Any hints? -
'Project' object has no attribute 'request' in Django Model
I am trying to save object of User Model in field created_by and updated_by. For that i wrote save method. But it is giving Attribute Error - 'Project' object has no attribute 'request' Models.py from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings # Create your models here. class Project(models.Model): name = models.CharField(max_length=30) overview = models.TextField(max_length=300) start_date = models.DateField() end_date = models.DateField() completed_on = models.DateTimeField(blank=True, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='project_created_by') created_on = models.DateTimeField(_('project created on'), auto_now_add=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='project_updated_by') updated_on = models.DateTimeField(_('project updated on'), auto_now=True) PROJECT_STATUS_CHOICES = ( ('Active', 'Active'), ('In Progress', 'Pending'), ('On Track', 'On Track'), ('Delayed', 'Delayed'), ('In Testing', 'In Testing'), ('On Hold', 'On Hold'), ('Approved', 'Approved'), ('Cancelled', 'Cancelled'), ('Planning', 'Planning'), ('Completed', 'Completed'), ('Invoiced', 'Invoiced'), ) status = models.CharField( max_length=23, choices=PROJECT_STATUS_CHOICES, default='Active', ) class Meta: verbose_name = _('project') verbose_name_plural = _('projects') db_table = "project" def __str__(self) : return self.name def save(self, *args, **kwargs): print('Inside Save') if self.created_by is None: self.created_by = self.request.user self.updated_by = self.request.user super(Project, self).save(*args, **kwargs) How can i save model field whenever i am updating or creating objects in Project. Should i use Signals -
Filtering choices in a form based on previous field selection - Django
Just quickly to summarize I have an app, which allows clubs to sign up and carry out different tasks. One of the features is a scheduling / rosters. Currently I have a form to add times to the roster. The club pages work off a session key based on the initially selected club. My form consists of: club_id - which I have hidden and initialized based on the logged in user. pitch_id - which is currently displaying all pitches associated to all clubs but I need this to only show pitches based on the foreign key for the club_id Would appreciate any help. form.py from django import forms from clubkit.roster.models import RosterId import datetime from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ class RosterForm(forms.ModelForm): class Meta(): model = RosterId fields = ('club_id', 'pitch_id', 'team_id', 'date', 'start_time', 'finish_time', 'reoccuring_event',) widgets = { 'date': forms.DateInput(attrs={'id': 'datepicker'}) } def clean_date(self): date = self.clean_date['date'] if date < datetime.date.today(): raise ValidationError(_('Date cannot be in the past.')) return date def __init__(self, *args, **kwargs): super(RosterForm, self).__init__(*args, **kwargs) self.fields['club_id'].widget = forms.HiddenInput() models.py for pitch class Pitch(models.Model): club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE, related_name="pitches") pitch_name = models.CharField(max_length=30) PITCH_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) PITCH_TYPE = … -
appointing current user as an entry author in CreateWithInlinesView
I am trying to use Django Extra Views pack to create new entry based on model + inline formset + extra information from the USER model. I know how to do it via function based views but now trying to decrease amount of the code: I have 2 models + user model: Model1: # primary model author = models.ForeignKey("ExtraUser", ) +some fileds Model2 # secondary model photo = models.ForeignKey("Model1", ) + some fields # user model Model ExtraUser(AbstractBaseUser) + some fileds I use following VIEW to render and save it all together: class ItemInline(InlineFormSetFactory): model = Model2 fields = ["somefiled"] class CreateBoatView(SuccessMessageMixin, LoginRequiredMixin, CreateWithInlinesView): model = Model1 inlines = [ItemInline] fields = ["list of the fields here"] template_name = 'create.html' def get_success_url(self): return reverse('app:url', args=(self.object.pk, )) It all work except 1 thing: I cant appoint current user as an entry author, that is author = models.ForeignKey("ExtraUser", ) is always NULL in ancestor function based view I used to do following: if form1.is_valid(): prim = form1.save(commit=False) prim.author = request.user # that is I connect this entry to the current user. # + do something + save(commit=True) finally. How to do same stuff in CreateWithInlinesView? Django says you have to override form_valid … -
Datetime field in a DjangoModelFactory breaks integrated tests
I want to add an "expiry_date" field to a DjangoModelFactory, to match its related model. Here is my implementation : models.py def set_default_expiry_date(): return timezone.now() + datetime.timedelta(days=7) [...] expiry_date = models.DateTimeField( verbose_name=_('Expiry date'), default=set_default_expiry_date, validators=[validate_expiry_date] ) factories.py class OfferFactory(factory.django.DjangoModelFactory): [...] expiry_date = factory.LazyFunction(set_default_expiry_date) test_views.py def test_POST_error_messages(self): offer = factory.build(dict, FACTORY_CLASS=OfferFactory) offer['price'] = 9999 offer['item_count'] = -123 self.client.force_login(self.company_user) response = self.client.post(self.url, offer) self.assertEqual(2, len(response.context['form'].errors)) self.assertTrue( 'price' and 'item_count' in response.context['form'].errors ) This test should only return two error messages, both from failed validation constraints on the 'price' and 'item_count' fields. Yet I get a translated form error message saying that I should provide a valid date and time. This error message does not originate from the custom validator I have added for this field. here is the form's definition, for the sake of completeness : forms.py class OfferForm(forms.ModelForm): [...] class Meta: model = Offer fields = ( [...] 'expiry_date' widgets = { [...] 'expiry_date': forms.DateTimeInput( attrs={'class': 'form-control', } ) } I have USE_TZ and USE_L10N enabled. It looks like the datetime object should use a localized format but fails to do so. When I run the server, the datetime field uses the localized format. So this isn't a configuration issue at … -
Get Parent id in child schema in graphql django
I Want to get child class object in parent schema Here my Models.py class Team(DefaultFieldsModel): name = models.CharField(max_length=50, null=True, blank=True) abbr = models.CharField(max_length=50, null=True, blank=True) class Event(DefaultFieldsModel): name = models.CharField(max_length=50, null=True, blank=True) event = models.foreignkey(Team) class Bet(DefaultFieldsModel): name = models.CharField(max_length=50, null=True, blank=True) event = models.foreignkey(Event) Schema.py class TeamType(DjangoObjectType): home = graphene.Field(TeamType) class Meta: model = Team def resolver_home(self, info): **# Here I want to get Bet object and perform some operations** if team.bet_id ==2: print("bet") return team.bet Class BetType(DjangoObjectType): home_team = graphene.Field(TeamType) class Meta: model = Bet In TeamType schema i want bet object so i can perform operations. I have also tried with graphene.String() but it couldn't help. -
why aren't the fields in my form being displayed?
The form I created isn't being displayed in the html. I made a similar form for signup and literally just changed the field names in the form, and the form isn't being displayed in the html. forms.py class PostCreateForm(forms.ModelForm): title=forms.CharField(max_length=100) content=forms.CharField(widget=forms.Textarea,required=False) class Meta: model=Blog fields=('title','content',) html <form method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> views.py def post_create(request): ImageFormset = modelformset_factory(PostImages, fields=('image',), extra=7) if request.method=='POST': form=PostCreateForm(request.POST) formset=ImageFormset(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): post=form.save(commit=False) post.author=request.user post.save() for f in formset: try: photo=PostImages(post=post,image=f.clean_data('image')) photo.save() return redirect('post-detail') except Exception as e: break else: form=PostCreateForm() formset=ImageFormset(queryset=PostImages.objects.none()) context={ 'form':form, 'formset':formset } return render(request,'blog/post_create.html') -
TinyMCE JS returns 404 in django project
I am getting a 404 in my local server when trying to load TinyMCE JS files. I am using the django-mce package, I have downloaded the latest mce files and added them to my media directory. In attempting to use them with a form, a 404 is returned. forms.py from django import forms from tinymce.widgets import TinyMCE class post(forms.Form): description = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) settings.py # File Management MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # tinymce TINYMCE_JS_URL = os.path.join(MEDIA_ROOT, "js/tiny_mce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(MEDIA_ROOT, "js/tiny_mce") TINYMCE_DEFAULT_CONFIG = { 'theme': 'advanced', 'relative_urls': False, 'plugins': 'media', 'theme_advanced_buttons1': 'bold,italic,underline,bullist,numlist,|,media,link,unlink,image', } The tiny mce js files are stored in proj/media/js/tiny_mce with the base js file saved as tinymce.min.js base.html <head> ... {{ form.media }} ... </head> The editor is working (as far as columns and rows go) but is missing the toolbar. Also the local server returns GET proj/media/js/tiny_mce/tinymce.min.js HTTP/1.1" 404 3024 and at this point I'm at a loss. Any help is appreciated. -
Django server can't find the static files
We're trying to set up a django server to host a web app made with Bootstrap Studio. When trying to merge the backend code and the web frontend, Django is not being able to find the static css and JS files (which are actually there). Here's our directory tree: bookalobackend: -bookalo: +static -css -bootstrap -js -fonts +templates -bookalobackend (main project folder) And here's our settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') GEOIP_PATH = os.path.join(BASE_DIR, 'geoip2') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bookalo', 'django.contrib.gis' ] 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 = 'bookalobackend.urls' TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates').replace('\\', '/'), ) 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 = 'bookalobackend.wsgi.application' #STATIC_ROOT = os.path.join(BASE_DIR, "static/") # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': … -
Django check_password() always returning False
I have an existing database that is used with NodeJs application, now same database will be used for new application that is built with Django. I have an user_account table, which stores user login credentials, and for password encryption bcrypt module has been used. I have extended the Django Users model and overrides its authencticate method, which is working fine. For password varification I'm using bcrypt method bcrypt.checkpw(password, hashed) which is working fine too. Problem: I want to use django user.check_password(password) instead of bcrypt.checkpw(password, hashed). Since it will save the pain of generating salt and encoding before password match and most of all it's a built in method for sole purpose. user.check_password(password) is always returning False and for same password bcrypt.checkpw(password, hashed) is returning True. I have already checked related questions, but all of them had issue with forms and I am not using any django form. My settings.py hashers are as follows PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', ] Input method is a simple django template <div class='col-md-12'> <form action='/auth/login' method='post'> {% csrf_token %} <div class='form-group row'> <label for='email'>Email</label> <input type='email' class='form-control' id='email' name='username'> </div> <div class='form-group row'> <label for='password'>Password</label> <input type='password' class='form-control' id='password' name='password'> </div> <div … -
Celery use own model instead of Taskresults
I'm using Celery with Django. I have periodic task that gets data from a web api. It then saves the results to the db in the taskresults model. The taskresults model just bunches the json from the api into one field, and this isn't what I need. Can I add fields to the taskresult model? I'm having issues with the alternative approach, where I'm creating the model object in a different app to the model - I keep getting app not ready issues in django like this: raise AppRegistryNotReady("Apps aren't loaded yet.") I have a core app with my models in and a Weather app which is my main app with the settings.py file. My celery.py is in Weather and is like so: from __future__ import absolute_import, unicode_literals import requests import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Weather.settings') from core import views from Weather.settings import OPEN_WEATHER_API_URL, OPEN_WEATHER_API_KEY # set the default Django settings module for the 'celery' program. app = Celery('Weather') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules … -
GraphQL: How do I define input parameters/constraints
I am looking for a way to include extra info in the schema so the API consumer knows what is expected. Think along the lines of a max length on a string or something. I expect this to be in the schema since that basically replaces the API documentation, right? I have found this: https://github.com/confuser/graphql-constraint-directive which appears to be similar to what I want, however I don't need the implementation/enforcement since django does that already. I just want to communicate these constraints on input fields. I am very new to this all, so is there maybe a concept of graphql I am missing? Or how do I add this kind of information in the schema? -
Continuous deployment of a django server
I would like to continuously deploy a django server. The command I run to deploy the server is python manage.py runserver However, this command runs as an infinite loop. Therefore, the associated job in the continuous deployment never ends. The problem is that I would like the server to be updated whenever some commit is done. But it won't work here because the next job associated with the commit won't start until the end of the first job. Is there a solution to this problem? -
Django throws error when having multiple forms in formsets while making POST request
I have a django project with a dashboard and forms with formsets built in django admin. I'm trying to make a POST request from the forms to an API. I have two formsets to be specific. When I have more than one form in either of the formsets i am getting the below error. A single form however is going through. Below is my code and the error, Internal Server Error: /admin/campaign/add Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 45, in _wrapped_view_func add_never_cache_headers(response) File "/usr/local/lib/python3.7/site-packages/django/utils/cache.py", line 252, in add_never_cache_headers patch_response_headers(response, cache_timeout=-1) File "/usr/local/lib/python3.7/site-packages/django/utils/cache.py", line 243, in patch_response_headers if not response.has_header('Expires'): AttributeError: 'NoneType' object has no attribute 'has_header' forms.py class CampaignForm(forms.Form): consumer = forms.CharField(label="Consumer", max_length=200) startDate = forms.DateTimeField(label="Start Date", input_formats=['%d/%m/%Y %H:%M']) endDate = forms.DateTimeField(label="End Date", input_formats=['%d/%m/%Y %H:%M']) referreeCredits = forms.IntegerField(label="Referree Credits") referrerCredits = forms.IntegerField(label="Referrer Credits") maxReferreeCredits = forms.IntegerField(label="Max Referree Credits") maxReferrerCredits = forms.IntegerField(label="Max Referrer Credits") message = forms.CharField(label="Message", max_length=200) kramerTemplateId = forms.CharField(label="Kramer Template ID", max_length=200) paymentMode = forms.ChoiceField(label="Payment Mode", … -
Django won't get https header
Intro I am building a web app using the latest Django version along with python3.7. The app is dockerized and I plan to deploy with docker-compose. Inside the container, I use nginx to proxy traffic to the application and not expose it directly. Also, I use apache in server level to proxy traffic to various other containers hosted on the same machine. In the Django application, I use oauth2 to authenticate to Fitbit Web API and the issue I am facing is that the django-social-auth is passing the hostname automatically as a redirect_uri which now, after a lot of configuration with all those proxies, works perfectly in HTTP but when I use HTTPS although the app responds normally the redirect_uri is still http which obviously is not allowed by fitbit and very risky. Although it is very hard for me to locate in which level the problem occurs I have tried various things but nothing seems to work out. What I have tried First I tried to make my container listen to https request which seemed the most appropriate solution to me but ended getting 502 errors from the Apache. I tried to find a solution on this by adding …