Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can deduct the value from table in django
I am trying to deduct the value of a column in a table from another table. I want if there is any issue in any item it deduct the from the other table but when i do it show the error failed 'ForwardManyToOneDescriptor' object has no attribute 'orderProduct' View.py from purchase.models import OrderRequest from .models import GatePass class OrderView(TemplateView): template_name = 'inventory/orderCheck.html' def get(self, request, *args, **kwargs): orderId = self.request.GET.get('order') order = OrderRequest.objects.filter(pk=orderId) args = {'order': order} return render(request, self.template_name, args) def post(self, request): orderId = self.request.GET.get('order_id') statusAccept = self.request.POST.get('action') == "accept" statusReject = self.request.POST.get('action') == "reject" if statusReject: try: data = self.request.POST.get orderView = GatePass( fault=data('fault'), remarks=data('remarks'), order_id=orderId ) order = OrderRequest.order.orderProduct.quantity - orderView.fault order.save() orderView.save() return redirect('gatePass', 200) except Exception as e: return HttpResponse('failed {}'.format(e), 500) -
Django models for an ESL school
I am working on building a management interface for an ESL (English as a Second Language) institute, basically it is a language school where people learn English. I have prepared my models for each app and I really would like someone to review them and provide me with suggestions and possible mistakes in the design. the models for an app called ez_core: GENDER_CHOICES = [ ('Female', 'Female'), ('Male', 'Male') ] STREET_ADDRESS_CHOICES = [ ('A', 'A'), ('B', 'B') ] EDUCATIONAL_LEVEL_CHOICES = [ ('Bachelor\'s Degree', 'Bachelor\'s Degree'), ('Master\'s Degree', 'Master\'s Degree'), ('PhD Degree', 'PhD Degree'), ] CONTACT_RELATIONSHIP_CHOICES = [ ('Brother', 'Brother'), ('Father', 'Father'), ('Mother', 'Mother'), ('Sister', 'Sister'), ('Uncle', 'Uncle'), ('Wife', 'Wife'), ] MEDICAL_CONDITION_CHOICES = [ ('Chronic Disease', 'Chronic Disease'), ('Allergies', 'Allergies') ] class PersonalInfo(models.Model): full_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) email_address = models.EmailField(max_length=100) birthdate = models.DateField() gender = models.CharField(max_length=6, choices=GENDER_CHOICES) personal_id_number = models.CharField(max_length=100) passport_number = models.CharField(max_length=100) personal_photo_link = models.CharField(max_length=100) id_card_attchment_link = models.CharField(max_length=100) passport_attachment_link = models.CharField(max_length=100) street_address = models.CharField( max_length=100, choices=STREET_ADDRESS_CHOICES) address_reference_point = models.CharField(max_length=100) educational_level = models.CharField( max_length=100, choices=EDUCATIONAL_LEVEL_CHOICES) specialization = models.CharField(max_length=100) contact_phone_number = models.CharField(max_length=100) contact_name = models.CharField(max_length=100) contact_relationship = models.CharField( max_length=100, choices=CONTACT_RELATIONSHIP_CHOICES) medical_condition = models.CharField( max_length=100, choices=MEDICAL_CONDITION_CHOICES) medication = models.CharField(max_length=100) class Meta: abstract = True The models for an app called ez_course: … -
Problem in importing the static files in the django?
i project a folder name = portfolio_projects in which i created the app enter image description here here is where my static folder and app is present enter image description here code of my settings.py STATIC_URL = '/static/' STATICFILES_URL=[ os.path.join(BASE_DIR, 'static'), ] and here is the file in which I want to import {% load static %} <link rel="stylesheet" type="text/css" href='{% static "main.css" %}'> here is the screenshot from the editor with marking enter image description here i am getting this error enter image description here -
DRF simpleJWT - Is there anyway to fetch user's data from an access-token with no access to the 'request' param?
I'm trying to write a custom authentication middleware for Django channels since I'm using JWT for my app's authentication scheme. I'm using the method that is mentioned in this article which basically gets user's token in the first request that is made to the websockets and then, in the receive method of the consumers.py file, fetches user's data based on that and then pours it in the self.scope['user'] (can't make use of the token_auth.py method because the UI app is separate..). Now since I have NO ACCESS to the request param that is usually being used in the views.py files to get the user's data, is there anyway to get the user's data out of an access token alone?? -
django-simple-history - Filter model as of a date
I'm trying to filter an Employee model based on their business, but to keep statistics accurate I want to be able to also get all of the employees as of a specific date. Using django-simple-history I can do Employee.history.as_of(date) which returns a generator object with the employees as of that date. Is there a way that I can use the as_of() method in conjunction with djangos object filtering? I could loop through the generator and do the check within that, but I imagine that would be inefficient. -
ModuleNotFoundError: No module named 'MyApp.urls' Traceback (most recent call last):
This Is My Views.py File from django.shortcuts import render def index(request): message = {"message": "I am from url mapping help!"} return render(request, 'MyApp/help.html', context=message) def second_index(request): message = {"message": "Hey Hello!"} return render(request, 'MyApp/index.html', context=message) This Is My admin urls.py file from django.contrib import admin from django.urls import path, include from MyApp import views urlpatterns = [ path('', views.second_index, name="App"), path('/help', include('MyApp.urls')), path('admin/', admin.site.urls), ] This is my app urls.y file from django.urls import path from MyApp import views urlpatterns = [ path('', views.index, name="index"), ] I already added my app to installed _app list INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyApp' ] When I run code then this File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'MyApp.urls' Traceback (most recent call last): File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\asus\anaconda3\lib\site-packages\django\utils\autoreload.py", line 598, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\asus\anaconda3\lib\site-packages\django\utils\autoreload.py", line 583, in start_django reloader.run(django_main_thread) File "C:\Users\asus\anaconda3\lib\site-packages\django\utils\autoreload.py", line 301, in run self.run_loop() File "C:\Users\asus\anaconda3\lib\site-packages\django\utils\autoreload.py", line 307, in run_loop … -
How to use JsonField instead of many to many field in django
Let say i have two models like these, and i want to store multiple Book's title in the Author's books. but i do not want to use ManyToManyField, and i want to use json instead class Book(models.Model): title = models.CharField(max_length=100) class Author(models.Model): books = JsonField() How can i get the data(title) in the json format from book and store that in Author(books) based on what the user select in django admin panel.(Actually i want to select the books my self, like i do in the many to many field) -
Multiple database in same MySql Server
I already have and database in MySql for my one Django project. !includedir /etc/mysql/conf.d/ !includedir /etc/mysql/mysql.conf.d/ [client] database = project1 user = project_user password = Password port = 3307 default-character-set = utf8 Here, can i have different database(database=project2) for my second project? Note: I am willing to use same user and same password How can i do that? Thanks in advanced. -
How to print OKM tree model in django?
I have to create an OKM model, and for each sentence when a parsed tree is generated have to print that on a Web UI. I am not getting how to do so in Django! How to print an OKM tree model in the Django interface? In python, I wrote the result.draw(), but how to do draw the same in Django? from django.shortcuts import render import os import stanza from bs4 import BeautifulSoup as bs import re import nltk from nltk.tag import tnt from nltk.corpus import indian def indexView(request): if request.method == "POST": user_string =request .POST.get("user_text") train_data = indian.tagged_sents('hindi.pos') tnt_pos_tagger = tnt.TnT() tnt_pos_tagger.train(train_data) tokens = nltk.word_tokenize(user_string) print(tokens) tag = nltk.pos_tag(tokens) print(tag) grammar = "NP: {<DT>?<JJ>*<NN>}" cp =nltk.RegexpParser(grammar) result = cp.parse(tag) result.draw() context = { 'converted_string': result, 'user_string': user_string, } return render(request,'index.html',context) else: return render(request,'index.html',{'content':""}) def dashboardView(request): return render(request,'dashboard.html') } -
How to get an object after been created using CreateView inside django CBV
am trying to create a notification system that tracks all the activities of my users. to achieve this I have created two models, The Contribution model and Notifition model class Contribution(models.Model): slug = models.SlugField(unique=True, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.PROTECT) amount = models.DecimalField(default=0.00, max_digits=6, decimal_places=2) zanaco_id = models.CharField(max_length=20, blank=True, unique=True, null=True) class Notification(models.Model): slug = models.SlugField(unique=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') message = models.TextField(null=True) I want to create a Notification object each time a user creates an object in the Contribution table, but am having some difficulties in getting the object created from CreateView class ContributionAdd(CreateView): model = Contribution fields = ['user', 'amount', 'zanaco_id'] template_name = 'contribution_add.html' def form_valid(self, form, *args, **kwargs): activity_ct = ContentType.objects.get_for_model("????") Notification.objects.create(content_type=activity_ct, object_id="?????",content_object=???,) return super().form_valid(form) how can I achieve the task above ? is their a way doing this using mixins ? -
How to load article page of a blog site using django?
I want to create a blog site. I already created the homepage of the site and there is 4 articles on my blog site. I want to open an article by clicking on it and it will redirect me to the unique article page. Every article page has few images and headlines and line breakers. How will I upload these to my blog model using django? Example article page...See the article page's picture -
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 …