Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If-statement not evaluating correctly in template
I've got the following logic in one of my templates. The message variable is set to "Close Demo" with my view as seen below. views.py messages.error(request, "Close Demo", extra_tags='errortag') I've got the following code in my template to exclude the message if it equals "Close Demo". Template {% if messages %} {% for message in messages %} {% if message != "Close Demo" %} {{message}} {% endif %} {% endfor %} {% endif %} Despite this, the "Close Demo" error still shows up on my page. I'm absolutely baffled why my if-statement isn't executing as desired. Thanks! -
How to fire up all docker containers on a same local ip address in django?
I am writing a django based application with docker where there are 3 projects apps running in different containers. All django applications run at 0.0.0.0:8000. But when I check the ip address of containers to browser the application in browser, they all run at different ip addresses: project1 runs at 172.18.0.10:8000 can be accessed at: 172.18.0.10:8000/app1 project2 runs at 172.18.0.9:8000 can be accessed at: 172.18.0.9:8000/app2 project3 runs at 172.18.0.7:8000 can be accessed at: 172.18.0.7:8000/app3 which makes the hyperlinks of my app unusable. How do I run all the containers at one single ip, 'localhost:8000'? Any suggestions where I am going wrong? -
adding results that generated from views to models(database) generating an error : null value in column "price" violates not-null constraint
my views generally does basic stuff like adding multilying etc now all this will be stored in a variable called grand_total now i want to add this grand_total to my model(database) i have done this by calling my model instance and adding it to it and saving def admin_order_pdf(request, order_id, *args, **kwargs): queryset=D.objects.all() order = get_object_or_404(queryset, id=order_id) type=order.type price=order.price meters =order.meters price_total=price*meters discount=order.discount total=price_total grand_total=total-discount # direct=D.objects.update_or_create(grand_total=grand_total) direct=D() direct.grand_total=grand_total direct.save() i expect the data should be updated in to my grand_total field when i run this function here is the complete error IntegrityError at /pro/bill/17/pdf/ null value in column "price" violates not-null constraint DETAIL: Failing row contains (26, , null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 2018-12-29 06:25:38.733529+00, 10). -
How Facebook Messenger bot (on Django) can ask a question, so next reply by user will be considered as answer?
I have build a bot on Django, and it sends messages if received messages are specific words, and saves them to the model with id of fbid(facebook id). Now I want to send a question (e.g. What is your address?). How to make the bot to send a "question"(not a message), so it knows that the next message from user will be answer. When making buttons in chat, they are with "payloads", so chat knows which button is clicked. Is there any way to apply that principle in messaging? -
Django Model custom field compare previous and new values
I have a field in admin like this: Currently, adding new items to the field replaces the entire field with new files (File Input allows multiple images). However, the goal is to be able to do two things: Uploaded photos append to the existing list of photos instead of replace Clicking "Clear" checkboxes remove photos The current underlying database representation is postgres JSONField. In order to achieve current state, I have overriden ClearableInputField widget and ImageField form field to support multiple files. I have also created a custom Photos Model field that uses JSONField to upload files. Now, here comes my biggest issue. In a typical scenario, if a field is cleared, the file/image will be deleted if it is required by application logic. However, due to the fact that I am fiddling with contents of a field in order to delete photos from the storage, I am not sure where to delete the photos. I like to think about it this way. My Field is basically a "Model" that has some properties. However, this raises one big question. Because I am working at a field level, I can't access previous value to compare values for deleting or appending photos. … -
Using this d3 gauge in django?
I have never used javascript nor d3 in django yet, can anyone run me through on how to include this gauge in my html file in django? I have already npm installed d3-simple-gauge, but I am not sure how to actually use it. https://www.npmjs.com/package/d3-simple-gauge My current understanding is: I have to put a script tag including the link, although I am not sure why. My current don't knows: Do I include the usage part in the d3-simple-gauge documentation all between a script tag? -
Displaying a specific object field in ChoiceField
I've got a ChoiceField in my form. The options that appear in the dropdown are equal to "industry name - frequency" (eg. Car Maintenance - Annual). I want the options in the dropdown to only be equal to the value in the frequency field of the choices that I initialize (eg. Annual). Models.py class IndustryFrequency(models.Model): industryname = models.ForeignKey(Industry, on_delete=models.CASCADE) frequency = models.CharField() def __str__(self): return '{} - {}'.format(self.industryname, self.frequency) Forms.py class UserOrderForm(forms.Form): frequency = forms.ChoiceField() def __init__(self, *args, **kwargs): super(UserOrderForm, self).__init__(*args, **kwargs) self.fields['frequency'].choices = [(t.id, t) for t in IndustryFrequency.objects.filter(industryname=industry)] Thanks for your help! -
Django: store value after user logs in or signs up
I need to create a random value when user stars session and store it after user logs in or signs up. Must be deleted after user logs out. I'm using session.session_key, but could be anyother random value. Why session.session_key? Because it gets automatically generated when user enters website. When user enters website they can add items to their shopping cart, but cannot buy until logs in or signs up. All cart_items use the random value as a token, so if I can save this value after user logs in or signs up I can query the cart_items that are already saved in DB and restore items user had already put in this shopping cart. So when user enters a new session.session_key is created but after user logs in or signs up another session.session_key is created. Making it impossible to use this value to establish a flow between user not logged in and user logged in. My logic: 1.- Save session.session_key in Cookie. 2.- After user logs in or signs up a new session.session_key is created. We need to replace this new session.session_key with the one saved in Cookie. 3.- Get old session.session_key to query all objects created using this value … -
Django Table - loading data table, accessing values
My background is 100% in Excel VBA. But I'm working on building some of my first web applications in Django framework. Please pardon me if this question is ridiculous. I have a giant table (5000 rows x 7 columns) in a CSV file. I would like to somehow load this table into the Django framework -- and access the values in the table. If the table were smaller, I could create a new model, then load the CSV into the model. But instinctively, it feels wrong to create a model with thousands of fields. Is there another way to load the table into Django framework, and reference the values via something like a vlookup function? Thank you for any assistance! -
Django creating a new user using a form
I am trying to allow people to create an account by submitting a form. This is currently just continuing to a login screen but not creating the actual user or coming up with any errors. Debug is currently enabled. I have tried adding an else statement after the user_form.is_valid() to ensure it wasn't invalid but the same issue was happening. I am guessing it is an issue with how the form is saving but I am newer to Django, so any help is appreciated. view: def home(request): if request.user.is_authenticated: return redirect('user_dashboard') else: user_form = CreateUserForm(request.POST or None) if request.method == 'POST': if user_form.is_valid(): user_form.save() context = { 'user_form': CreateUserForm, } return render(request, 'Main/index.html', context) Model: class CreateUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = [ 'username', 'email', 'password', ] def clean_password(self): password = self.cleaned_data.get("password") confirm_password = self.cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) else: return password -
Django on Windows with DB2 fails
I am using: Windows 10 Pro IBM DB2 V11.1 Python 3.7 Django 2.1.4 ibm_db 2.0.9 ibm_db_django 1.1.1.2 After setting the connection information in settings.py and running python manage.py runserver I get the errors (tail only): File "D:\Python37\lib\site-packages\django\db\models\options.py", line 203, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "D:\Python37\lib\site-packages\django\db__init__.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "D:\Python37\lib\site-packages\django\db\utils.py", line 203, in getitem conn = backend.DatabaseWrapper(db, alias) File "D:\Python37\lib\site-packages\ibm_db_django\base.py", line 155, in init super( DatabaseWrapper, self ).init( *args ) File "D:\Python37\lib\site-packages\django\db\backends\base\base.py", line 101, in init self.client = self.client_class(self) TypeError: 'NoneType' object is not callable The same setup works fine on MacOS. A simple python program using ibm_db works fine on Windows. -
How to associate “owner” with default User model?
I’m trying to teach myself Django and the Django Rest Framework, but I'm having a hard time understanding how object ownership is defined. I want to apply the custom “IsOwnerOrReadOnly” permissions given in the DRF documentation with the default User model. My goal: Users will be able to PUT/PATCH/DELETE the information in their own account, but won't be able to change any other users’ information. My user serializer: class UserSerializer(serializers.ModelSerializer): rides = serializers.PrimaryKeyRelatedField(many = True, queryset = Ride.objects.all()) class Meta: model = User fields = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'password', 'rides' ] write_only_fields = ['password'] read_only_fields = ['pk', 'username'] The IsOwnerOrReadOnly code: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user The problem is with the line return obj.owner == request.user. It always returns AttributeError: 'User' object has no attribute 'owner’. Why is the "owner" of a user not the user itself? How can I say “owner = this object” so that my permissions classes work? Follow-up question: I would like to eventually extend the default User model to add more fields. Would my permissions still work if I made a new User model by inheriting from AbstractBaseUser? (I just … -
Getting error while playing video in django web app
I am creating a video streaming website like youtube in django and I am getting the following error while playing videos and when forword the running video. [enter image description here][1] -
How to run django app in heroku with DEBUG=False
I know this may be asked before, but I have tried a lot to get it right but it just won't. I have tried setting DEBUG=False and then setting ALLOWED_HOSTS = ['*'] as many posts here o SO and on medium suggested. please help me get this to work or link to a recent answer that got it right. I have django_herokuu installed already. Below is my settings.py file. When I run it like that I get a 500 error DEBUG = False ALLOWED_HOSTS = ['*'] -
How i can open my django adminstration page again?
I created a django project in my linux terminal and i reached the step that django adminstration page after that i closed the page. Now, i don't know that how i will open that adminstration page again and to make something on my project? -
Where to creat forms an models
Is it a best way to create only one file of forms and one files of models in the folder of the project django? Create for each application one forms.py and one models.py is too long. -
Django how update page after receiving POST request?
I'm new with Django. I would like to update the page in the browser each time a POST request is received by the app. By the moment, I send POST request with POSTMAN. At the end, it is another webserver which will send data through POST request. I don't find any solution to do this. This the code in my view : @csrf_exempt def prem(request): if request.method == 'GET': print("GET") context = {'contenu': request.GET.get("request_received", "nothing") } elif request.method == 'POST': print("POST") datar = request.GET.get('request_received','rien') context = { 'request_received' : datar } return render(request, 'polls/seco.html', context) Code in my template : {% if request_received %} {% csrf_token %} <p>Message received from POST request : {{ request_received }}</p> {% endif %} Someone could help me ? -
Django login user=username never true
I am having problems with my Django login. The below if statement (if user is not None:) always resolves as false, so it moves onto the else. I'm not sure why and I would appreciate any help Thanks VIEWS.PY def index(request): return render(request, 'home.html', {}) def login_user(request): if request.method == 'POST': user = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=user, password=password) if user is not None: login(request, user) messages.success(request, ('You are logged in')) return redirect('index') else: messages.success(request, ('Login failed')) return redirect('login') else: return render(request, 'login.html', {}) And here is the login form: <form name="form1", id="form1" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" id="user" aria-describedby="emailHelp" placeholder="Enter email"> </div> <div class="form-group"> <input type="password" class="form-control" id="password" placeholder="Password"> </div> <button type="submit" class="btn btn-danger">Login</button> </form> -
How to parse request in view.py in Django API?
I want to pass two parameters to the end-point of my Django API. This is the first Django API that I am doing. Currently I hardcoded the input parameters in data = {'param1':[0.4],'param2':[0.9]}. Then I want to be able to call this end-point as follows http://localhost:8000&lat=50&param2=30 How should I update this code of view.py in order to obtained the desired functionality? from django.http import HttpResponse import pandas as pd import json # used to export a trained model from sklearn.externals import joblib def index(request): decision_tree = joblib.load('proj/model/decision_tree.pkl') # now I manually pass data, but I want to get it from request data = {'param1':[0.4],'param2':[0.9]} test_X = pd.DataFrame(data) y_pred = decision_tree.predict(test_X) response_data = {} response_data['prediction'] = y_pred response_json = json.dumps(response_data) return HttpResponse(response_json) -
Issues opening static files using djnago in BeaverDam
I am trying to use the video annotation tool BeaverDam to annotate a static video offline. https://github.com/antingshen/BeaverDam I have a video file 0.mp4 in the directory '/home/arl/BeaverDam/annotator/static/videos' I then included the STATICFILES_DIRS in the setup file: https://github.com/antingshen/BeaverDam/blob/master/beaverdam/settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "annotator/static/") STATICFILES_DIRS = ("/home/arl/BeaverDam/annotator/static/videos", ) I have not been able to view the static folder in the URL. Tried options like localhost:5000/annotator/static/ localhost:5000/annotator/static/videos Any help will be highly appreciated -
How to send password reset email from Django using django-rest-auth and Mailgun
I'm setting up user authentication in Django with Django rest auth. Most things are working well but I can't get the password reset emails to send, either in the dummy backend or with Mailgun. I have an account with Mailgun and am trying to use the sandbox to send mails. # api/urls.py from django.urls import include, path urlpatterns = [ path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('users/', include('users.urls')), ] I'm requesting a password reset for a registered user via the browsable API form: http://127.0.0.1:8000/api/v1/rest-auth/password/reset/ I enter an email address in the form and press 'POST'. The page displays this: POST /api/v1/rest-auth/password/reset/ HTTP 200 OK Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Password reset e-mail has been sent." } However the email is not sent! The mailgun logs show no activity - no email has been sent. When I look on the Network tab in the browser, I don't see a post request. Here's my setup using Mailgun: EMAIL_HOST = 'smtp.mailgun.org' EMAIL_PORT = 587 EMAIL_HOST_USER = 'postmaster@sandboxxxxx.mailgun.org' EMAIL_HOST_PASSWORD = 'xxxx' EMAIL_USE_TLS = True (I've put my real sandbox and password in the actual file) First, with this in settings.py: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I expect the email text to be logged to … -
Django - Update foreign keys to BigAutoField using makemigrations
I had a model with this code: class Author(models.Model): id = models.AutoField(primary_key=True) name= models.CharField(max_length=100) And I have this other model that uses the model above: class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.PROTECT) But, because a integration with other database that I had to do, the id of the Author became a very big integer. So, I had to change the id of Author from models.AutoField() to models.BigAutoField(). Almost everything went Ok. But the field "author" in "Book" continues to be a normal Integer field. And now I'm having problems when I try to insert new Books from an Author because some author's ID's are too big. I found a solution, but it's impracticable in my current database because in other Models I have the same situation of this one. I tried to run django's makemigrations and migrate but even after the fields changes he doens't update the table structure. Please, Is there anything that I can do? -
ModelForm - Access fields in clean()
Giving the the following Model and a ModelForm, how would i get 'Title' in clean()? https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#overriding-modelform-clean-method "A model form instance attached to a model object will contain an instance attribute that gives its methods access to that specific model instance." But 'self.instance.Title' returns "None", even if the field has a value. class Book(models.Model): Author = models.CharField() Title = models.CharField() class Author_Form(forms.ModelForm): Author = forms.CharField() class Meta: model = Book fields = ['Author',] def clean(self): Title = self.instance.Title Author = self.cleaned_data.get("Author") -
Django can't populate table rows on loop every x seconds with jquery post
I want to repopulate my table every few seconds to see what clients are doing on our servers. I'm new to Django but I've managed to stand this project up on a remote server through SSL. I need to request this information and then send back the list for table. I've gotten 404 forbidden errors, errors related to not being able to find the function, ect. Currently, I have the information being fetched but its refreshing the entire page rather than the table rows. This is obviously because I was using: **setInterval(function() { document.getElementById('jobs').submit() }, 5000);** Which I'm trying to avoid Views.py (part of it) class ActiveServerJobsView(LoginRequiredMixin,generic.ListView): template_name = 'project_name/active_server_jobs.html' context_object_name = 'current_job_list' def post(self, request): if request.method == "POST": db_default = connections['default'] default_cursor = db_default.cursor() default_cursor.execute("select server_name from table_name where server_is_database = True") host_list = default_cursor.fetchall() current_job_list = get_current_jobs(host_list) args = {'current_job_list': current_job_list} return render(request,'project_name/active_server_jobs.html',args) def get_queryset(self): db_default = connections['default'] default_cursor = db_default.cursor() default_cursor.execute("select junk, and, stuff from table_name where server_is_database = True") host_list = default_cursor.fetchall() return get_current_jobs(host_list) def get_current_jobs(host_list): current_jobs = [] for host in host_list: host_name = host[0] host_db = connections[host_name + "/example"] host_cursor = host_db.cursor() #get file jobs host_cursor.execute("select junk, and, stuff") host_file_list = host_cursor.fetchall() for … -
How to POST a form with Django and not reload the page
I'm working on an app where the user will submit a value and I want to hide the div containing the form on submit and display a div containing the results. The goal is to have them submit the form and display a different hidden div. What am I doing wrong with either the Django code or Javascript? views.py from django.shortcuts import render from .models import VintageMac from .forms import VintageMacForm def home(request): if request.method == "POST": form = VintageMacForm(request.POST) if form.is_valid(): form.save() form = VintageMacForm() else: form = VintageMacForm() return render(request, 'hmwypapp/index.html', {'form': form}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] models.py from django.conf import settings from django.db import models from django.utils import timezone from django import forms class VintageMac(models.Model): price = models.IntegerField() def publish(self): self.save() def __str__(self): return '%s' % (self.price) forms.py from django import forms from .models import VintageMac class VintageMacForm(forms.ModelForm): class Meta: model = VintageMac fields = ('price',) HTML <div id="submission1"> <p class="card-text">Some quick example text to build on the card title.</p> <div class="bottom"> <div class="row"> <form action="/create_post/" class="w-100" method="POST" id="form1"> <div class="col-12"> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor …