Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reduce excel sheet generation time in Django
I have a huge code written in python(Django framework) which generates an excel sheet and it takes more than 5-10 mins to do so. The code generates multiple tabs in the sheet and it does it one after another (sequential function calls).The first 5-6 tabs take less time and the remaining tabs(network tabs) use the same logic in a single for loop to generate independent network tabs. Is there any way I can generate these network tabs simultaneously to reduce the excel sheet generation time? -
Error validating in instagram api login with django
hi i have a problem in instagram api login im doing all that right as doc said but i have this error : Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request its redirect once but when i want to make a post request it didnt work : @api_view(["GET"]) def insta_call_back(request): code = request.query_params.get("code") user_id = request.query_params.get("state") data = { "client_id": settings.INSTAGRAM.get("client_id"), "client_secret": settings.INSTAGRAM.get("client_secret"), "grant_type": "authorization_code", "redirect_uri": f"{settings.ONLINE_URL}api/insta_call_back", "code": code } resp = requests.post("https://api.instagram.com/oauth/access_token/", data=data) return Response({ "resp": resp.text }) i write this code in python django -
Facing AttributeError: 'bytes' object has no attribute 'read'
cursor = connection.cursor() Fetchstepseven = cursor.execute( "SELECT t.profile_photo, t.id_option, t.id_proof, t.id_proof_number, t.signature FROM trainee t WHERE t.user_id=%s", [payload["id"]], ) records = cursor.fetchall() payload = [] content = {} for result in records: # profile_photo= base64.b64encode(urlopen("https://jrf-recruitment.iirs.gov.in/encodeimage/"+result[0]).read()) gcontext = ssl.SSLContext() profile_photo = JSONParser().parse( base64.b64encode( urlopen( " https://jrf-recruitment.iirs.gov.in/encodeimage/" + result[0], context=gcontext ).read() ) ) jsonResponse = json.loads(profile_photo.decode("utf-8")) content = { "profile_photo": jsonResponse, "id_option": result[1], "id_proof": "encodeimage/" + result[2], "id_proof_number": result[3], "signature": "encodeimage/" + result[4], } # https://jrf-recruitment.iirs.gov.in/encodeimage/"+result[0] payload.append(content) content = {} # Get step seven data code end return JsonResponse( { "success": True, "message": "Step Six successfully done.", "token": token, "data": jrf_serializer.data, "step7": payload, } ) -
I need to execute specific functions in django backend when I click specific buttons in react frontend
Register.js import React, { useState } from 'react'; import './Register.css'; import axios from 'axios' import {RegionDropdown} from 'react-country-region-selector'; function Register() { const [fname,SetFname]=useState(''); const [Lname,SetLname]=useState(''); const [Country,SetCountry]=useState(''); const [des,SetDes]=useState(''); const [file,setFile] = useState(null) const imagehandle =(e)=>{ const datas = e.currentTarget.files[0] setFile(datas) } const handleSubmit= e =>{ e.preventDefault() console.log(file) let form_data = new FormData(); form_data.append('firstname',fname); form_data.append('lastname',Lname); form_data.append('image', file); form_data.append('country', Country); form_data.append('description', des); axios.post('register/', form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then((res)=>{ console.log(res.data) }) .catch((err)=>console.log(err)) } return ( <div class="container"> <h1>Register New case</h1> <form onSubmit={handleSubmit} autoComplete='off'> <div class="row"> <div class="col-25"> <label for="fname">First Name</label> </div> <div class="col-75"> <input type="text" value={fname} onChange={e=> SetFname(e.currentTarget.value)} id="fname" name="firstname" placeholder="Your name.." /> </div> </div> <div class="row"> <div class="col-25"> <label for="lname">Last Name</label> </div> <div class="col-75"> <input type="text" value={Lname} onChange={e=> SetLname(e.currentTarget.value)} id="lname" name="lastname" placeholder="Your last name.."/> </div> </div> <div class="row"> <div class="col-25"> <label for="country">Last Seen</label> </div> <div class="col-75"> <RegionDropdown country="India" value={Country} name="place" onChange={e=> SetCountry(e)}/> </div> </div> <div class="row"> <div class="col-25"> <label for="description">Description</label> </div> <div class="col-75"> <textarea id="des" value={des} onChange={e=> SetDes(e.currentTarget.value)} name="description" placeholder="Write something.."></textarea> </div> <div class="col-25"> <label for="Image">ImageUpload</label> </div> <div class="col-75"> <input type="file" name='img' src={file} onChange={imagehandle} multiple accept="image/*"/> </div> </div> <div class="row"> <input type="submit" value="Submit"/> </div> </form> </div> ); } export default Register; views.py class PostView(APIView): parser_classes = (MultiPartParser, … -
Django form with third party API
I am new in django and web developing. I have something in trouble of django working with third party API and would like some helps. What I want to do is to tell django to send an API simultaneously to store the information at the time the form is submit. (meanwhile save data in both django and other place). Is it possible to do so? Also in UpdateView? Below is my current code, it works well with django about creating data, however I am not sure where to place third party API in them. models.py class DocumentingJob(models.Model): class TaskType(models.TextChoices): MACHINE_LEARNING = ("machine_learning_task", "ml_task") RULE = ("rule_task", "r_task") name = models.CharField(max_length=100, verbose_name="document_task", default="Job") description = models.TextField(verbose_name="description of task") is_multi_label = models.BooleanField(default=False) job_type = models.CharField(max_length=100, choices=TaskType.choices, default=TaskType.RULE) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) task_id = models.UUIDField(default=uuid.uuid1, unique=True, editable=False) create_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return f"{self.name} ({self.get_job_type_display()})" def get_absolute_url(self): return reverse('documenting_jobs:job-detail', kwargs={'pk': self.pk}) views.py class IndexAndCreateView(LoginRequiredMixin, generic.CreateView): model = DocumentingJob template_name = "documenting_jobs/index.html" form_class = DocumentingJobForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['documenting_jobs'] = self.model.objects.order_by('-create_time') return context def form_valid(self, form): form.instance.create_time = self.request.user return super().form_valid(form) forms.py class DocumentingJobForm(forms.ModelForm): class Meta: model = DocumentingJob fields = '__all__' exclude = ['create_by', 'is_multi_label'] widgets … -
How to invalidate django rest framework cache on cloudwatch when doing PUT or POST call
I have a Django rest framework application running behind AWS Cloudfront. I then have an api endpoint /api/user/ which has a GET, POST, and PUT enabled. When I do a POST call to the api endpoint, the GET call shows cache results for about a minute. How do I remove the cache when a POST or PUT is ran? -
store users data django python
Could you please clarify, where users data store when user register in django. F.ex according to this link in github: enter link description here When I login to admin page I can see all users, but can not understand where data stores. -
Responsive CSS not working in Django project
I am using Django for my project. I have given CSS links in my html files like , <link rel="stylesheet" type="text/css" href="{% static 'css/sideCart.css' %}"> My normal CSS are being rendered , but my responsive CSS are not being rendered in , " Device Toolbar " mode. It renders in just inspecting site normally. I have given responsive CSS code as follows: @media (max-width : 920px){ .sideBar{ display : none ; } } -
How to update an item in django without creating a new item?
I'm trying to update an item(book) present in the database, Even though I've added instance so that a new item is not created but instead the item is only updated, but unfortunately it's not working as it is supposed to, Instead of updating the item, a new item is being created, am I missing something in here? models.py class Book(models.Model): book_name = models.CharField(max_length= 100) author_name = models.CharField(max_length=100) publisher = models.CharField(max_length=100) published_on = models.DateTimeField(blank=True, null=True) Language = models.CharField(max_length=100) image = models.ImageField(blank = True, upload_to='images/') created = models.DateTimeField(auto_now_add = True) def __str__(self): return self.book_name @property def imageURL(self): try: url = self.image.url except: url = " " return url views.py def book_register(request): if request.method == 'POST': form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') else : return render(request, 'crud_operation/book_form.html', {'form': form}) else: form = BookForm() context = {'form':form} return render(request,'crud_operation/book_form.html',context) def book_update(request,pk): book = Book.objects.get(id=pk) form = BookForm(instance = book) if request.method == 'POST': form = BookForm(request.POST, request.FILES, instance=book) if form.is_valid(): form.update() return redirect('/') context = {'form':form} return render(request, 'crud_operation/book_form.html',context) urls.py urlpatterns = [ path('create-book/',views.book_register, name = 'books'), path('update-book/<int:pk>/',views.book_update, name = 'book_update'), ] forms.py class BookForm(ModelForm): class Meta: model = Book fields = '__all__' widgets = { 'published_on': DateInput(attrs={'type': 'date'}) } -
How to handle 404 request in Django?
I am trying to handle 404 requests when the page is not found. I am getting an error as Server Error (500). Here is the code : In settings.py DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] In myapp.views: def handle_not_found(request, exception): return render(request, "404.html") In project urls.py : handler404 = "myapp.views.handle_not_found" -
Throwing error when tried to sent javascript object to views in Django
I need to send data that I have as a Javascript object in a javascript file to views in Django. Tried as below but throws error as : Not Found: /postendpoint/$ **main.js** #data from the HTML form stored as JS object formdata={ surname:sur_name, firstname:first_name, login:login_id, assignee:assignee, phonenumber:phone_no, groupname:group, email:email, segment:acsp }; function validation(){ var valid=checkValidity(); console.log(valid); if(valid){ **#sending formdata** $.ajax({ url:'/postendpoint/$', type: "POST", data: formdata, success:function(response){ console.log("formdata sent") }, error:function (xhr, textStatus, thrownError){ console.log("formdata not sent") } }); displayTable(); } } **views.py** def YourViewsHere(request): if request.method == 'POST': formdata=request.POST.get('data') print(formdata) **urls.py** from django import URLs from django.urls import path,re_path from smgusersearch import views urlpatterns = [ path("", views.index,name="index"), path("postendpoint/", views.YourViewsHere,name="YourViewsHere"), ] Need to send the form data in JS file to views -
Google-distancematrix-api not calculating distance for my country
I'm using google-distance_matrix in my web app to calculate distance and prices. The code seems to be working fine if I'm using counties other than my own country (Zimbabwe ). For example from Brooklyn Bridge to Madison Square Gardens the API is able to get the coordinates and provide results first attachment but for any locations within Zimbabwe, the API is unable to produce results second attachment. What might be the problem? first attachment second attachment -
Checksums Sha256
Would love it if some one can I guess have technical knowledge of Checksums sha256 an would like to talk about VMWARE IoT Smartcontracts an about the unruly Oracle problem -
How to solve django and angular cors errors
I'm developing application and got this error: Access to XMLHttpRequest at 'https://subdomain.domain.org/api/parks/?page_size=6&page_number=1' from origin ''https://subdomain.domain.org' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Django Config setting.py: INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ALLOWED_HOSTS = ['app_name-backend.herokuapp.com'] CORS_ALLOWED_ORIGINS = [ 'https://app_name-frontend.herokuapp.com', 'https://subdomain.domain.org', ] CORS_ALLOW_ALL_ORIGINS = False Angular Requests service.ts: getParks(filters: any=null, parameters:any=null): Observable<any> { ... var httpHeaders = new HttpHeaders(); httpHeaders.set('Content-Type', 'application/json'); httpHeaders.set('Access-Control-Allow-Origin', '*'); var requestUrl = this.baseServiceUrl + this.serviceUrl; return this.httpClient.get<any>(requestUrl, { params: httpParams, headers: this.httpHeaders }) .pipe( ... ), catchError(this.handleError<Park[]>('Park getParks', [])) ); } The front and back are hosted on heroku Any idea how to fix it ? Thanks in advance. -
Cann't install django with error 'Non-zero exit code (2)'
When i create new django project in pycharm i have error enter image description here Help me please -
how do I update cart with AJAX
I'm trying to use ajax to update the {{cartItems}} on nav when someone hits the add-to-cart button on shop.html without reloading the page, so far this is what I was able to work on. So how do I make this work? also if u have any other suggestion please lemme knw! would really appreciate your help, thx!! rest of the important code is here: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), nav.html <span class="bag-icon"> {% url 'store:cart' as url %} <a id="icons-account" href="{% url 'store:cart' %}"><i class="fas fa-shopping-bag {% if request.path == url %}change{% endif %}"></i><a id="lil-icon-two">{{cartItems}}</a></a> </span> cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" /*replacing location.reload() with ajax*/ function updating_cart_ajax(){ $.ajax({ url: 'ajax_update/', success: function (result) { $('.shop').reload(result) }, … -
Is it okay to use WordPress HTML for Django?
I have a client asking me to build a static HTML website. He wants to integrate it with Django for backend. The first initial design was not very good and he wants me to build another one with specific feature. I was looking to build the site using WordPress and then convert the WordPress site into a static HTML website using a plugin called Simply Static. My only concern is will it be okay if I use such method to build a static site? I've never use Django, so I don't really know whether it would a problem to integrate their backend or not. The reason why I'm using WordPress is because I think it would be a lot faster for me to do the job. I already generate one Wordpress page into a static HTML and it runs okay without any problem. But, as I said, I don't know if it's gonna be a problem for backend team to integrate Django. Thank you -
react.js & django, useParams unable to navigate to the page
I am current building a react app with django, I am trying to navigate from the HomePage to the DataPage with corrsponding id. However, it return Page not found error. I am using react-router-dom v6. Using the URLconf defined in robot.urls, Django tried these URL patterns, in this order: admin/ api/ api-auth/ homepage homepage/data The current path, homepage/data/54, didn’t match any of these. Here is my App.js export default class App extends Component { constructor(props) { super(props); } renderHomePage() { return ( <HomePage /> ); } render() { return ( <BrowserRouter> <Routes> <Route exact path='homepage/' element={this.renderHomePage()} /> <Route path='homepage/data/:id' element={<DataPage />} /> </Routes> </BrowserRouter> ) } } const appDiv = document.getElementById("app"); render(<App />, appDiv); And I want to navigate to the DataPage below: const EmtpyGrid = theme => ({ Grid: { ... } }); function DataPage(props) { const { classes } = props; const { id } = useParams(); return ( <div> ... some material ui components ... <div/> ) }; DataPage.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(EmtpyGrid)(DataPage); I was thinking whether I need configure my url.py in frontend as well, and I need to define a designated value for {id} returned from the materialui component first. Perhaps … -
How to list the given data in ascending order. The columns "Account name " and " Account status"
enter image description here views.py `def listEngagements(request): active=Engagement.objects.filter(status="Active") completed=Engagement.objects.filter(status="Completed") datas_list=active|completed query = request.GET.get('q') if query: datas_list = Engagement.objects.filter(engagementName__contains=query) paginator = Paginator(datas_list, 20) # 6 datas per page page = request.GET.get('page',1) try: datas = paginator.page(page) except PageNotAnInteger: datas = paginator.page(1) except EmptyPage: datas = paginator.page(paginator.num_pages) return render(request,'engagement.html',{'datas':datas,'username':username}) models `class Engagement(models.Model): engagementName = models.CharField(default=" ",max_length=100,null=True,blank=True) engagementValue=models.IntegerField(default=0) email = models.EmailField(null=True,blank=True) status = models.CharField(max_length=50,null=True) class Meta: ordering =['engagementName'] def __str__(self): return str(self.engagementName)` html code <table class="table table-stripped table-hover"> <thead> <tr> <th>Account Name</th> <th>Account Value</th> <th>Email</th> <th>Account Status</th> <th></th> </tr> </thead> <tbody> {% for i in datas %} <tr> <td>{{i.engagementName}}</td> <td>{{i.engagementValue}}</td> <td>{{i.email}}</td> <td>{{i.status}}</td> <td> <a href="#editEmployeeModal" class="edit" data-toggle="modal" onclick="editengagementDetails( name = '{{i.engagementName}}', engagement_id = '{{ i.id }}', email = '{{i.email}}', status ='{{i.status}}' );" ><i class="fa fa-edit" data-toggle="tooltip" title="Edit"></i></a> <!-- <a href="{% url 'deleteclient' i.id %}" class="delete" ><i class="fa fa-trash" data-toggle="tooltip" title="Delete"></i></a> --> </td> </tr> {% endfor %} </tbody> ` -
migrate fails due to auth.User
I'm trying to use rest_framework.authtoken I'm following this instructions https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication but whenever i try to do python manage.py migrate authtoken.Token.user: (fields.E300) Field defines a relation with model 'auth.User', which is either not installed, or is abstract. authtoken.Token.user: (fields.E307) The field authtoken.Token.user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed. this error happens I red error message and thought that I need to install "auth" so I pip install django-rest-auth but it didn't work and this is my part of my settins.py INSTALLED_APPS = [ 'rest_auth', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } it is views.py (i'm working on it so itis not completed) @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def exchange_token(request, backend): serializer = UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = request.backend.do_auth(serializer.validated_data['access_token']) if user:#drf built in token authentication?? token, _ = Token.objects.get_or_create(user=user) # drf token authentication return Response({'token':token.key}) else: return Response( {'errors':{'token':'Invalid token'}}, status = status.HTTP_400_BAD_REQUEST, ) I'm trying to do this to use that "Token.objects~~" there is no migration file i can fix.. documents just told me to do python manage.py migrate anyone please inform me what is wrong.. -
How to use tooltip in django dropdownlist form
I have a django dropdown list in the django form in forms.py Fruits= [ ('orange', 'Oranges'), ('cantaloupe', 'Cantaloupes'), ('mango', 'Mangoes'), ('honeydew', 'Honeydews'), ] fruits = forms.CharField(label='Fruits', widget=forms.Select(choices=Fruits)) i want to make it such that whenever I hover to any of the list it needs to show a description of that particular fruit. For instance: For orange: it is orange, for apple: it is apple and so on. How would I accomplish that? Any help would be appreciated. Thank you! The option tag has only 'value' attribute, but I would need 'data-toggle: tooltip' and the title attribute. -
My pagination is not working properly django and bootstrap
First image before clicking on the next button second image is after clicking on the next button -
How to use multiple models in one ListView Class
I want to create pege which previews auhors profile and posts with Django. I created UserPostListView Class, then I want to search on Profile model by author's name and get profile. How can I do this? All code here models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg',upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) views.py(UserPostListView Class) class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) context['profiles'] = Profile.objects.all() return context -
Import Deep Learning Models into Django
Background I was building a demo search engine and met a problem of loading my DL models into django. My code is basically structured like this: models/ DPR.py # save model defination utils/ manager.py # save model hyperparameter settings backend/ SearchApp/ view.py # where I want to use my model To clarify, my model should be initialized this way: from utils.manager import Manager from models.DPR import DPR manager = Manager() model = DPR(manager) Problems I want to load the model once after the django app run. I failed to load the model in backend/SearchEngine/app.py as suggested in here because I cannot import DPR and Manager into this file. So any idea? Thanks in advance. -
How do i update manytomanyfield in django?
I want to assign a job to an artisan who clicks 'Accept' but i cant get to assign or update the model to indicate that someone has accepted it.Below is my codes: I want to assign a job to an artisan who clicks 'Accept' but i cant get to assign or update the model to indicate that someone has accepted it.Below is my codes: #model here is the model **class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default =1) img = CloudinaryField(blank=True,null=True) status = models.CharField(max_length=200, null=True, blank=True, default='Pending') description=models.TextField(max_length=100,null=True,blank=True) #location = models.ForeignKey('artsans.Area' ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=300, null=True,blank=True) artisan_assigned = models.ManyToManyField('artisan.Artisan' ,blank=True) date_created = models.DateField(auto_now_add = True, null=True, blank=True) #date_accepted = models.DateField(auto_now_add = True, null=True, blank=True) #payment_id class Meta: verbose_name_plural='Orderitem' ordering = ['-date_created'] #2nd model 2nd model class Artisan(models.Model): user = models.OneToOneField(User,null=True,blank=True, on_delete= models.SET_NULL,related_name='artisan') nin = models.CharField(max_length=20, null=True, unique = True) location = models.ForeignKey(Area ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=15, null=True,unique=True) profession_name = models.CharField(max_length=200, null=True, unique = False) profile_img = CloudinaryField(blank=True,null=True) #date_created = models.DateTimeField(auto_now_add=True, null=True) date_created = models.DateField(auto_now_add = True, null=True, blank=True) def __str__(self): return str(self.user.username) # view file #view.py def jobAccepted(request,id): artisan = [Artisan.objects.filter(user=request.user)] if OrderItem.objects.get(id=id, ordered=True,status='Paid'): …