Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MPESA integration with C2B Till Number Payment and STK Push
I would like to be able to integrate MPESA API C2B Till Number Payment capabilities with STK push into a Django Web app I am working on such that the user of the platform gets an STK Push notification to pay to the till number and the transaction is stored in the database through a model. I have seen some frameworks people have developed online but most seem to cater for paybill and not till. any help with frameworks that can help me do this will be appreciated. I am finding the official documentation bulky and kind of difficult to work with from django. -
NoReverseMatch at /post/1/log/ Reverse for 'log-create' with keyword arguments '{'post_id': ''}' not found
I have a Post model with a whole bunch of posts. I also have a log model which has a foreign key field to the Post model. Essentially the Log model stores log entries for the Posts in the Post model (basically Post comments). Everything was going great. I have been using CBV for my post models and I used a CBV to List my log entries. I then added a link to redirect me to the Log CreateView using the following anchor tag: <a class="btn" href="{% url 'log-create' post_id=log.post_id %}">Add Entry</a> When the NoReverse errors started occuring. When I change the log.post_id to 1, the page loads correctly. This leads me to believe that the log.post_id is not returning any value. Another thought that I had was that because this anchor tag was on the LogListView there were multiple log entries so it didn't know which post_id to use. But I used the get_queryset function on this view to make sure that only logs related to a single post are returned. In my mind the log.post_id should work. My models are: class Post(models.Model): title = models.CharField(max_length=100, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) overview = models.TextField(blank=True) def get_absolute_url(self): … -
django, supervisor and gunicorn FATAL exited too quickly
*Note: Yes, I know there are several threads with about the same issue but none of them helps. Problem: this is about the conf file of supervisor getting to read the data from gunicorn_start file to launch the server. When I do: sudo supervisorctl reread sudo supervisorctl update All goes well. When I do supervisorctl status I get the answer: FATAL exited too quickly (process log may have details) Error I get: As I have looked in the logs it complains about not being able to find a file /home/videos/gunicorn_start: line 19: /home/videos/languagetech/../entornovirtual/bin/gunicorn: No such file or directory The strange thing is that if I modify the gunicorn_start file by adding extra lines, and I run again sudo supervisorctl status videos I get again the mention to line 19 although it should be another line. This is the gunicorn_start file. After having created it, I did a python manage.py test and all was well. #!/bin/bash NAME="django-videos" DIR=/home/videos/languagetech USER=videos GROUP=videos WORKERS=3 BIND=unix:/home/videos/run/gunicorn.sock DJANGO_SETTINGS_MODULE=tutoriales.settings DJANGO_WSGI_MODULE=tutoriales.wsgi LOG_LEVEL=error export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../entornovirtual/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- ===================================================================== SUPERVISOR FILE [program:videos] command=/home/videos/gunicorn_start directory = /home/videos/languagetech user=videos autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/videos/logs/gunicorn.log … -
How to render template after failed form validation?
urls.py: urlpatterns = [ path('employee/add_employee/', views.add_employee, name='add-employee'), path('employee/add_employee/add/', views.add_employee_action, name='add-employee-action'), ] I have add-employee page and some forms to fill there. views.py: def add_employee(request): personal_form = PersonalEmployeeForm() history_form = EmployeeHistoryForm() return render( request, 'sections/add_employee.html', context={ 'personal_form': personal_form, 'history_form': history_form, } ) def add_employee_action(request): if request.method == "POST": personal_form = PersonalEmployeeForm(request.POST) history_form = EmployeeHistoryForm(request.POST) if personal_form.is_valid() and history_form.is_valid(): # here is some logic with models return redirect('add-employee') else: personal_form = PersonalEmployeeForm() history_form = EmployeeHistoryForm() return render( request, 'sections/add_employee.html', context={ 'personal_form': personal_form, 'history_form': history_form, } ) The problem is after submitting invalid forms I have a page with blah-blah/employee/add_employee/add/ URL. And if I try to submit forms again I have a page with blah-blah/employee/add_employee/add/add/ URL, wich is incorrect. How can I render the page with blah-blah/employee/add_employee/ URL and show all error messages? -
How can I store possible values of a dropdown-box in a model and use them in a form
I am trying to create a dropdown box where a list of possible values is taken from the model, in such a way that when instanciating a model in the admins view for example, multiple options can be given to the model for use as the variables in the dropdown-box. I have tried googling around and can't find a clear awnser, or I am not understanding them at least. I also found django-collectionfield is this what I need? Just to be clear, I want the variables displayed to be dynamic on a model level. I want the give the administrator option to define a list of variables which then are used on the appropriate form in a dropdown-box. Thanks in advance! -
Active Tag in for extended templates
I'm a newbie to Django and want some help on template inheritance. I want to set "class="active" for the current active page but how do I do with template inheritance,as it generalizes it for all the pages but the active should change on changing current active page. I know this question might be silly but I don't know the answer still. I have no idea what to do for this case. <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse " id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item mx-3"> <a class="nav-link" href="/Homepage/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item mx-3"> <a class="nav-link" href="/booking/">Make a Booking</a> </li> <li class="nav-item mx-3 active"> <a class="nav-link" href="/History/">History</a> </li> <li class="nav-item mx-3"> <a class="nav-link" href="/pending/">Pending requests</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="nav-item "> <form method="POST" action="{% url 'logout'%}"> {% csrf_token %} <a class="navbar-brand text-capitalize navbar-brand text-white">{{ user }}</a> <button type="submit" class="btn btn-danger mx-3">Logout</button> </form> </li> </ul> </div> </nav> I expect the active class might get applied to only current active pages. -
How to render elements depends on select value in react
i'm newbie in react and i wanted to render different HTML Elements depends on Selected value And if its possible POST datas in selected html to django model here is my react js code : class Resepy extends React.Component { constructor(props){ super(props); this.state = { selected : 'default' }; } setSelected = (event) => { let select = document.getElementById("id_field1"); document.getElementById("test").innerHTML = select.value; } render() { return ( <div className="Resepy"> <h1>Something</h1> <form> <select id="id_field1" name="field1" onChange={this.setSelected}> <option value="default">Food type not selected</option> <option value="burger">Burger</option> <option value="pizza">Pizza</option> </select> <div id="test"></div> <div className="food">{ this.state.selected == "default" ? <div className="default">Default</div> : this.state.selected == "Burger" ? <div className="burger">Burger</div> : <div className="pizza">Pizza</div> }</div> <button type="submit">Add to tray</button> </form> </div> ); } } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> -
How to know in a middleware which type of url entered?
Recently I started a new simple project in Django. I wrote some middleware. but in one of the middlewares, I want to know which URL is called because I have to make a decision which is related to URL. I used this code: import os path = os.environ['PATH_INFO'] but it makes an error which is described below: raise KeyError(key) from None KeyError: 'PATH_INFO' so how I can know the URL in my middleware? -
main view keeps redirecting to login page even for logged-in user in django
my main view is, def main(request): if request.user.is_authenticated: return render(request,'main/main.html',{'use':use,'query':query,'noter':noter,'theme':request.user.profile.theme}) else: return redirect('home') the home page is responsible for serving login form is def home(request): if request.user.is_authenticated: return redirect('main') else: return render(request,'home.html') the "home.html" uses ajax to submit login page $(document).ready(function(){ $('#form2').submit(function(event){ event.preventDefault(); $('#username_error').empty(); $("#password_error").empty(); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var formdata={ 'username':$('input[name=username2]').val(), 'password':$('input[name=loginpassword]').val(), }; $.ajax({ type:'POST', url:'/Submit/logging', data:formdata, dataType:'json', encode:true, headers:{ "X-CSRFToken": csrftoken }, }) .done(function(data){ if(!data.success){//we will handle error if (data.password){ $('#password_error').text(data.password); } if(data.Message){ $('#password_error').text("You can't login via pc"); } blocker(); return false; } else{ window.location='/'; } }); event.preventDefault(); }); this configuration is working fine but main page keeps redirecting to home.html even when though user is already logged in. I'm using nginx server whose configuration is server { server_name host.me www.host.me; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/projectname; } location /media/ { root /home/username/projectname/appname; } location / { include proxy_params; proxy_pass http://unix:/home/username/projectname/projectname.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.host.me/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.host.me/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }server { if ($host = www.host.me) { return 301 https://$host$request_uri; } # managed by Certbot if ($host … -
Django Design: Store Extracted File Contents Automatically to DB
In my application, I have a scraper that kicks off every morning, generates the daily Islamic prayer times and saves them in a text file. I need to extract the contents from this file and save them to a db. I would like to have Django/Python automatically do this for me, check the file if it exists and slurps up the contents. The contents in the text file looks something like this: {"sunrise": "6:30AM", "noon": "12PM", "afternoon" : "5:30PM"} How do I go about writing the Model class? Should I go with a variable for each entry, meaning: pSunrise, tSunrise, pNoon, tNoon...etc (p = prayer, t = time) Or does it get stored differently? Secondly, how do I initiate Django to automate this for me? This has been bugging me for quite a while and I greatly appreciate all the help I can get. Thank you! -
3 questions about the web development
i am trying to go into the web development path and trying to React+Django Combination to get started. But i am having some doubts related to this. i. we can build a webpage both with Django and react. Then why are we categorized them as frontend and backend ? Though i know frontend means what user sees and backend means the logic behind the scene that helps the frontend to thrive. Can't we just use just one Django or React ? ii. Suppose i followed a tutorial to build 2 projects using react and Django separately. Then we will deploy . What are next things to learn to make it happen? i am asking long questions as am a noob here. Hoping for a detailed explanation. -
How to get coordinates correctly from django to leaflet with geojson
I loaded some Shapefile multipolygons into Geodjango to show them as a layer on a Leaflet map. But on the website, no layer appears, just the map itself. The geometry data are stored in the Geodjango database like so: from django.contrib.gis.db import models class wgo(models.Model): (some more variables) poly = models.MultiPolygonField(srid=4326) I pass the multipolygons with geojson and serialize like so: wcrds = wgo.objects.filter(id=wid) gridone = serialize('geojson', wcrds.all()) return render(request, 'result.html', {'gridone': gridone}) And when I inspect the page I can see that the geojson data indeed makes it to the html: var Hlayer = new L.GeoJSON( {"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"wijkcode": "WK036356", "wijknaam": "Middenmeer", "poly": "SRID=4326;MULTIPOLYGON (((4.93714288723798 52.3576900936898, 4.93742729807085 52.3577390397678,)))", "pk": "909"}, "geometry": null}]} , { style: Hstyle } ); var mymap = L.map('mapid').setView([52.3701, 4.8967], 13); var OpenStreetMap_Mapnik = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(mymap); (I took out most of the coordinates for brevity's sake). It looks like geojson did not pick up on the fact that the poly variable is the one with the geometry. I see geojson coordinates with square brackets around them on example sites, as opposed to the round ones on mine. I … -
How to render element depends on selected option?
i'm new in React, and i want to render Different Elements depends on user selection via select and option tags. how can i do this? this is my wrong code : class Resepy extends Component { state = { Resepy : 'default' } render() { let Resepy = ( <div className="Resepy"> <form> <select id="id_field1" name="field1" onChange={(e) => this.state.Resepy = "Burger"}> <option value="default">Food type not selected</option> <option value="burger" onClick={(e) => this.setState({ Resepy: 'Burger' })}>Burger</option> <option value="pizza" onClick={(e) => this.setState({ Resepy: 'Pizza' })}>Pizza</option> </select> <div className="food"> <div className="default" Resepy={this.state.Resepy === 'default'}></div> <div className="burger" Resepy={this.state.Resepy === 'burger'}></div> <div className="pizza" Resepy={this.state.Resepy === 'pizza'}></div> </div> </form> </div> ); -
field of a model is disabled in admin panel
I have a model which name is article and each article has a title. I want to create a new article via admin but I've encountered that just the title field is suddenly disabled and I can't enter the title. my article model is such below: class Article(models.Model): title=models.CharField(max_length=100) body=models.TextField() view=models.IntegerField(default=0) created_at=models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now = True) published_at = models.DateTimeField(default=timezone.now) show=models.BooleanField( default=1) def __str__(self): return self.title user = models.ForeignKey(User,on_delete=models.SET_NULL, null = True) categories = models.ManyToManyField(Category) class Meta: permissions=( ('private_section_article','Private Section Article'), ) and the admin file corresponds to this model is: @admin.register(Article) class ArticleAdmin(ModelAdminJalaliMixin,admin.ModelAdmin): def published_fa(self,model): return datetime2jalali(model.published_at).strftime('%y/%m/%d _ %H:%M:%S') list_display=('title','view','published_fa','created_at','updated_at','show') list_display_links=('published_fa',) search_fields = ['title','body','created_at'] list_filter=('published_at','title') date_hierarchy='updated_at' ordering=['-created_at'] readonly_fields = ('title',) actions=['make_hide','make_show'] fieldsets = ( (None, { "fields": ( 'title','categories','body','published_at' ), }), ('Advanced Options',{ 'classes':('wide', 'extrapretty','collapse'), 'fields':('view','show','user') }) ) def make_hide(self,request,queryset): # queryset oonayi hastan ke tik khordan row_updated = queryset.update(show=0) message='1 article was' if row_updated is not 1: message="%s articles were" % row_updated self.message_user(request,"%s marked as hide" % message)# to show a message after this action have done make_hide.short_description='make selected articles as hide' def make_show(self , request , queryset): row_updated = queryset.update(show = 1) message='1 article was' if row_updated is not 1: message="%s articles were" % row_updated self.message_user(request,"%s marked … -
Django - Displaying Prices on elasticsearch results
I am making a booking website, and I have implemented elasticsearch. I got the search working just fine, but now I am kind of stuck on a problem. What I'm trying to do is display the lowest price for the apartment the user has searched for, in the search results. The prices are stored in the "ApartmentPrices" model : class ApartmentPrices(models.Model): apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="price") price_start_date = models.DateField(blank=True, null=True) price_end_date = models.DateField(blank=True, null=True) price = models.IntegerField() def __str__(self): return self.apartment.title This is my document and view for the actual search : search view : def search(request): apartments = Apartment.objects.all() q = request.GET.get('q') if q: apartments = ApartmentDocument.search().query("match", title=q) else: apartments = '' return render(request, 'search/search_elastic.html', {'apartments': apartments, "q": q, }) document: apartments = Index('apartments') @apartments.document class ApartmentDocument(Document): class Django: model = Apartment fields = [ 'title', 'id', 'bedrooms', 'list_date', ] I have tried passing in apartment_id to the search view, but I cannot get it to work. Can anyone point me in the right direction please ? -
Redirect to model creation if it doesn't exit
When I login to django as a superuser, if an object of some model or the a field of the last object in that model doesn't exist or isn't set, how would I redirect to the creation of that model? And don't let me access the WebApp unless it's made? I'm guessing there's a function to be run whenever a superuser logs in and check for an object or a field in the last object. I just don't know how to make this function and where to put it. Thank you for your time reading this. -
Use of Django and GeoDjango simultaneously
I've a doubt about the use of GeoDjango with Django. I've two app in my project: Blog and Map. This two app are in relation with a third app Kernel. Inside Kernel there are some models useful for Blog and Map and one of they is the TimeManager. TimeManeger is a simple model that "manege the time": from django.db import models class TimeManager(models.Model): publishing_date = models.DateTimeField( 'Published at', default=timezone.now, ) updating_date = models.DateTimeField( 'Updated at', auto_now=True, ) timestamp = models.DateTimeField( auto_now=False, auto_now_add=True, ) class Meta: abstract = True Into Blog there is a model Post: from django.db import models from kernel.models import TimeManager class Post(TimeManager): title= slug= descrtiption= . . Into Map there is a model MyMap: from django.contrib.gis.db import models from kernel.models import TimeManager class MyMap(TimeManager): geom = models.PointField() title = . . Now, my doubt is this: is correct to use TimeManager both for geometric models and not geometric models? I know that GeoDjango inherit from Django his models but I don't know if my approach is correct. -
How do I properly link my JSON credentials file in Django settings.py?
I am using the Django-gcloud-storage library to allow my Django app to store images on GCS. I already created a bucket, GCS service account and downloaded a JSON keyfile according to the tutorial. However, saving an image to the Cloud storage raises this error: AssertionError at /showroom/create/ Credentials file not found ... /srv/showroom/views.py in form_valid images.save() … ▶ Local vars (showroom/create is the upload form). This is how I have linked to it in my settings.py GCS_PROJECT = "torque-xxx" GCS_BUCKET = "torque-xxx.appspot.com" GCS_CREDENTIALS_FILE_PATH = os.path.join(BASE_DIR, 'static', 'js', 'torque-xxx-02827c7cc0ad.json') # GCS_CREDENTIALS_FILE_PATH = '/static/js/torque-256805-02827c7cc0ad.json' ## This was my first try, didn't work # DEFAULT_FILE_STORAGE = 'google.storage.googleCloud.GoogleCloudStorage' DEFAULT_FILE_STORAGE = 'django_gcloud_storage.DjangoGCloudStorage' I'm very unfamiliar with Cloud storage and APIs, so forgive me if this is a novice question. :-) -
How can I execute a Python script in Django views with pk
I'm writing web application - product generator based on Django Forms. One of the functionality is creating a bill of materials for production according to options user pick up. I have python back-end script in two versions: functions and classes. They are running perfect but I can't handle how to execute them in Django Views. I prefere to keep business logic in usecases and import them to views. I've red a lot about it and as a newbie, still can't solve the problem. Should I use simple View, FormView, TemplateView, CreateView? # urls from django.urls import include, path from . import views urlpatterns = [ path('<int:pk>/detail/bom/', views.BillofMaterialsFormView.as_view(template_name='bom.html'), name='conveyorform_bom'), # html <form action="#" method="get"> <button name="bom" value="Submit">Get Bill of Materials</button> </form> # views from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView, DetailView, FormView from django.urls import reverse_lazy from .models import Conveyorform, ConveyorType, ConveyorModel from .forms import ConveyorformForm from conveyorform.usecases.bill_of_materials_creation import BillOfMaterials class BillofMaterialsFormView(FormView): template_name = 'bom.html' model = Conveyorform form_class = ConveyorformForm success_url = reverse_lazy('conveyorform_bom') def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): self.run_use_case(form) if not form.errors: return self.form_valid(form) return self.form_invalid(form) def run_use_case(self, form): usecase = BillOfMaterials( conveyorform_id=form.data['id'] ) usecase.get_conveyormodel_name() usecase.get_components_by_conveyormodel_name() usecase.create_components_table_for_instance() usecase.create_bill_of_materials_per_conveyorform_instance() Python script as classes … -
How to extend the locking/transaction between the views?
I have the functionality where I want to extend the transaction between two views. When a user clicks on 'Place Order' then the transaction begins and user is redirected to the merchant site to process the payment. In that case, where the control is not in the view where the transaction was written then How do I keep the locking alive unless the user returns on either of the defined callback URLs and then release it. (And, another story is when user don't even land on callback then is there a quick option to auto-release the lock if the transaction isn't completed in set time boundaries) -
Can't install matplotlib, pygame, and others after deleting anaconda
After a few days of anaconda being annoying with to use with idle, I have decided to delete anaconda with steps on this video https://www.youtube.com/watch?v=hm8AXAyEl4o So after uninstalling it, I decided to reinstall matplotlib, pygame, etc. The thing is this kind of error happened src/checkdep_freetype2.c:1:10: fatal error: 'ft2build.h' file not found #include <ft2build.h> ^~~~~~~~~~~~ 1 error generated. error: command 'gcc' failed with exit status 1 Installing django with pip3 install django worked, but for this one it doesn't seem to want to work, any solutions? -
Django Formset Error 'JournalVoucherEnteryForm' object has no attribute 'instance'
I'm working with dynamically add forms fields with jQuery.I'm using python 3.7 and Django 2.2.6 with postgrsql. I follow a tutorial and Github code. Here is link Youtube: https://www.youtube.com/watch?v=Tg6Ft_ZV19M Github code: https://github.com/shitalluitel/formset I got this error please check and help me to solve this problem. 'JournalVoucherEnteryForm' object has no attribute 'instance' Thanks Views.py def acc_journal(request): entriesFormset = modelformset_factory(JournalVoucherEntery, form=JournalVoucherEnteryForm, fields=('ajve_group','ajve_account','ajve_location','ajve_narration','ajve_currency','ajve_ex_rate','ajve_debit_amt','ajve_credit_amt','ajve_debit_base','ajve_credit_base','ajve_balance'), extra=2) form = AccountJournalVoucherForm(request.POST or None) formset = entriesFormset(request.POST or None, queryset=JournalVoucherEntery.objects.none(), prefix='journalvc') if request.method == 'POST': if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): journalv = form.save(commit=False) journalv.save() for entry in formset: data = entry.save(commit=False) data.ajve_journal_vc = journalv data.save() except IntegrityError: print('Error Encountered') context = { 'acc_journal_acti': 'active', 'main_header': 'Accounts', 'header_heading': 'Journal', 'acc_journals': JournalVoucher.objects.all(), 'form': form, 'formset': formset } return render(request, 'accounts/journal.html', context) models.py class JournalVoucher(models.Model): journal_voucher_id = models.AutoField(primary_key=True) acc_jurnl_vc_num = models.CharField(max_length=50, blank=False) acc_jurnl_vc_loc = models.CharField(max_length=50, blank=False) acc_jurnl_vc_date = models.DateField(auto_now=False) acc_jurnl_vc_ref_num = models.CharField(max_length=50, blank=True) acc_jurnl_vc_total_debit = models.DecimalField( max_digits=30, decimal_places=2, blank=True, null=True) acc_jurnl_vc_total_credit = models.DecimalField( max_digits=30, decimal_places=2, blank=True, null=True) acc_jurnl_vc_info = models.TextField(blank=True) acc_jurnl_vc_added_by = models.CharField(max_length=200, blank=True) jv_date_added = models.DateTimeField( default=datetime.now) def __str__(self): return str(self.journal_voucher_id) class Meta: db_table = 'journalvoucher' class JournalVoucherEntery(models.Model): ajve_id = models.AutoField(primary_key=True) ajve_journal_vc = models.ForeignKey( JournalVoucher, related_name='journalvc', on_delete=models.CASCADE) ajve_group = models.CharField(max_length=200) ajve_account = models.CharField(max_length=200) ajve_location = models.CharField(max_length=200, default='') ajve_narration … -
How to implement progressbar with ajax for a long celery task
How do I implement or check the progress of a celery task from ajax the display progress with a progress dialog... so user can initiate next operation on task completion. I am using python flask. Thank you -
I want to apply get_absolute_url in the update view
I want to use get_absolute_url in the update view below, but I'm not sure how to modify I hope the page is moved by get_absolute_url defined in the model after the update is complete. I tried this but failed return reverse (get_absoulte_url()) Do you know how to fix it? Thanks for letting me know view class modify_myshortcut_by_summer_note(UpdateView): model = MyShortCut form_class = MyShortCutForm_summer_note def form_valid(self, form): form = form.save(commit=False) form.save() return HttpResponseRedirect(reverse('wm:my_shortcut_list')) def get_template_names(self): return ['wm/myshortcut_summernote_form.html'] model class MyShortCut(models.Model): title = models.CharField(max_length=120) filename= models.CharField(max_length=50, blank=True) content1 = models.CharField(max_length=180, blank=True) content2 = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=False) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) type= models.ForeignKey(Type, on_delete=models.CASCADE) image = models.ImageField(upload_to='wm/%y%m%d', blank=True) def get_absolute_url(self,*args,**kwargs): return reverse('wm:my_shortcut_list')+'#shortcut_{}'.format(self.pk) def __str__(self): return self.title Should I fix this in view? or sholud i fix both view and model? if you knwo how to fix it thakns for let me know ~! return HttpResponseRedirect(reverse('wm: my_shortcut_list')) -
I am getting Template Does Not Exist at / when I'm running my server in Django
When I run server I get Template Does Not Exist at / for my index.html page. Same problem occurs for other templates as well. I've tried the solutions for previously asked similar questions like checking the template directory and installed apps in settings.py file but nothing seems working. Also, when I create a new project folder at some other location and copy all the code there, it usually works. This is my folder tree: Folder Tree I'm currently learning Django and new at stack overflow. Any help would be appreciated?