Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stop the data base from being updated in production
I am new to Heroku, I have deployed a site from git but the issue is that every time I update the site code, the database also gets updated and all data from my localhost gets in the production, and the data of users from the site is lost. I don't use Heroku ClI and just have simply connected GitHub to Heroku. It's a Django app with a sqlite3 database. I tried .gitignore and git rm --cached too but didn't work. Please tell a way to stop the database file from getting updated when I push it. -
youtube like video function in django
I want to add a new video function to my Django website like youtube like the home page when the user clicks on the video card user is redirected to the video view page but I don't know how to do it -
Force HTML to show time with seconds from a Python model object
Please excuse my newbie status to python and web applications. For a few hours, I simply cannot get this to work properly. All I want to do, is have the table items display the time with seconds. It prints correctly from within views.py, but seems to undergo some conversion when passed to index.html(as seen on console.log)? Or is someone could clarify for me? or point me in the right direction please? model.py: class dbMachine100RunTime(models.Model): ID = models.AutoField(primary_key=True) Machine = models.ForeignKey(Machines, on_delete=models.SET_NULL, null=True, blank=True) Date = models.DateField(auto_now=False, default=datetime.now) Time = models.TimeField(auto_now=False, default=datetime.now) OnOff = models.CharField(max_length=3, default="Error", null=True) Count = models.IntegerField(default=0, null=True) def __str__(self): return str(self.Machine) views.py: def index(request): EndTime = datetime.now() TimeDifference = timedelta(hours=1) StartTime = EndTime-TimeDifference MachineRuntime = dbMachine100RunTime.objects.filter(Time__range=(StartTime, EndTime)) Machine = MachineRuntime[0].Machine print(MachineRuntime[0].Date) #Shows date as = 2021-04-25 print(MachineRuntime[0].Time) #Shows time as = 10:30:36 return render(request, 'Machine_Monitor/index.html', {'MachineRuntime': MachineRuntime, 'Machine': Machine}) index: {% for item in MachineRuntime %} <tr> <td>{{item.Date}}</td> <td><time step="1">{{item.Time}}</time></td> <script> console.log("{{item.Date}}"); <!--Shows as: April 25, 2021 --> console.log("{{item.Time}}"); <!--Shows as: 10:30 a.m. --> </script> </tr> {% endfor %} -
Crispy Fields not working but Crispy Form does
I'm not sure why this is happening but... When I layout my Django ModelForm, if I do {{ form | crispy }} everything goes as planned. If I try to do each individual field like, {{ form.city|as_crispy_field }} everything renders correctly, I get "POST /management/edit_gamelines/197/ HTTP/1.1" 200 28761" in the terminal but the form doesn't submit. Any ideas? I appreciate the help :) -
Is there a way of creation sessions in django via class based views after posting data?
class CreateCompanyView(CreateView): model = Company template_name = 'create/company_create.html' form_class = CompanyForm success_url = '/' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): instance = form.save(commit=False) #section where the session is supposed to be created request.session['company'] =instance.pk instance.save() return redirect("/") I would appreciate if someone has a simpler way or another alternative based on using class based views -
having problem with retriving ( latitude and longitude ) in python
i am working on a report system with django in which the user gives a image of the area they are reporting , locality ( a text field ) and some more text field. i want to add a map in which user can select the location which they are reporting specificaly i want the coordinates ( latitude and longitude ) of the image the user is sending us . can you suggest me some way to get the location of the image the user is sending us as i can't be dependent on the user to tell me correct location here is my html form {% extends 'base.html' %} {% block body %} <form action="report" method="post" enctype="multipart/form-data"> {% csrf_token %} <input name="person" placeholder="person" type="text" value="None"> <input name="local" placeholder="locality" type="text" required> <input name="description" placeholder="description about report" type="text" required> <input name="file" type="file" required> <input type="submit"> </form> {% endblock %} the way that i thought of is we will give the user a map in which he will mark the location and my backend will get the location marked by the user on the map . pls suggest me some way to this this is my current report system that does all … -
when i am try to add post then post add successfully but not show in deshboard it show only home tell me what i do
when i am try to add post then post add successfully but not show in deshboard it show only home. how to solve my problem tell me models.py class Post(models.Model): title = models.CharField(max_length=100) decs = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('author-detail', kwargs={'pk': self.pk}) def __str__(self): return self.title + '|' + str(self form.py class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' labels = {'title': 'Title', 'decs': 'Decription'} title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control',})) decs = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control',})) views.py this function use for add post def addpost(request): if request.user.is_authenticated: if request.method =="POST": form = PostForm(request.POST) current_user = request.user posts = Post.objects.filter(user=current_user) if form.is_valid(): #current_user = request.user title = form.cleaned_data['title'] decs = form.cleaned_data['decs'] pst = Post(title=title, decs=decs) pst.save() messages.success(request, "Blog Added successfully !!") form = PostForm() return render( request, "addpost.html", {'posts':pst} ) else: form = PostForm() return render( request, "addpost.html", {'form' : form} ) else: return HttpResponseRedirect('/login/') this function used for deshboard def dashboard(request): if request.user.is_authenticated: current_user = request.user posts = Post.objects.filter(user=current_user) else: redirect('/login/') return render( request, "dashboard.html", {'posts':posts} ) deshboard.html Dashboard <a href="{% url 'addpost' %}" class="btn btn-success">Add Post</a> <h4 class="text-center alert alert-info mt-3">Show Post Information</h4> {% if posts %} <table class="table table-hover bg white"> <thead> <tr class="text-center"> <th scope="col" … -
Django Error: Request has no attribute user
I have a standard form that allows a user to create a new customer in the system. The new customer data is passed in a POST request from the form, and a stored procedure is executed with the POST data. I have several other functions that operate in the same way with no issues. The Traceback suggests the error is being raised from django\contrib\auth\decorators.py: Traceback (most recent call last): File "...\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "...\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "...\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "...\views.py", line 326, in new_customer new_customer(entityID, storeID, userID, lastName, firstName, phone, dlState, dlNum, dob, dlExp, adr1, adr2, city, state, zipc) File "...\venv\lib\site-packages\django\contrib\auth\decorators.py", line 20, in _wrapped_view if test_func(request.user): AttributeError: 'int' object has no attribute 'user' I added some print statements to the function to verify the value of request. Why is request an int in the first place? The Function: @login_required def new_customer(request): if not validate_user_session(request.user.id): return redirect('newSession') if validate_user_session(request.user.id): print(request.user.id) if request.method == 'POST': entityID = Current_Session_VW.objects.filter(user_id=request.user.id)[0].entity_id storeID = Current_Session_VW.objects.filter(user_id=request.user.id)[0].store_id userID = request.user.id lastName = request.POST['Last_Name'] firstName = request.POST['First_Name'] phone = request.POST['Phone'] email = request.POST['Email'] dlState = request.POST['Driver_License_State'] dlNum … -
Can't implement wiki search properly. Search results by query doesn't work
I'm new to programming and am working on wiki website based on Django. My problem is with Search. If you type the exact name of entry which already exists in wiki it redirects to description properly, but search results by query doesn't work. Returns error: "decoding to str: need a bytes-like object, NoneType found" Here is my code: views.py def search(request): """Search form.""" entries=(util.list_entries()) q = request.POST.get('q') def list_str(entries): str1="" for i in entries: str1 += i return str1 if q.lower() in list_str(entries).lower(): return HttpResponseRedirect('wiki/'+q) elif q.lower() not in list_str(entries).lower(): return render(request, "encyclopedia/nomatches.html") else: empty=[] for title in entries: if q.lower() in title.lower(): results=empty.append() return render(request, "encyclopedia/results.html", {'res':results}) base.html <form action="{% url 'search' %}" method="post">{% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> results.html {% extends "encyclopedia/layout.html" %} {% block title %} Search Results {% endblock %} {% block body %} <h1>Search results</h1> <ul> {% for result in res %} <li> <a href="{% url 'page' entry %}"> {{ result }} </a> </li> {% endfor %} </ul> {% endblock %} There is also util.list_entries() function which returns a list of all names of encyclopedia entries. I chose not to include it, but if it or any other code is needed … -
I am using Chatterbot library can we edit the response which i trained earlier?
I have trained the chatterbot with some conversation now can we edit the trained conversations or should i use chatterbot.storage.drop() -
when I trying to run python manage.py runserver then this error comes
TypeError at /evaluate/ expected string or bytes-like object Request Method: POST Request URL: Django Version: 3.2 Exception Type: TypeError Exception Value: expected string or bytes-like object Exception Location: C:\Users\mrtha\AppData\Local\Programs\Python\Python37\lib\re.py, line 194, in sub Python Executable: C:\Users\mrtha\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.8 Python Path: ['D:\answerEvaluator\answerEvaluator', 'C:\Users\mrtha\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\mrtha\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\mrtha\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\mrtha\AppData\Local\Programs\Python\Python37', 'C:\Users\mrtha\AppData\Local\Programs\Python\Python37\lib\site-packages'] Server time: Sun, 25 Apr 2021 08:05:01 +0000 Traceback Switch to copy-and-paste view C:\Users\mrtha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\mrtha\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars D:\answerEvaluator\answerEvaluator\evaluatorApp\views.py, line 116, in evaluateView answer = re.sub('[^a-zA-Z0-9\s]', '', answer) … ▶ Local vars C:\Users\mrtha\AppData\Local\Programs\Python\Python37\lib\re.py, line 194, in sub return _compile(pattern, flags).sub(repl, string, count) … ▶ Local vars -
making one button trigger another in html
I have a button that lets user download a file, and I have a form that needs to POSTed whenever the user clicks on download button. <a class="down" href="{{x.image.url}}" download="none"> <button>get</button> </a> <form action="/image_info/" method="POST" id='image_form'> {% csrf_token %} <input name='info_button' type="hidden" value="{{x.id}}> <button class="imginfo" type="submit">info</button> </form> So, in this I want the image_form to be submitted and the image to be downloaded when the down button is pressed.Basically the imginfo submit button should be pressed when the download button is pressed. Thankyou! -
Cross-Origin Resource sharing error: Header Disallowed by preflight response
i am learning how to use react as a front end and django as a backend. i am getting these cors issue everytime im hitting post method to django server. It is a very application. Sending a value from react to django server and printing it. In Django server terminal it shows "OPTIONS /sample HTTP/1.1" 200 0 and in react it is showing cors error. i added all the different kinds but the problem still exists enter code here React Component Code import axios from 'axios' import React, { Component } from 'react' import App from '../App'; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "XCSRF-TOKEN"; class addProduct extends Component { constructor(props) { super(props) this.state = { testId : '12324', } this.ButtonClicked = this.ButtonClicked.bind(this) } ButtonClicked =(e) => { e.preventDefault() console.log(this.state) axios({ method: 'post', url: 'http://127.0.0.1:8000/sample', data: this.state.testId, crossDomain: true, mode : 'CORS', headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT", "Access-Control-Allow-Headers": "Origin, Content-Type", "Access-Control-Max-Age" : "200" } }) .then(Response => console.log(Response.data)) } render() { return ( <div className = "addProduct"> <button type = "submit" onClick = {this.ButtonClicked} >Start</button> </div> ) } } export default addProduct Django Code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def showsample(request): username = … -
Why I'm getting a POST http://localhost:3000/upload 404 (Not Found)?
I am making a project that has a React frontend and a Django backend. I was working with the Upload functionality for this project. Users can upload files from the React frontend which will then be uploaded to the media folder in the Django backend. Files are then processed in the Django backend and response data is send to the React frontend. So this is the code for my upload component for the frontend. import React,{useState} from 'react' import './Upload.css' import axios from 'axios' export default function Upload() { const [selected,setSelected] = useState(null) const config = {headers:{"Content-Type":"multipart/form-data"}} const onChangeHandler=event=>{ setSelected(event.target.files) } let url = 'http://127.0.0.1:8000/upload/'; const onClickHandler = async () => { const data = new FormData() for(var x = 0; x<selected.length; x++) { data.append('file', selected[x]) } try{ const resp = await axios.post(url, data,config) console.log(resp.data) } catch(err){ console.log(err.response) } } return ( <div className="upload-container"> <form method="post" encType="multipart/form-data" onSubmit={onClickHandler} > <input type="file" name="myfile" multiple onChange={onChangeHandler} /> <input type="submit" /> </form> </div> ) } This is the core urls.py file at the Django backend. The upload component of react has a route of '/upload'. So, I have created an upload path in the URLs which in turn is linked to Scanner.urls. Scanner … -
How to get dictionary value of a key inside a loop in Django Template?
views.py def get(self, request, *args, **kwargs): domains = Domain.objects.all() context['domains'] = domains domain_dict = {} # .......... # ..........some codes here for domain_dict dictionary print(domain_dict) context['domain_dict'] = domain_dict return render(request, self.response_template, context) Output after printing the domain_dict {4: '', 3: '', 1: '', 5: '', 7: '', 2: '', 6: 'Are you a candidate for the engineering admission (BUET, KUET etc.) test in 2021 ? Obviously you are having regular study and thinking to how to get better day by day. Our experienced advisors may help you for the best preparation for one of the most competitive admission test of Bangladesh.'} Now the domain_dict is sent to template through context. templates.html <div class="col-md-8"> <div class="tab-content"> {% for domain in domains %} {% with domain_id=domain.id %} <div class="tab-pane container p-0 {% if forloop.first %} active {% endif %}" id="services{{domain.id}}"> <div class="img" style="background-image: url('static/counsellor/images/service-1.png');"> </div> <h3><a href="#">Name: {{domain.name}} ID: {{domain_id}}</a></h3> <p>{{domain_dict.6}}</p> </div> {% endwith %} {% endfor %} </div> </div> In the above template I use <p>{{domain_dict.6}}</p>. domain_dict.6 to find the value of key 6. It returns perfectly. Outputs: Are you a candidate for the engineering admission (BUET, KUET etc.) test in 2021 ? Obviously you are having regular study and thinking … -
Which User Agent should i use in My Python Django App Deployed on Heroku which is request another link
I have deployed a python django web app on Heroku. In that app there is a internal function requesting another url and the response 403 is coming in return. The code that i used is url = 'https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY' headers = {'User-Agent' : 'Mozilla/5.0'} page = requests.get(expiry_url, headers=headers) print(page) This Code is working fine in my local terminal as well as on browser and showing result. But in Heroku response <Response [403]> This is recieved. -
unable to send argument value from one view to another view in Django
In my login view function, i wanted to know if the user is redirected here after being stopped from accessing a Page This is basically a Q & A website where user is redirected to login page if he click on write Answer link without signing In Here is views.py of main app from django.shortcuts import render from django.http import request, HttpResponseRedirect, HttpResponse # import the models from .models import Question, Answer, Comment # import paginator for pagination from django.core.paginator import Paginator # import forms from .forms import Write_Answer_form, CommentForm # import user from django.contrib.auth.models import User # import timezone for update function from django.utils import timezone # reverse for efficient url redirecting from django.urls import reverse from django.shortcuts import redirect # Create your views here. # i have deleted some views functions as they seems irrelavant here def writeAns(request,questionID): # check if the user is authenticated if request.user.is_authenticated: # get the Question from ID RequestedQuestion= Question.objects.get(id= questionID) # check if there is a post request from template if request.method == 'POST': # get all the form data with post request into a variable fom= Write_Answer_form(request.POST) if fom.is_valid(): get_save_form_data(RequestedQuestion, request, fom) # make a string url to pass as a … -
How to convert this code to proper float format
I am working on a django app to print the cost of daily expenses I want to print the sum of the total expenses in proper format. I used the below code to print the total total_expense = Expenses.objects.aggregate(total_price=Sum('cost')) and this too Expenses.objects.aggregate(Sum('cost')) They print the total in this format : {'total_price': Decimal('3581360')} I want to print only 3581360 Please can someone tell me how to do it? -
costumer matching query does not exist <- what is this and why does it trigger in form.is_valid() django
I have a code this kind of registration form for my app that I am developing, I am just on my way to implement validation and this happened. I have no idea what is happening Here is my views.py from django.http import HttpResponse from django.shortcuts import render, redirect, get_list_or_404 from users.models import costumer from .forms import costumer_forms def home_view(request, *args, **kwargs): # return HttpResponse("<h1>Hello</h1>") username = "Hello" stat = "Hey" if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") obj = costumer.objects.get(email=email) stat = obj.check_password(password) if stat: return redirect('messenger', username=obj.username) context = { "name": username, "stat": stat, } return render(request, "home.html", context) def register_form(request): # if request.method == "POST": form = costumer_forms(request.POST or None, request.FILES or None) request.session.flush() if form.is_valid(): print("hello") form = costumer_forms() context={ "form": form, } return render(request, "register.html", context) def contact_view(request, username): obj = costumer.objects.get(username = username) context ={ "obj": obj } return render(request, "product/detail.html", context) Here is my forms.py from django import forms from users.models import costumer class costumer_forms(forms.Form): firstname = forms.CharField(required=True, widget=forms.TextInput( attrs={ "type":"text", "name":"firstname", "placeholder": "Ex Juan" } ) ) lastname = forms.CharField(required=True, widget=forms.TextInput( attrs={ "type":"text", "name":"lastname", "placeholder": "Dela Cruz" } ) ) username = forms.CharField(required=True, widget=forms.TextInput( attrs={ "type":"text", "name":"username", "placeholder": "What should … -
Follow and unfollow users - Profile model relationship - SPA
I have created my User and NewPost Models before deciding to add follow and unfollow button, And I have made the relationship when making a new post to add the "poster" as the User and not profile (The new model) - and based on that I've written my queries to return JSON responses. but now I'm trying to add follow and unfollow feature, I have made a new model but I don't have any profiles which make it return "error": "User not found." since I don't have any profiles. How can I fix this do I have to change all the relationships in NewPost or there is a way out? models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted") description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) def serialize(self): return { "id": self.id, "poster": self.poster.username, "description": self.description, "date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } class Profile(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) followers = models.ManyToManyField("User", related_name="following") def serialize(self): return { "profile_id": self.user.id, "profile_username": self.user.username, "followers": self.followers.count(), "following": self.user.following.count(), } views.py import json from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from … -
Display the days of the week for a whole week before changing them in Django template
I'm displaying the days of the weeks like this on my template: {% for day in 7|times %} {% if forloop.counter0 == 0 %} <a href="#category-tab{{forloop.counter}}" id="day-tab{{forloop.counter}}" data-toggle="tab" role="tab" class="day-info active checked"> {% else %} <a href="#category-tab{{forloop.counter}}" id="day-tab{{forloop.counter}}" data-toggle="tab" role="tab"class="day-info"> {% endif %} <span class="num">{{ forloop.counter0|add_days|date:"d" }}</span> <hr class="hr"> <span class="day">{{ forloop.counter0|add_days|date:"D" }}</span> </a> {% endfor %} and everything is fine, the add_days filter is written like this: @register.filter(name="add_days") def add_days(days): newDate = datetime.date.today() + datetime.timedelta(days=days) return newDate and the times filter: @register.filter(name='times') def times(number): return range(number) So I'm getting the days starting from today, and 6 more days, it's fine but I'm wondering can I make those days hold still for like a week before changing them? I mean for today I have the dates displayed from 25 April---->1 May and tomorrow I'll have the days from 26 April--->2 May, what I want is to keep the list still until let's say 1 May before changing it again to the next 7 days, is this possible? -
Different types of models into a django field
Is there an option to create a field that can contain a list of different types of other models? For example we have 3 models (Man,Woman,Child), and a field that can containt a list of them? So that i could for example do something like Human.var.add(Woman), Human.var.add(Man), Human.var.add(Child). Some sort of a list / dict as a field could also work (and this field should containt many of them, var containt many of them). -
Which wsgi server is best performance wise on low end AWS EC2 ubuntu server for deploying django App?
Recently heard about bjoern (they say it is better than uwsgi, gunicorn) but didn't find any nice tutorial to get started with. I don't want to pay AWS for hosting that's why using ec2 micro -
TypeError: 'User' object is not iterable in django
I have wriiten some code here. Please check out the file. When I filled all the fields from django admin then it's working but when I redirect it with http://127.0.0.1:8000/user/application then I am getting below error return [ TypeError: 'User' object is not iterable Where I did wrong? How can I solve it? What is the mean of this? -
how do I push data from Manager producer-consumer to django project and viceversa?
I wrote something to implement a model of consumer-producer with Python asyncio, but I want to move to a real-world scenario where data_sources = [A(),B()] pushes tasks queue to a broker msg like rabbitMQ or Redis backed by celery in order state the periodic handle tasks since data_sources needs to be running each hour, and the base entry data (data topics / IDS or content-specific) to crawl it only pushes one every 24 hours and continue with the hourly worker and once as per on incoming data our consumer it will push the data to PostgreSQL overview architecture overview . ├── backend │ ├── services │ │ ├── newsservice │ └── subscription │ ├── newsletter │ └── subscription ├── patches ├── spiders │ └── blog_crawler │ ├── common ├── third_party │ ├── pipeline │ │ ├── common │ │ └── tests │ │ └── async_sample.py │ │ └── pipeline_async.py data source mock response class A: def __init__(self): pass def run(self): return {"ID-2002-0201":{"id":"ID-2002-0201","updated_at":"2018-05-14T22:25:51Z","html_url":"xxxxxxxxxxxx"}} class B: def __init__(self): pass def run(self): return {"ID-2002-0202":{"id":"ID-2002-0202","updated_at":"2018-05-14T22:25:51Z","html_url":"xxxxxxxxxxxx"}} Manager class Manager: async def producer(self, pipeline, data_sources): """Pretend we're getting a number from the network.""" for data_stream in data_sources: await pipeline.set_message(data_stream.run(), "Producer") logging.info("Producer got message: %s", data_stream) async …