Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use membership in Django?
I am a beginner in Django and need to learn it for a local bot web application. Usually, modern MVC and MVM web frameworks such as ASP.net core and meteor have simple possibilities and tricks for membership (especially meteor). But I didn't find anything about this in Django. Does Django has these possibilities or I should download third-party packages? -
Problems with dict json in pytest drf
When I try to run my tests I receive the following error: self = HStoreField(required=False), value = '"key"=>"value"' def to_representation(self, value): """ List of object instances -> List of dicts of primitive datatypes. """ return { six.text_type(key): self.child.to_representation(val) if val is not None else None > for key, val in value.items() } E AttributeError: 'str' object has no attribute 'items' Looking on the internet I found some tips in the relation of json format, but I believe that is ok. My error test is: @pytest.mark.django_db def test_market_get_view(market): response = market response_get = client.get(f'/api/market/{response.data["id"]}/') assert response_get.status_code == 200 and my fixture: @pytest.fixture def market(client): response = client.post( '/api/market/', data={ 'name': "foo", 'address': "bar" 'attributes': {"key": "value"}, }, format='json', ) return response My other test (bellow) to PUT is ok. @pytest.mark.django_db def test_market_put(market): response = market response_put = client.post( f'/api/market/{response.data["id"]}/, data={ 'name': "foo foo", 'address': "bar bar" 'attributes': {"key 1": "value 1"}, }, format='json', ) assert response_put.status_code == 200 -
Django - How can I pass information from my google map to my view?
I am using Django and I have my map set up like this in my index.html: <div id="map"></div> <script> var map; function initMap(){ map = new google.maps.Map(document.getElementById('map'),{ center: {lat: {{clat}}, lng: {{clng}}}, zoom:12 }); } </script> <script src={{gmap_url}} async def></script> First I want to initiate the map with markers from my database which fit within the shown area. Then add the ability for the user to change the shown area (drag or zoom) and press a button which will query my database based on the newly shown area of the map. How can I tell what area my map is currently showing? I'd also like to query my database when the user clicks on a marker using information stored in that marker, how can I pass information to my view onclick? -
Bootstrap carousel template not working in django
I am trying to add bootstrap carousel to my home page in django app it is not changing slide. templates/posts/index.html {% extends "posts/base.html" %} {% block content %} <div class="container pt-3 mh-50"> <div class="bd-example"> <div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for fpost in featured_post %} {% if forloop.counter == 1 %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <img src="{{fpost.thumbnail.url}}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>{{fpost.title}}</h5> <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p> </div> </div> {% endfor %} </div> <ol class="carousel-indicators"> <li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleCaptions" data-slide-to="1"></li> <li data-target="#carouselExampleCaptions" data-slide-to="2"></li> </ol> </div> </div> </div> views.py def index(request): featured = Post.objects.filter(featured = True) #put this on carousel latest_post = Post.objects.order_by('-timestamp')[:6] startup_post = Post.objects.filter(category__title__iexact='startup')[0:3] opinion_post = Post.objects.filter(category__title__iexact='opinion')[0:3] # add a video field here context = { 'featured_post': featured, 'latest_post': latest_post, 'startup_post': startup_post, 'opinion_post': opinion_post } return render(request, 'posts/index.html', context) I am trying to render post with featured post true on carousel. It is giving me just static picture without any slideshow. -
Django Rest Framework | Writable multiple nested relations
I have some models and they are nested each others. I want to make a bulk create for 2 serializers , both have relations with other models. I looked at documentation on DRF but could not implement it in my code. #models.py class Address(): ... class Customer(): address = models.ForeignKey(Address, ...) class Painting(): ... class Product(): ... class Selling(): customer = models.ForeignKey(Customer, ...) products = models.ManyToManyField(Product, through='SellingProduct') class SellingProduct(): selling = models.ForeignKey(Selling, ...) product = models.ForeignKey(Product, ...) painting = models.ForeignKey(Painting, ...) Here is my serializers.py class AddressSerializer(): ... class CustomerSerializer(): address = AddressSerializer() ... class PaintingSerializer(): ... class ProductSerializer(): ... class SellingProductSerializer(): painting = PaintingSerializer() product = ProductSerializer() class SellingSerializer(): customer = CustomerSerializer() products = SellingProductSerializer(many=True) ... def create(self, validated_data): ... Thank you all in advance for any help! -
django bulk update field with incrementing integer
Is it possible to bulk update one field of a queryset with an incrementing integer (not id)? Like queryset.update(serial_no=i) where i=1,2,3... Django version = 1.11 -
How to debug connection from computer to server, server-side
My Centos 7 server is running apache 2.4.6, and is serving up a django webapp using mod_wsgi. My problem is that I cannot access the server url from my browser from another computer. I am not getting any errors from apache and its up and running no problem. I've set the error logs to 'debug' in the http.conf file but still no errors. I know the server is in fact connected to the internet by pinging it, i know it is listening on port :80 by running netstat -tunlp | grep 80. My settings.py has the url and the ip address under ALLOWED_HOSTS How do i debug this issue so i have an error i can look into? -
sending message to client using Django Channels from Celery tasks.py
I'm trying to use channels(v2.1.7) in django to send messages from server to client. When i execute the celery task below, my message is not being fetched in consumers.py(so not being sent to client) and surprisingly no error occures. I'm able to send message from consumers to client directly. But i couldn't manage to send from outside of consumers using async_to_sync(). (I tried to use async_to_sync method in standard django views.py and i had same problem) wololo/tasks.py @app.task(name='wololo.tasks.upgrade_building') def upgrade_building(user_id): os.environ['DJANGO_SETTINGS_MODULE'] = 'DjangoFirebaseProject.settings' from channels.layers import get_channel_layer channel_layer = get_channel_layer() print(channel_layer, "wololo") async_to_sync(channel_layer.send)('chat', { 'type': 'hello.message', 'message': 'hadiInsss', }) return True wololo/consumers.py from channels.generic.websocket import WebsocketConsumer import json from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect(self): async_to_sync(self.channel_layer.group_add)("chat", self.channel_name) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)("chat", self.channel_name) def hello_message(self, event): print("U MUST SEE THAT MSG") # Send a message down to the client self.send(text_data=json.dumps(event['message'])) the result that i have in celery terminal click to see celery terminal Thanks in advance -
Python Django PDF Flattening of Form Fields
I have a project where I need to fill out pre-made PDFs and the most logical solution that comes to mind to accomplish this is to make the pre-made PDFs into PDF forms so there are tags where input values are supposed to go, then I can look through the form tags in the PDF and line them up with a dynamic data dictionary I will create in the backend (for my code here the data dictionary to fill the fields is static). I have accomplished this. Overall, I took an image of a web form and then opened Acrobat and created a PDF form based on the fields seen in the image. My issue is that once I fill out the form programmatically, the input values are for lack of a better term ‘hidden’ from the view until a user clicks on the input field. In Acrobat, the values are completely hidden, and they do not print. When I move the PDF to my browser some of the fields show up, but some have the same issue. I have used pdfrw for this so far, and it works fine in terms of filling out the PDF form fields, but … -
how can i restrict users to some specific urls
I want to restrict users to access the payment and checkout pages by typing the url in address bar like "home/shop/checkout/" and "home/shop/payment/" I want to make these pages accessible only if either buy_now form is valid or items_buy_now form is valid urls.py path('payment/',views.payment,name='payment'), path('checkout/', views.checkout, name="checkout"), views.py def checkout(request): request.session.pop('data', None) messages.success(request,'Done.Thanks for using our services.') return redirect("shop:mycart") def payment(request): return render(request,'shop/payment.html') def buy_now(request,slug): if not request.user.is_authenticated: messages.info(request, 'You have to logged in first.') return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) product = Product.objects.get(active=True, slug=slug) if request.method == "POST": form = BuyerDeliveryForm(request.POST) if form.is_valid(): buyer = form.save(commit=False) buyer.save() return redirect('shop:payment') else: form = BuyerDeliveryForm() return render(request, 'shop/delivery_form.html', {'form': form, 'products': product}) def items_buy_now(request): if not request.user.is_authenticated: messages.info(request, 'You have to logged in first.') return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) if request.method == "POST": form = BuyerDeliveryForm(request.POST) if form.is_valid(): buyer = form.save(commit=False) buyer.save() return redirect('shop:payment') else: form = BuyerDeliveryForm() return render(request, 'shop/delivery_form.html', {'form': form}) -
Equivalent of .presence in Python
So, I've been using Ruby on Rails for some time, and I'm wondering if there is something like .presence in Python/Django. Presence returns the receiver if it is present otherwise returns nil. object.presence is equivalent to: object.present? ? object : nil For example, something like: state = params[:state] if params[:state].present? country = params[:country] if params[:country].present? region = state || country || 'US' becomes region = params[:state].presence || params[:country].presence || 'US' Anthony -
Python Error: object has no attribute 'META'
I have a bit of a problem with my view here as it is returning an error on django but I don't know what I have done wrong. My code is as follows in my view: from django.views.generic import TemplateView from django.shortcuts import render from community.models import Community class CommunityLanding(TemplateView): def get_context_data(request): template_name = 'community/landing.html' objects = Community.objects.all() context = { 'object': objects } return render(request, template_name, context) Can anyone point me in the right direction? -
Authentication django
Why self.request.user.is_authenticated() doesn`t work in this view? I got an error: 'bool' object is not callable? my view: class ArticleDetailView(DetailView, CategoryListMixin): model = Article template_name = 'mainapp/article_detail.html' def get_context_data(self, *args, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) context['articles'] = self.model.objects.all() context['article'] = self.get_object() context['comments'] = Comments.objects.filter(article=context['article']).order_by('-pub_date') if self.request.user.is_authenticated(): context['current_user'] = PersonalAccount.objects.get(user=self.request.user) return context -
Trying to make a working upload button to upload video files to a local video folder
I'm trying to make this function in python and I keep getting this error. RuntimeError: Model class registration.models.RegistrationProfile doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. what am I doing wrong? -
Saving a Django Project in VSCODE
I am currently setting up a project of Python Django in VS COde, I have created a Virtual Environment and worked on it for a day and after my day was done, i turned off VS code. And the next morning I do not the Virtual Env in my root! Is this a common thing or I just need to create Virtual Env everytime I start the project? Also, I did save my project to GIT! I feel like doing the same thing again each day kills more time and I would lost the track of work! Please someone help me! Thanking you in advance! -
How To Configure Django Authy For Two Factor Authentication
I have been researching Django 2 factor for the last couple days. I've finally come to a point where I've gotten the Django Twilio phone verification to work. Here is the code the working code... from authy.api import AuthyApiClient from django.conf import settings from django.shortcuts import render, redirect from .forms import VerifyForm, TokenForm authy_api = AuthyApiClient(settings.ACCOUNT_SECURITY_API_KEY) def SetupView(request): if request.method == 'POST': form = VerifyForm(request.POST) if form.is_valid(): request.session['phone_number'] = form.cleaned_data['phone_number'] request.session['country_code'] = form.cleaned_data['country_code'] authy_api.phones.verification_start( form.cleaned_data['phone_number'], form.cleaned_data['country_code'], via=form.cleaned_data['via'] ) return redirect('token_validation') else: form = VerifyForm() return render(request, 'registration/verify.html', {'form': form}) def token_validation(request): if request.method == 'POST': form = TokenForm(request.POST) if form.is_valid(): verification = authy_api.phones.verification_check( request.session['phone_number'], request.session['country_code'], form.cleaned_data['token'] ) if verification.ok(): request.session['is_verified'] = True return redirect('verified') else: for error_msg in verification.errors().values(): form.add_error(None, error_msg) else: form = TokenForm() return render(request, 'registration/token_validation.html', {'form': form}) def verified(request): if not request.session.get('is_verified'): return redirect('phone_verification') return render(request, 'registration/verified.html') Using the code above along with specifying the ACCOUNT_SECURITY_API_KEY in my settings.py file is all that was required to get the code above to pass a 4 digit code to my phone. Progress... However, what I'm really trying to accomplish is to leverage the AUTHY app to provide the login code....I've looked at the following page...https://www.twilio.com/docs/authy/quickstart/two-factor-authentication-python-django#linkcode And the code does … -
how to structure a mutation in vuex orm graphql to connect with django graphql backend
I'm having problems making queries and creating / updating / deleting things in django graphql through the graphql plugin of vuex orm. From the interface provided by django to execute queries, I can perfectly use my mutations and consult any particular data or any collection of them. I'm going to write an example of how I create an object called "TipoProducto" from the django interface: mutation myMutation { createTipoProducto(input: {nombre:"Pizza", descripcion:"foobar"}) { tipoProducto {nombre, descripcion} status } } This code will return the object with its attributes and a status 200 if it was successful. The Django classes in the schema: class TipoProductoNode(DjangoObjectType): class Meta: model = TipoProducto filter_fields = ['nombre', 'productos'] interfaces = (relay.Node, ) class TipoProducto(graphene.ObjectType): nombre = graphene.String() descripcion = graphene.String() class CreateTipoProducto(graphene.ClientIDMutation): class Input: nombre = graphene.String(required=True) descripcion = graphene.String(required=True) tipo_producto = graphene.Field(TipoProducto) status = graphene.Int() ok = graphene.Boolean() def mutate_and_get_payload(self, info, nombre, descripcion, client_id_mutation=None): tipo_producto = TipoProductoNode._meta.model(nombre=nombre, descripcion=descripcion) tipo_producto.save() return CreateTipoProducto(tipo_producto=tipo_producto, ok=bool(tipo_producto.id), status=200) My model in vuex orm: import { Model } from '@vuex-orm/core'; import Product from './Product' export default class TipProd extends Model { static entity = "tipProds" static fields () { return { id: this.increment(), nombre: this.attr(''), descripcion: this.attr(''), producto: this.hasMany(Product, 'tipProd_id') } … -
Can someone help me i get an Attribute Error in Django?
import django import sys django.setup() import os I think what i've imported is good, i think maybe it comes from my urls.py but i don't know what to add to it BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'm0i@n*1e&b6@5w7^#=h712+z#-jj2&ynbi30j0z$yf#t+@x1s#' ALLOWED_HOSTS = ['192.168.0.101', 'localhost', '127.0.0.1', '[::1]'] I allowed hosts to try debbugging INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite', 'polls' ] Installed apps of Django MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Middleware of Django My error come from here ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] Settings of Django: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' Backend authentification: AUTHENTICATION_BACKENDS = ('apps.apployment_site.auth.CustomAuth',) I can't understand why i get an Attribute Error in my console when i launch the server ! -
What is a modern reliable way to store total user clicks during their time on a webpage?
I apologize in advance if this is too "vague" for SO, but I'm at a loss at how to do what I'm trying to do and feel like I've been running in circles the past week. TL;DR - Is there a reliable, modern, cross-platform way to determine when a user is "done" viewing a webpage? Documented below is my current thought process so far. Background: I'm working on a small project for my girlfriend where I make a single-page Django app that contains a single picture of our cat. The picture changes when you tap it, randomly choosing another from the pool of pictures. It's a cute idea, but I wanted to make it more fun and engaging (since she's sending the website to all her friends) so I decided include a "clicks high score" beneath the picture. I've got all the pieces in the right place: document.cookie["clickcount"]. models.ClickLog.number_of_clicks and models.ClickLog.time_posted. views.log_clicks that POSTs a new ClickLog object and resets the cookie, and a corresponding AJAX function that calls this view. a display of the current "high score" of clicks per session on the webpage determined by max(i.number_of_clicks for i in ClickLog.objects.all()). However, the one thing I'm having trouble figuring … -
Attempting to send email in django, HTML being passed with email address
I'm attempting to send an email as a action when a form is sent. I'm doing so with the following function: def send_emails(first_name, last_name, to_email): #get template htmly = get_template('email_templates/welcome.html') #create a context d = {'first_name':first_name, 'last_name':last_name} subject, from_email, to = 'Subject line', settings.EMAIL_HOST_USER, to_email #pass the context to html template html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() I'm calling this function like so: send_emails(first_name, last_name, email) The fields being passed as an argument are obtained from my form, like so: email = request.POST.get('email', False) first_name = request.POST.get('first_name', False) last_name = request.POST.get('last_name', False) When attempting to send, I get the following error: SMTPRecipientsRefused at /url/ {'test@example.com': (404, b'4.5.2 <=?utf-8?q?jake?=>: Sender address rejected: need fully-qualified address')} To me, it looks like HTML is attempting to be sent with the address, but I am unsure why. The form data gets saved in my database as it should without issue, so I am unsure why the same data would be causing a problem here. How can I troubleshoot? -
Adding style in django form definition for extended forms that don't correspond to model
I have a django form I am using to process orders and card payments. I have extended my form in my view to have credit card fields, as these fields do not correspond to my model, as I am not saving them in my database. In my forms.py, I am specifying the class attribute for my form fields like so: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'email', 'address', 'zipcode', 'city', 'state'] widgets = { 'first_name': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Last Name'}), 'email': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'E-Mail'}), 'address': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Address'}), 'zipcode': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Zipcode'}), 'city': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'City'}), 'state': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'State'}), } I understand it is frowned upon to mix presentation and business logic, however I have a strict deadline, and I am working with a paid tempalte with advanced CSS that I do not entirely understand, so this is the method I have found to work so far. I will revise this at a later stage to add the class via a template … -
How do I make Django unit tests check M2M DB constraints?
Say I have this model definition: class Foo(Model): ... class Bar(Model): some_m2m_field = ManyToManyField(Foo) and this code: bar = Bar.objects.create() bar.some_m2m_field.set(an_id_array_with_some_invalid_pks) When I run that normally, the last line will, as it should, throw an IntegrityError. However, if I run the same code from a django unit test, the last line will NOT throw an error. It instead will wait until the tear_down() phase of the test to throw the IntegrityError. How do I fix that? I suppose that's configurable, but I haven't been able to find it... Follow-up question: Ultimately, I need to handle the case when there are bad IDs being passed to the m2m_field.set() method (and I need unit tests that verify that bad IDs are being handled correctly, which is why the delayed IntegrityError in the unit test won't work). I know I can find the bad IDs by looping over the array and hitting the DB one for each ID. Is there a more efficient way to find the bad IDs or (better) simply tell the set() method to ignore/drop the bad IDs? -
Combined datetime object created is not timezone aware
I have a form that takes a date field and a time field (have to be separately due to how the form and javascript functions are structured). In my view I combine these field to make a datetime, as I know that can be timezone aware. When I save it, it saves as-is, without converting to UTC in my database. I believe my timefield being an input from a dynamically generated dropdown (10:00 am, 11:00 am, etc) might be causing this, but am unsure. I would greatly appreciate any help with making my datetime object save in UTC. forms.py class BookedForm(forms.ModelForm): booked_instrument = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'})) booked_length = forms.ChoiceField(choices=length_list, widget=forms.Select(attrs={'class' : 'form-control', 'id' : 'length', 'required' : 'True'})) booked_date = forms.DateField(input_formats=['%b. %d, %Y'], widget=forms.DateInput(attrs={'class': 'form-control', 'name' : 'date'})) booked_time = forms.ChoiceField(choices=time_list, widget=forms.Select(attrs={'class' : 'form-control', 'id' : 'time', 'name' : 'time', 'required' : 'True'})) views.py def book_lesson(request, lesson_id): if request.user.is_authenticated and request.user.time_zone: activate(request.user.time_zone) else: deactivate() lesson = Lesson.objects.get(id=lesson_id) if request.method == 'POST': form = BookedForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.booked_datetime = datetime.combine(book.booked_date, book.booked_time) book.student_user = request.user book.teacher_user = lesson.user book.save() messages.success(request,'Lesson was successfully booked!') return redirect('/teacher/dashboard') else: form = BookedForm() form = BookedForm() context = {'form' : form, 'lesson' : … -
Cannot implement star rating for restraunt review form django
I am currently working on a restaurant review website on Django, but I am having difficulties with implementing star ratings to my reviews. Here is my Django code: detail.html <form method="POST" class="post-form"> <fieldset class="rating"> <input type="radio" id="star5" name="rating" value="5" /><label class = "full" for="star5" title="Awesome - 5 stars"></label> <input type="radio" id="star4half" name="rating" value="4half" /><label class="half" for="star4half" title="Pretty good - 4.5 stars"></label> <input type="radio" id="star4" name="rating" value="4" /><label class = "full" for="star4" title="Pretty good - 4 stars"></label> <input type="radio" id="star3half" name="rating" value="3half" /><label class="half" for="star3half" title="Meh - 3.5 stars"></label> <input type="radio" id="star3" name="rating" value="3" /><label class = "full" for="star3" title="Meh - 3 stars"></label> <input type="radio" id="star2half" name="rating" value="2half" /><label class="half" for="star2half" title="Kinda bad - 2.5 stars"></label> <input type="radio" id="star2" name="rating" value="2" /><label class = "full" for="star2" title="Kinda bad - 2 stars"></label> <input type="radio" id="star1half" name="rating" value="1half" /><label class="half" for="star1half" title="Meh - 1.5 stars"></label> <input type="radio" id="star1" name="rating" value="1" /><label class = "full" for="star1" title="Sucks big time - 1 star"></label> <input type="radio" id="starhalf" name="rating" value="half" /><label class="half" for="starhalf" title="Sucks big time - 0.5 stars"></label> </fieldset> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default" style="width: 100px!important; margin-left: 40%!important; border: none!important; background-color:#ffbf24!important; outline: 0!important; color: white!important;">Send</button> </form> {% else %} <center><h6 … -
Executing a Task programatically Django-Viewflow
im trying to run a viewflow flow entirely by code. I have succesfully created a task this way but I have failed to execute the task that follows the creation of the process. I've tried using de handler aproach given in the oficial view-flow documentation but I don't know how to do it properly. flows.py from __future__ import unicode_literals from viewflow import flow , Task from viewflow.base import this, Flow from viewflow.flow.views import CreateProcessView, UpdateProcessView, CancelProcessView, AssignTaskView, DetailProcessView from viewflow.lock import select_for_update_lock from .models import DeliveryProcess, Revisiones from viewflow import frontend from . import views from formtools.wizard.views import SessionWizardView @flow.flow_start_func def create_flow(activation, campos_proceso, **kwargs): activation.process.asignador = campos_proceso['asignador'] activation.process.ejecutor = campos_proceso['ejecutor'] activation.process.tipo_de_flujo = campos_proceso['tipo_de_flujo'] activation.process.estado_del_entregable = campos_proceso[ 'estado_del_entregable'] activation.process.save() activation.prepare() activation.done() return activation @frontend.register class Delivery_flow(Flow): process_class = DeliveryProcess start = flow.StartFunction(create_flow).Next(this.execution_received_handler) execution_received_handler = ( flow.Function( this.on_execution_recived, task_loader=this.get_shipment_handler_task) .Next(this.end) ) ejecutar = ( flow.View( UpdateProcessView, ).Assign(lambda act: act.process.ejecutor ).Next(this.end) ) end = flow.End() @flow.flow_func def on_execution_recived(self, activation): activation.process.revisor = process_fields['revisor'] activation.process.save() activation.prepare() activation.done() def get_shipment_handler_task(self, flow_task, ejecutar): return Task.objects.get(process=ejecutar.process) views.py from ..Flujo import flows from datetime import datetime from django.views import generic from django.shortcuts import render from .models import Revisiones, DeliveryProcess, Entregable from viewflow.flow.views import CreateProcessView, UpdateProcessView from viewflow.decorators import flow_start_view, …