Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelForm Does Nothing
I want to submit a form to the server via Django forms. I did this a few times manually but wanted to use the ModelForm-class this time. Long story short: when I press "Submit" nothing happens plus the "game"-field from the model doesn't show up in the form. My forms.py: from django.forms import ModelForm from .models import Task, Game class UploadForm(ModelForm): class Meta: model = Task exclude = ('player') My model.py: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Game(models.Model): subject_name = models.CharField(max_length=25) class Task(models.Model): task_name = models.CharField(max_length=255) document = models.FileField(upload_to='Tasks/%Y/%m') player= models.ForeignKey(User, related_name="player", on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) stage = models.IntegerField(validators=[MaxValueValidator(13), MinValueValidator(1)]) My HTML code: <form method="post" action="/upload/"> {{ form }} {% csrf_token %} <button type="submit">Add task</button> </form> And finally my view: from .models import Task from .forms import UploadForm @login_required def upload(request): if request.method == "POST": new_task = Task(player=request.user) form = UploadForm(instance=new_task, data=request.POST) if form.is_valid(): form.save() return redirect('user_home') else: form = UploadForm() return render(request, 'upload.html', { 'form': form }) I checked back with some tutorials and they did pretty much the same thing, I just can't find my mistake. I am sorry if this is somewhat obvious but I tried to fix this for the last β¦ -
static django not calling media files
All files in static folder are served like css, font..etc.. but files in media folder aren't like images settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR,'static/') STATIC_URL = '/static/' urls.py urlpatterns += static('media/', document_root=settings.MEDIA_ROOT) urlpatterns += static('static/', document_root=settings.STATIC_ROOT) html <img src='{% static 'media/item/{{data[i].item_photo}}' %}'> The image in file can be accessed and displayed using the link http://localhost:8000/media/item/cake2_Iq0qS8s.jpeg The error says the path is incorrect when i run html http://localhost:8000/static/media/item/%7B%7Bdata%5Bi%5D.item_photo%7D%7D (404 not found) My question is how to call image in media folder using static? -
How to embed ipython notebook to webpage?
I have developed predictive model in jupyter notebook(Python 3.0) which takes input ( 5 features) and predicts the outcome out of it. I want to visualize the output on the webpage using JavaScript. After going through lot of feeds, I found Django or flask could be useful but I don't know how to use it with notebook. Any help would be much appreciated. Novice programmer here, apologies for the language. Thank you -
browserify is not recognized as an internal or external command on django website
I am creating a dynamic form in django using react and browserify. I installed browserify and created my dynamic form with no problem on my laptop. but I can't manage to do the same on the server that will host the website. I tried to install browserify globally and not globally, in and out of the python environment and same thing each time. I tried the solution described in browserify is installed, but is not available in command line I check that the Environment variable %PATH% have the correct path to browserify : screenshot path Here the settings on the server : Server : Windows Server 2012 R2 Python : 3.6.4 Apache : 2.4 Django : 2.0.2 Here the full error message : browserify: subprocess returned a non-success result code: 1, stdout=b'', stderr=b"'browserify' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" Request Method: GET Request URL: ******************** Django Version: 2.0.2 Exception Type: FilterError Exception Value: browserify: subprocess returned a non-success result code: 1, stdout=b'', stderr=b"'browserify' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" Exception Location: C:\Envs\OncoSPPRINT\Lib\site-packages\webassets\filter__init__.py in subprocess, line 527 Python Executable: C:\Apache24\bin\httpd.exe Python Version: 3.6.4 Python Path: ['C:\Apache24\htdocs\OncoSPPRINT', 'C:\Program β¦ -
Django: Display objects and their foreign key objects
Need some help with displaying data. **models.py** class Brand(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Car(models.Model): name = models.CharField(max_length=100) brand = models.ForeignKey(Brand, related_name='brands', on_delete=models.CASCADE) def __str__(self): return self.brand.name + " - " + self.name **views.py** def car_view(request): # pls halp How to display list of Brands and after each brand a list of cars? Example is shown below. Thank you for your help!! :) <html> <ul> <li>Toyota</li> <ul> <li>Corolla</li> <li>Avensis</li> <li>Yaris</li> </ul> <li>Volkswagen</li> <ul> <li>Golf</li> <li>Transporter</li> <li>Passat</li> </ul> </ul> </html> -
Django: override model delete method to remove single object
The page displays a list of users and the videos they added. I'm looking for a way in the file list to add a delete button to completely delete all model fields without going to a separate url. The site administrator clicks on the button, the page is updated and there is no deleted object on it. models.py class VideoFile(models.Model): name = models.CharField(max_length=200, blank=True) file = models.FileField(upload_to="vstories/%Y/%m/%d", validators=[validate_file_extension]) date_upload = models.DateTimeField(auto_now_add = True, auto_now = False, blank=True, null = True) descriptions = models.TextField(max_length=200) reports = models.BooleanField(default=False) vstories = models.ForeignKey(Profile, blank = True, null = True) def delete(self): self.delete() Here I do not know how to properly make the delete method, it turned out to be too simple, and obviously not correct. So I have two questions: first - how to correctly override the delete method in the model. And the second is how to add the method to the button. html {% for profile in profiles %} {{ profile.nickname }} {% for videofile in profile.videofile_set.all %} <video width="320" height="240" controls src="{{ videofile.file.url }}"> Your browser does not support the video tag. </video> <button>Delete</button> {% endfor %} {% endfor %} -
Django2.0 Collectstatic and Admin Issue
I'm deploying my Django web application into my new server in order to set production application. After 2 days in order to config Apache2 and wsgi, I'm getting a new issue according to static files and Administration static page. My Production Environment : Ubuntu Server 16.4 Django 2.0.1 Python 3.5.2 Apache 2.4 WSGI My Static environment : MyProject βββ MyProject β βββ settings.py βββ App1 βββ App2 βββ App3 βββ App4 βββ static β βββ Theme β βββ Theme1 β βββ css β βββ js β βββ images β βββ flags β βββ Theme2 β βββ css β βββ js β βββ images β βββ flags As you can see, I have a static directory which contains all static files in function of choosen theme. I have to make : python3 manage.py collectstatic in order to import static files according to Administration part in my static directory. My settings.py file : # Static files (CSS, JavaScript, Images) # http://docs.djangoproject.com/en/2.0.1/howto/static-files/ STATIC_URL = '/static/' THEME_DIRS = os.path.join(BASE_DIR, "static", "Theme/") STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), THEME_DIRS, ] PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') TraceBack : Copying '/var/www/html/DatasystemsCORE/static/Theme/Datasystems/css/Base.css' Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/valentin/.virtualenvs/DSCoreEnv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, β¦ -
'csrfmiddlewaretoken' is an invalid keyword argument for this function
I have the following class view to calculate the total working days with numpy which is pretty much a simple method but I tend to have an error: 'csrfmiddlewaretoken' is an invalid keyword argument for this function how do I fix this: Models.py class WorkingDay(models.Model): # YY-MM-DD start = models.DateField(null=True, verbose_name="start") end = models.DateField(null=True, verbose_name="end") bizdays = models.IntegerField(null=True) class WorkingDayAPI(APIView): """ { "start":"2018-01-01", "end":"2018-05-01" } """ serializer_class = WorkingDaySerializer # queryset = WorkingDay.objects.all() def bizdays(self, start, end): start = datetime.strptime(start, '%Y-%m-%d') # print(start) end = datetime.strptime(end, '%Y-%m-%d') bizdays = np.busday_count(start, end) return bizdays def get(self, request, format=None): working_days = WorkingDay.objects.all() serializer = WorkingDaySerializer(working_days, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): start = request.data.get('start') end = request.data.get('end') bizdays = self.bizdays(start, end) total_days = WorkingDay.objects.create(**request.data) total_days.start = start total_days.end = end total_days.bizdays = bizdays total_days.save() serializer = WorkingDaySerializer(total_days) return Response(serializer.data, status=status.HTTP_201_CREATED) -
how i can create web application for search "company name" for INDIA like searching domain name
I am working on one of project which have one function, User can search company name using our site. I have eat one hole date for searching API for same but not success. How i can done it. Which API i need to use. -
Django populate user model extension / profile model
So, I created an application and this application needs to save some settings to the user model, hence I added a model with a OneToOne field / profile model. class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) play_onload = models.BooleanField(default=True) I already had some users registered before creating this model and these users need to have entries in the newly created model as well because every user has to have saved settings in the "Manager" application. My problem is now that, although I ran the migrations and gave the field a default value, the model is empty: This seems logical because Django assumingly only populates the models when a user is created. But how would one now go about this? Simply patch the database and fill in entries for all already existing users, also altering the user-creation process? Or is there already a simpler and better way to do this? My manual approach would be simply retrieveing the full list of user ids and creating entries with them, schematically users = User.objects.all() for user in users: Manager(user=user.id) but the problem is that it's manual (and most likely not even 100% correct) -
Make button clickable when 2 input-text aren't empty
I have the following code: <form class="d-flex" action="{% url 'interface:data_v2' user_id %}" method="post"> <input size=13 name="date-start" type="text" placeholder="Data inicial" class="text-center" id="datetimepicker"/> <input size=13 name="date-end" type="text" placeholder="Data final" class="text-center" id="datetimepicker2"/> <button class="btn btn-primary w-100" disabled type="submit"> Mostrar Dades </button> </form> I want to change the disabled to enabled when both input-text aren't empty. How I can do that? -
django middleware TypeError: object() takes no parameters
I try to write a middleware in django.And I get the error and I dont know why. There are the codes in the following: setting.py 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', 'my.middleware.ReadedMiddleware' ] middleware: from django.utils.deprecation import MiddlewareMixin class ReadedMiddleware(MiddlewareMixin): def process_request(self,req): pass the information of error: mw_instance = middleware(handler) TypeError: object() takes no parameters according to other answers.If the middleware subclass from middlewareMixin rather than object,the error will be solved. BUt it not worked. -
How to extend an UpdateView
I want to do some operations after updating an object. So my question is to know after using the django generic UpdateView how can I do some work ? Thanks -
django erasing duplicate values of a model
Hi a have 2 models in my django apps: class City(models.Model) name = Model.CharField(max_length=100) code = Model.PositiveSmallIntegerfield(null=True) def __str__(self): return self.code class Patient(models.Model) name = Model.CharField(max_length=100) city = Model.ForeignKey(City,on_delete=Model.CASCADE,null=True) The problem is i had accidentally add duplicate cities, now i am updating the model for code to unique=True, but it's asking me to delete Patient instances related to those duplicate values. Is there any way to migrate the model properly, without losing related Patient instances? thank you in advance. -
I am new in django and I am stuck in following scenario
I am new in django and stuck with following scene. I am executing following code and when user is invalid means when below code doesn't get access token and error_status flag is true then code in login.html is suppose to execute but it is not executing. Anybody knows why and what modification I have to do to execute following code when user entered wrong credentials. views.py: from django.contrib import messages from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse if access_token: error_status = False { " do something "} else: error_status = True messages.error(request,"Wrong credentials") return HttpResponseRedirect(reverse(login)) login.html: {% if not access_token and error_status %} <small class="small-10 medium-8 large-8 small-centered medium-centered columns error all-error">{% trans "Either your email or password is incorrect !" %}</small> {% endif %} -
duplicated entry error message to ModelForm in django
how to add an error message to be displayed if the user tried to add an entry that is already on the table forms.py class AddCatForm(ModelForm): class Meta: model = Categories fields = ['category_name'] labels = { 'category_name': ('Ψ₯Ψ³Ω Ψ§ΩΩΨ¦Ψ© Ψ§ΩΨ¬Ψ―ΩΨ―Ψ©') } error_messages = { 'category_name': { 'unique': ('Ψ§ΩΩΨ¦Ψ© Ω ΩΨ¬ΩΨ―Ψ© Ψ¨Ψ§ΩΩΨΉΩ') } } views.py def add_cat(request): if request.method == "POST": form = AddCatForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.save() return redirect('/') else: form = AddCatForm() return render(request, "add_cat.html", {'form': form}) When i add an entry that is already there , it just does nothing , i want it to view an error -
Django Framework: ModuleNotFoundError...'bootstrapform'
I get the error ModuleNotFoundError: No module named 'bootstrapform' but I have already installed django-bootstrap-form. I have read other questions here where the fix has been to install that module, but in my case this is not working. I have the same site running on my laptop and can see no difference so it is confusing. So here is the module list: Here is the error: ...and here is the INSTALLED_APPS section of settings.py: I can't see the problem... -
Query data filter by foreign key
Which is correct when I filter by the foreign key? I have a Server model: class Server(models.Model): user = models.ForeignKey(to=User, related_name="servers") ... I want to query a user's all servers, which is correct? Server.objects.filter(user_id=1) and Server.objects.filter(user=1) If the Server.objects.filter(user_id=1) is correct, can I use the Server.objects.filter(user=xxx) to query? -
Django MSSQL server on docker container won't migrate
I am using macOS, Django 2.0 on a virtualenv, and a Docker Container with the SQL Server 2017 up and running. I'm trying to use this package: https://github.com/michiya/django-pyodbc-azure This is my DATABASES settings.py setup: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'TUTORIAS_DATOS', 'HOST': '0.0.0.0', 'PORT': '1402', 'USER': '***', 'PASSWORD': '***', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'driver_charset': 'iso-8859-1', } } } The problem is that when I do python manage.py makemigrations the migration is made, but when I try to apply the migration to the database (python manage.py migrate) I get: Operations to perform: Apply all migrations: admin, auth, contenttypes, menu, sessions Running migrations: No migrations to apply. Instead of what I should get if I use the sqlite (default Django database), which is: Operations to perform: Apply all migrations: admin, auth, contenttypes, menu, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying menu.0001_initial... OK Applying sessions.0001_initial... OK I don't know what could be the problem, theoretically if I follow this steps β¦ -
django redis incr raise exception dict object is not callable incr return not int?
used windowserver2012 django2.0.2 python3.4 iis fastcgi redis_cli.py(https://i.stack.imgur.com/pBKm3.png) account_con.py(https://i.stack.imgur.com/1SpEx.png) my mac run successed same code but this server raise exception 'dict' object is not callable from r.incr() post in moblie sry.. -
when i click the button to update my form CSRF verification failed pop ups
I have two different forms in my index.html template and in both the forms i'm using csrf token. The problem that i'm facing is when I try to update my form i'm getting "CSRF verification failed. Request aborted." I've searched almost all the questions in this site and other websites and did everything still the error is shown. This is my first form which adds student entry: <form action = "{% url 'studentapp:addstudent' %}" id="addform" method = "POST"> {% csrf_token %} <div class = "form-group"> <label for = "your_name"> Your name: </label> <input class = "form-control" id="new_name" type = "text" name="name" value="{{ current_name }}" placeholder="Enter your name"> </div> <div class="form-group"> <label for = "course_name"> Course: </label> <input id="new_course" class = 'form-control' type = "text" name="course" value="{{ current_course }}" placeholder="Enter your course"> </div> <div class = "form-group"> <label for = "rollno"> Roll No.: </label> <input id="new_rollno" type = "text" class = 'form-control' name="roll" value="{{ current_roll }}" placeholder="Enter your roll number"> </div> <div class = "form-group"> <label for ="addr"> Address: </label> <textarea id="new_address" type = "text" name="address" class = 'form-control' value="{{ current_addr }}" placeholder="Enter your address"></textarea> </div> <input type = "submit" value="Submit" class = "btn btn-success" style="font-size:18px;" /> </form> This is my β¦ -
am a newbie working on a simple project am getting wierd errors .using django
what are this errors File "C:\Users\Admin\Projects\trydjango\musicyltd\restaurants\views.py", line 25, in contact return render(request, "contact.html", context) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py", line 63, in render reraise(exc, self.backend) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py", line 84, in reraise raise new from exc django.template.exceptions.TemplateDoesNotExist: base.html [25/Apr/2018 13:54:27] "GET /contact/ HTTP/1.1" 500 120949 -
Django rest bad request error
I have a model: class Scenario(models.Model): tasks = models.ManyToManyField(Task, blank=True) Its serializer: class ScenarioSerializer(serializers.ModelSerializer): class Meta: model = Scenario fields = '__all__' and a view to create a scenario: @api_view(['GET', 'POST']) def scenarios_list(request): """ List all scenarios, or create a new. """ if request.method == 'GET': scenarios = Scenario.objects.all() serializer = ScenarioSerializer(scenarios, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ScenarioSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am sending following data from my frontend: [ {id: 3, title: "Three", how_often: "DS", how_important_task: "EI", role: "Lorem", β¦}, {id: 1, title: "One", how_often: "MO", how_important_task: "RI", role: "Lorem", β¦}, {id: 6, title: "Six", how_often: "WO", how_important_task: "EI", role: "", β¦}, {id: 4, title: "Four", how_often: "", how_important_task: "", role: "", β¦} ] Which throws me BAD REQUEST error. What am I doing wrong? -
Alexa Home Skill - Oauth2 Toolkit - Django Rest Framework - unable to link at this time
Alexa can control smart home devices with its Smart Home Skills. I'm trying it out, but when I try to enable MySkill from the Alexa app, I get 'We were unable to link MySkill at this time'. I've followed Alexa's build a smart home skill I used Django, Django Rest Framework and Oauth2 Toolkit to make my authentication server. I've tested the oauth2 on the command line with curl and it seems ok. When I look at Django's output, I see that it processes both the '/o/authorize/?client_id=...' (GET and POST) with returns 200 and 302. After that I see a '/o/token/' with a 200. Also I see in the database a new 'Access Token' and 'Refresh Token'. All this makes me think Oauth2 has completed successfully. At the point of failure, it points to a guide, Link an Alexa User with a User in Your System. In that guide under the Account linking flow for authorization code grant - The Alexa service validates the returned information, then uses the code to request an access token and refresh token pair from your authorization server (specified in the Access Token URI field in the developer portal). Both of these items are saved β¦ -
Apache/Wsgi - trouble switching from local environment to virtualenv on CentOS
I'm trying to move an existing, working django app from using the local env (i.e. /usr/lib/python2.7/site-packages) to using a virtualenv instead (i.e. [PATH_TO_VIRTUALENV]/lib/python2.7/site-packages). This is meant to help me with package updates eventually, so I can roll back to a previous env if necessary. I started by installing on a fresh virtualenv all of the packages installed in the local env, using the exact same versions. At this point I am able to run the django shell form within the app dir (/home/django/qa/web) using the new env, which should confirm that all dependencies are met. Below are the initial, working configurations. wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web.settings") application = get_wsgi_application() VirtualHost: <VirtualHost *:80> ServerName qa.myserv.com DocumentRoot /var/www/qa.myserv.com/public_html ErrorLog /var/www/qa.myserv.com/logs/error.log CustomLog /var/www/qa.myserv.com/logs/requests.log combined <Directory /home/django/qa/web/web> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess qa python-path=/home/django/qa/web:/lib/python2.7/site-packages WSGIProcessGroup qa WSGIScriptAlias / /home/django/qa/web/web/wsgi.py </VirtualHost> Now, I tried getting this to work with the virtual env, which is located at /home/django/env/qa_0, by changing the WSGIDaemonProcess row: Attempt 1 WSGIDaemonProcess qa python-path=/home/django/qa/web:/home/django/env/qa_0/lib/python2.7/site-packages This resulted in an Internal Server Error, with the following in the error log: [Wed Apr 25 13:57:25.089794 2018] [:error] [pid 23812] [remote 192.168.1.248:240] from django.core.wsgi import get_wsgi_application [Wed Apr 25 β¦