Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How work with two models and one form?
I've got two models ('Student', 'Instructor') and one form 'RegisterForm' with two selectors (for types). How can i save data from form in corresponding model if in class Meta field 'model' just for the only one model? I guess, my way is wrong, but so i asking. class Student(models.Model): username = models.CharField(max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) password = models.CharField(max_length=30) email = models.EmailField() passed_tests = models.IntegerField(default=0) available_tests = models.IntegerField(default=0) def __str__(self): return self.username class Instructor(models.Model): username = models.CharField(max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) password = models.CharField(max_length=30) email = models.EmailField() written_tests = models.IntegerField(default=0) def __str__(self): return self.username -
Django-Import-Export is not showing up in Admin interface GUI
I have been following the instructions to get the django-import-export http://django-import-export.readthedocs.io/en/latest/ library to work with my models (for importing Products into my Product model). The import/export commands don't to appear on the admin GUI. from import_export import resources from django.contrib import admin from .models import Product, Category from import_export.admin import ImportExportModelAdmin, ImportMixin, ExportMixin, ImportExportMixin class ProductResource(resources.ModelResource): class Meta: model = Product # Register your models here. admin.site.register(Product) class ProductAdmin(ImportExportModelAdmin): resource_class = ProductResource admin.site.register(Category) -
Django Channels not sending reply message
Let me preface this by saying: I am a beginner at RabbitMQ and the concepts around it. I think I am starting to understand though. I currently have a problem with Django Channels. I had a setup where I was using the 'asgiref.inmemory.ChannelLayer' and I am currently switching to 'asgi_rabbitmq.RabbitmqChannelLayer' This all seems to work fine until I try to connect to the websocket from the browser. Nothing happens for a while (7 or 8 seconds) and then all of a sudden the websocket.receive gets triggered and the websocket disconnects. I think it is because the reply channel is not receiving my accept message.(or perhaps too late). routing: lobby_routing = [ route('websocket.connect', ws_test_add, path=r"^/testadd/$"), ] Consumer: def ws_test_add(message): print "TEST" message.reply_channel.send({'accept': True}) Group("testadd").add(message.reply_channel) Settings: CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_rabbitmq.RabbitmqChannelLayer", "ROUTING": 'CouchGames_Backend.routing.lobby_routing', "CONFIG": { 'url': 'amqp://guest:guest@localhost:5672/%2F', }, }, } Log: 2018-01-31 20:00:21,141 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-01-31 20:00:21,144 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-01-31 20:00:21,157 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-01-31 20:00:21,157 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-01-31 20:00:21,163 - … -
django-python3-ldap Search Users belonging to Specific Group in Active Directory
I have django-python3-ldap included in my Django project, and I have it pointed at an Active Directory server. It connects to the AD server and returns a the username, first name, and hashed password to the auth_user table. How do I limit the search to only users in a specific AD group? Here are the relevant settings: LDAP_AUTH_SEARCH_BASE = "OU=******,DC=ad,DC=******,DC=org" LDAP_AUTH_USER_FIELDS = { "username": "samaccountname", "first_name": "givenname", "last_name": "surname", "email": "EmailAddress", } LDAP_AUTH_OBJECT_CLASS = "User" LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "AD" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" I believe I need to use LDAP_AUTH_FORMAT_SEARCH_FILTERS to "and" conditions to the original search base, but I'm not sure exactly how to do so. I assume I need to write a custom format_search_filter, but I don't intuitively understand how it would cross-check with AD groups. -
Multiplying the value of two django integer fields
I am having trouble multiplying the values of two IntegerFields in Django. I am new to Django so I am probably missing something obvious. Here is the error I am getting: NameError at /multiplication/multiplied name 'multiply_two_integers' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/multiplication/multiplied Django Version: 2.0.1 Exception Type: NameError Exception Value: name 'multiply_two_integers' is not defined Here is my code: from django import forms class HomeForm(forms.Form): quantity1 = forms.IntegerField(required = False) quantity2 = forms.IntegerField(required = False) def multiply_two_integers(x,y): return x*y def return_product(self): return multiply_two_integers(quantity1,quantity2) And: from django.shortcuts import render,get_object_or_404 from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic import TemplateView from multiplication.forms import HomeForm # Create your views here. # def startPage(request): # return render(request, 'multiplication/detail.html') template_name1 = 'multiplication/detail.html' template_name2 = 'multiplication/multiplied.html' def get(request): form = HomeForm() return render(request,template_name1,{'form': form} ) def post(request): form = HomeForm(request.POST) if (form.is_valid()): product = form.return_product() return render(request, template_name2, {'form': form, 'product': product }) And template_name1: <h1>Multiplication Function</h1> <form action = "{% url 'multiplication:post' %}" method = "post"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value ="Multiply"> <!--<button type="submit"> Multiply </button>--> <h1>{{product}}</h1> </form> template_name2: <h1>{{product}}</h1> -
is it wrong in Django SQLITE?
class M_Post(models.Model): '''' CODE '''' class M_File(models.Model): .... CODE .... class M_Post_File(models.Model): post = models.ForeignKey(M_Post,on_delete=models.CASCADE) file = models.ForeignKey(M_File,on_delete=models.CASCADE,null=True) error: django.db.utils.NotSupportedError: Renaming the 'posts_file' table while in a transaction is not supported on SQLite because it would break referential integrity. Try adding atomic = False to the Migration class. is it something wrong in SQLite? -
psycopg2.DataError: invalid input syntax for integer: "test" Getting error when moving code to test server
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. Thanks! Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call l ast): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/b ackends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core /management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core /management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core /management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core … -
what the Django form.is_valid() always false
I'm writing a login code. but form.is_valid() always false I don't know why? model.py class User(models.Model): Man = 'M' Woman = 'W' GENDER_CHOICES=( (Man, 'M'), (Woman, 'W'), ) user_no = models.AutoField(primary_key=True) user_email = models.EmailField(max_length=254) user_pw = models.CharField(max_length=50) user_gender = models.CharField( max_length=1, choices=GENDER_CHOICES, default=Man, ) user_birthday = models.DateField(blank=True) user_jdate = models.DateTimeField(auto_now_add=True) signin.html <form method="post" action="{% url 'signin' %}"> {% csrf_token %} <h3>ID : {{form.user_email}} </h3> <h3>PASSWORD : {{form.user_pw}} </h3> <input type="submit" class="btn_submit" value="로그인" /> views.py def signin(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): print("success") else: print("false") else: form = Form() return render(request,'signin.html',{'form':form}) 1) What's wrong? 2)The other signups are true because the signup_bails are true, but why is the signin always false? 3)How do I fix it? -
Django DetailView additional checks based on object
Which method should be overridden to add additional checks and redirect accordingly? i.e. I've a DetailView for my product page, and if this product is not published (and brand has more products) I want to redirect to the brand page. I added this check to get method and I'm calling get_object() manually and then doing my checks, but in the end I'm also calling the super().get() which calls get_object() as well, this makes the SQL run twice. The solution I've found is overriding the get_object() method as following.. def get_object(self, queryset=None): if not hasattr(self, 'object') or not self.object: self.object = super().get_object(queryset=queryset) return self.object This doesn't feel right though, what is the best way to do checks without triggering get_object twice? My code that calls get_object twice looks like this: without the hack above. def get(self, request, *args, **kwargs): product = self.get_object() if not product.published: if product.brand and #more products from brand exists# return redirect(reverse('brand', args=(product.brand.slug,))) else: return redirect(reverse('pages:home')) return super().get(request, *args, **kwargs) -
Django Rest Framewrok Token Authentication for Custom User Model
I'm new to using Django Rest Framework. I have inherited a Django project that has 2 user models: mods.User tied to AUTH_USER_MODEL and players.Member. For reasons I can't get into here, they both inherit from AbstractBaseUser but involve different information, with only an email field common between them. I am trying to use token authentication for users in players.Member. I have created an endpoint /players_endpoint/register which successfully adds players to the database. However, after adding the player to the database, the json response comes back with Cannot assign "<Member: offworld_321>": "Token.user" must be a "User" instance. My create view is as follows: class MemberCreateView(generics.CreateAPIView): queryset = Member.objects.all() def post(self, request, format='json'): serializer = MemberCreateSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: token = Token.objects.create(user=user) json = serializer.data json['token'] = token.key return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I was following the tutorial here How can I make it such that upon registration, a player receives a token which will be used for authentication? -
Why am I receiving this error about app name in my django unittest?
When running manage.py test, I receive the following error. ====================================================================== ERROR: Failure: RuntimeError (Model class app.pipeline.models.Product doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/nose/failure.py", line 39, in runTest raise self.exc_val.with_traceback(self.tb) File "/usr/local/lib/python3.5/site-packages/nose/loader.py", line 418, in loadTestsFromName addr.filename, addr.module) File "/usr/local/lib/python3.5/site-packages/nose/importer.py", line 47, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/local/lib/python3.5/site-packages/nose/importer.py", line 94, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/local/lib/python3.5/imp.py", line 235, in load_module return load_source(name, filename, file) File "/usr/local/lib/python3.5/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 693, in _load File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/src/app/pipeline/tests.py", line 9, in <module> from .views import job_details File "/usr/src/app/pipeline/views.py", line 37, in <module> from .models import (Product, Platform, CdTool, File "/usr/src/app/pipeline/models.py", line 9, in <module> class Product(models.Model): File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 113, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class app.pipeline.models.Product doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. settings.py INSTALLED_APPS = [ 'pipeline.apps.PipelineConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_nose', 'bootstrap3', 'bootstrap_pagination', 'mobilereports', 'rest_framework', 'api' ] This error only gets thrown when I run … -
Django audit packages with django 1.11 and python 3 compatibilty
I am making a project where if the student changes some data in his profile , the teacher should be notified about the same and should have history of all changes . So i am looking for audit packages. I found some but they do not support python 3 . I need to use this changed data so can anyone help me out here ! Thank You -
Comparison between DateField and date.today()
I have a method inside a Django Model class for a Task, that must return the risk situation of such, based on the comparison of expected start and finish dates with today, but I get an error when I try to compare start_date and finish_date models.DateField with date.today() this is the code of the method: def get_todo_situation(self): if self.finish_date == None: return 'unassigned' elif date.today() < self.start_date: return 'warning' elif date.today() < self.finish_date: return 'danger' else: return 'normal' and this is the error I get: File "/home/hugolvc/Code/TaskManagerProject/TaskManager/TaskManagerApp/models.py", line 63, in get_todo_situation elif date.today() < self.start_date: TypeError: '<' not supported between instances of 'datetime.date' and 'NoneType' I have seen examples where this works, but I think I am failing to grasp something. -
Django Deployment Server serving Static Files with only uWSGI
im trying to get my Django App to run using only uWSGI. The project is not that big, so i would really prefer to leave nginx out. I just can't get uWSGI to show my static files though. I've gone through the settings multiple times and can't find the problem. I have the STATIC_URL set to 'module/static/' STATIC_ROOT set to '/module/static_files/' (i read somewhere that they should not be the same) and my uwsgi.ini looks like this: [uwsgi] module=Module.wsgi:application master=True http=:80 processes=4 threads=2 static-map /static= /module/static_files/ the projects file structure is set up in the following way: -- Project: ---init.py ---settings.py ---urls.py ---wsgi.py -- Logs -- module ---static ---static_files ---[... module template, model, urls etc] -manage.py -db.sqlite3 I can run collectstatic and generate all the static files in the correct folder. But when i run the uwsgi script, it wont work and gives me a 404 file not found for all static files. I would really appreciate any help, I've been stuck on this for an entire week now... (i have checked out Deployment with Django and Uwsgi but as far as i can tell, my static-map is set correctly) -
pycharm not loading css files
ok I know this question was asked and I tried every solution. I am using pycharm (community edition) and trying to make use of css files but the project not affected . my project files organization : enter image description here and the codes from files I think the problem is some code in these 2 files because all the project works fine index.html <!DOCTYPE html> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'music/bootstrap /css/bootstrap.min.css' %}" /> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'music:index' %}">Vibber</a> </div> </div> </nav> <body> {%if all_albums%} <h3>Albums</h3> <ul> {% for album in all_albums %} <li> <a href="{% url 'music:detail' album.id %}">{{album.album_title }}</a> </li> {% endfor %} </ul> {%else%} <h3>No Albums</h3> {%endif%} </body> </html> here is setting file """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'utj^)r1l2nso_upv#k+dlb$385x*zo4fdy1n7egwuhgria4hc+' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
How do I make a website which show graphs of sentiment analysis of tweets using Twitter API?
how to make a live website which show graphs of sentiment analysis on tweets based on a specific topic by using python and text-blob library . Iam new to web-development , have moderate knowledge in python . please suggest the resources that i should follow ? -
Allowing HTTP access to Django API that is being authenticated by gmail login
I have an existing web app written in django (python). I have some endpoints that I would like to expose for a new app that we are creating, and we are writing it in ReactJs. In the current web app, where django serves the client pages, we verify authentication via python-social-auth dependency. How can use the gmail authentication for pure REST api calls? do I need to create a new mechanism? -
js to realtime listen to an existing django StreamingHttpResponse
I have been looking for previous answers to similar questions but could not find a clear solution for the frontend part. A view is generating a StreamingHttpResponse upon POST request views.py class streamPredictions(LoginRequiredMixin): def __init__(self,the_thread,the_stream,the_array,the_estimator): self.the_array = the_array[:] self.the_stream = the_stream self.the_thread = the_thread self.the_estimator = the_estimator def predict(self): while self.the_thread.isAlive(): aux_sample,aux_timestamp = self.the_stream.read('AUX') if aux_sample != [0.0,0.0,0.0] and 'nan' not in str(aux_sample): self.the_array = np.roll(self.the_array,-3) self.the_array[0][-3] = aux_sample[0] self.the_array[0][-2] = aux_sample[1] self.the_array[0][-1] = aux_sample[2] X = self.the_array[:] new_val = '{},{}'.format(self.the_estimator.predict(X)[0][0],self.the_estimator.predict(X)[0][1]) yield new_val # def LaunchPredictions(request,pk): ... if request.method == 'POST': the_preds = streamPredictions(t,the_stream,temp_arr_pred,rfr) return StreamingHttpResponse(the_preds.predict()) Here the post request in a js file activated by the click of a button : predict_button function receive_predictions(the_info,the_type,the_fbID,the_URL){ var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value; var data = new FormData(); var initTime = Date.now(); data.append("csrfmiddlewaretoken", csrftoken); data.append("info", the_info); data.append("type", the_type); data.append("id", the_fbID); // Feedback ID data.append("date", initTime); $.ajax({ url: window.location.pathname.replace("acc_calib",the_URL), method: "POST", data: data, contentType: false, processData: false, enctype: 'multipart/form-data', }); } predict_button.click(function() { receive_predictions('Predict','R_FOREST_REG',1,"launch_predictions"); } so that the corresponding url is in urls.py url(r'^launch_predictions/(?P<pk>\d+)/$',views.LaunchPredictions,name='launch_predictions') So far the generated data is streamed as expected from the middleware side but I would need my js to keep listening to it so that I can update graphics generated … -
Django Filter with Pagination
I'm attempting to follow the following tutorial for pagination with django filters, but the tutorial seems to be missing something, and i'm unable to get the pagination to show using the function based views method. https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html My users_list.html is the following: {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-4"> <label/> User ID {% render_field filter.form.employeeusername class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> First Name {% render_field filter.form.employeefirstname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Last Name {% render_field filter.form.employeelastname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Status {% render_field filter.form.statusid class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> <table class="table table-bordered"> <thead> <tr> <th>User name</th> <th>First name</th> <th>Last name</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <td>{{ user.employeeusername }}</td> <td>{{ user.employeefirstname }}</td> <td>{{ user.employeelastname }}</td> <td>{{ user.statusid }}</td> <td><input type="checkbox" name="usercheck" />&nbsp;</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> </table> {% if users.has_other_pages %} <ul class="pagination"> {% if users.has_previous %} <li><a href="?page={{ users.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} … -
Formatting display of floats in django-tables2?
I have a column of floats in a table, and want them to be shown to just two decimal places (so, 10.238324 would be shown as 10.24). In Django templates, I do this using {{number||floatformat:2}}. Is there a similar formatting convention available for columns in django-tables2? Potentially relevant docs: http://django-tables2.readthedocs.io/en/latest/pages/column-attributes.html. -
Django Filtering queryset for use in a form in Heroku
I'm new to this stack so thought I would ask for help on what I think is a simple operation. I have a user model class: class UserProfile(models.Model): SA = 0 TA = 10 PA = 20 DA = 30 US = 1000 ACL_CHOICES = ( (SA, 'Super Admin'), (TA, 'Top Admin'), (PA, 'Parish Admin'), (DA, 'Parish Data Admin'), (US, 'User'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL) access_level = models.IntegerField(choices=ACL_CHOICES, default=US) associated_parish = models.ForeignKey('Parish', null=True, blank=True, default=None) associated_church = models.ForeignKey('Church', null=True, blank=True, default=None) contact_address = models.TextField(max_length=1000, blank=True, null=True) contact_number = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): return "%s's Profile" % self.user.username def username(self): return self.user.username def userid(self): return self.user.pk def is_superadmin(self): return self.access_level == UserProfile.SA def is_topadmin(self): return self.access_level == UserProfile.TA def is_parishadmin(self): return self.access_level == UserProfile.PA def is_parishdataadmin(self): return self.access_level == UserProfile.DA and an admin class for use in creating gui components on heroku: class EventAdmin(admin.ModelAdmin): exclude = () list_display = ('title', 'start_time', 'end_time') def get_queryset(self, request): qs = super(EventAdmin, self).get_queryset(request) if request.user.userprofile.associated_parish: return qs.filter(church__parish=request.user.userprofile.associated_parish) return qs def save_model(self, request, obj, form, change): super(EventAdmin, self).save_model(request, obj, form, change) if request.user.userprofile.associated_parish: obj.parish = request.user.userprofile.associated_parish obj.save() def get_form(self, request, obj=None, **kwargs): if request.user.userprofile.associated_parish: if 'exclude' not in kwargs.keys(): kwargs['exclude'] = [] kwargs['exclude'].append('parish') form = … -
Django test client POST command not registering through 301 redirect
I'm writing Django tests for a live Heroku server, and am having trouble getting Django to recognize a POST request through a redirect. On my test server, things work fine: views.py def detect_post(request): """ Detect whether this is a POST or a GET request. """ if request.method == 'POST': return HttpResponse( json.dumps({"POST request": "POST request detected"}), content_type="application/json" ) # If this is a GET request, return an error else: return HttpResponse( json.dumps({"Access denied": "You are not permitted to access this page."}), content_type="application/json" ) python manage.py shell >>> from django.urls import reverse >>> from django.test import Client >>> c = Client() # GET request returns an error, as expected: >>> response = c.get(reverse('detectpost'), follow=True) >>> response.status_code 200 >>> response.content b'{"Access denied": "You are not permitted to access this page."}' # POST request returns success, as expected >>> response = c.post(reverse('detectpost')) >>> response.status_code 200 >>> response.content b'{"POST request": "POST request detected"}' However, when I move over to my production server, I encounter problems. I think it's because my production server has SECURE_SSL_REDIRECT, so all pages are redirecting to an SSL-enabled version of the same page. Here's what happens when I try to run the same test code on my production server: heroku … -
Django 1.11: ImportError: cannot import name [view]
I'm trying to add ChartsJS as an extra view in my Django App but I keep getting an Import Error. I have no idea why. I don't have any circular dependencies as far as I can find. Similar StackOverflow questions don't seem to match the problem. I'm totally stuck. The problematic view is Analytics view. project/app/urls.py: # -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals ) from django.conf.urls import url from future import standard_library from survey.views import ConfirmView, IndexView, SurveyCompleted, SurveyDetail, AnalyticsView from survey.views.survey_result import serve_result_csv standard_library.install_aliases() urlpatterns = [ url(r'^$', IndexView.as_view(), name='survey-list'), url(r'^(?P<id>\d+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^csv/(?P<pk>\d+)/', serve_result_csv, name='survey-result'), url(r'^(?P<id>\d+)/completed/', SurveyCompleted.as_view(), name='survey-completed'), url(r'^(?P<id>\d+)-(?P<step>\d+)/', SurveyDetail.as_view(), name='survey-detail-step'), url(r'^confirm/(?P<uuid>\w+)/', ConfirmView.as_view(), name='survey-confirmation'), url(r'^analytics/$', AnalyticsView.as_view(), name='analytics-view'), ] project/app/views/analytics_view.py: # -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals ) from builtins import super from future import standard_library from django.views.generic.base import TemplateView from django.contrib.auth.models import User standard_library.install_aliases() import arrow class AnalyticsView(TemplateView): template_name = "survey/analytics.html" ... I've read it may be to do with Settings, but I can't see any configuration problems there - project/settings.py: ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/bootstrap_admin/static/' STATICFILES_DIRS = [ os.path.normpath(os.path.join(ROOT, '..', "survey", "static")), ] Traceback: Unhandled exception in thread started by <function wrapper at 0x05CBB9F0> … -
NOT NULL constraint failed: teams_team.user_id
When I submit a new team as a authenticated user, I get this error is showing. I searched a lot of answers but they say do it null=True or default=1 but I don't want to be it null or something I want to be user's id it. Plus I imported and tried settings.AUTH_USER_MODEL and get_user_model from django.contrib.auth.models import User #models.py class Team(models.Model): creator = models.ForeignKey(User, related_name='teams', on_delete=models.CASCADE) name = models.CharField(max_length=20, unique=True) rank = models.IntegerField(default=0) #views.py class TeamsCreateView(generic.CreateView): model = Team form_class = TeamCreationForm #forms.py class TeamCreationForm(forms.ModelForm): class Meta: model = Team fields = ('name',) -
How to save local image to Django's model?
I've got some images in static dir which is located in 'apps/app_name'. I want to save this images while model instance creation. def save(self, *args, **kwargs): if not self.logo: self.logo = ... super().save(*args, **kwargs) I tried this: file = FileIO(os.path.join(settings.STATICFILES_DIRS[0], 'app_name/image.png')) but i've got an error: The joined path (/home/.../image.png) is located outside of the base path component (/home/.../media) Here is my settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'