Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to put emails in sent folder with django send_mail()?
Iam using djangos simple mail send function from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) how can I use this, to put the sent emails to the mailbox sent folder? -
Django CSV Export - Foreingkey
Export to CSV is working properly... BUT the only thing is that the model fields which are defined via a ForeignKey are outputted as their PK... How can I solve this? Below the code in my views.py : def export_cashflow_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="cashflow.csv"' writer = csv.writer(response) writer.writerow(['date', 'type', 'amount', 'fund', 'description']) cashflows = CashFlow.objects.all().values_list('date', 'type', 'amount', 'fund', 'description') for cashflow in cashflows: writer.writerow(cashflow) return response the field fund is a Foreignkey to the model Fund. many thanks all ! -
Django. Add, edit and delete on django
Tell me, please, what will the function for adding, editing and deleting listings look like? First, how to correctly register the current user in this function? Secondly, how to ensure that only the current user can delete and edit listings? At the moment, this can be done by anyone, even an unregistered user. def listing_delete(request, listing_id): listing = Listing.objects.get(id=listing_id) listing.delete() return redirect('index') def listing_edit(request, listing_id): form = ListingForm(instance = Listing.objects.get(id = listing_id)) if request.method == "POST": form = ListingForm(request.POST, request.FILES, instance = Listing.objects.get(id = listing_id)) if form.is_valid(): listing = form.save() return redirect('listing', listing_id) else: ListingForm(instance=Listing.objects.get(id = listing_id)) return render(request, 'listings/listing_edit.html', {'form': form}) def listing_add(request): form = ListingForm() if request.method == "POST": form = ListingForm(request.POST, request.FILES) if form.is_valid(): listing = form.save(commit=False) listing.realtor = request.user listing.save() return redirect('dashboard') return render(request, 'listings/listing_add.html', {'form': form}) I understand that listing.realtor = request.user is wrong, because there must be an instance of a realtor, but I didn’t understand how to do it correctly. It's molel Listing: class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риэлтор') region = models.CharField(default="Чуйская", max_length=100, verbose_name='Область') city = models.CharField(default="Бишкек", max_length=100, verbose_name='Город') district = models.CharField(blank=True, max_length=100, verbose_name='Район') title = models.CharField(max_length=200, verbose_name='Заголовок') address = models.CharField(blank=True, max_length=200, verbose_name='Адрес') description = models.TextField(blank=True, verbose_name='Описание') stage = models.IntegerField(blank=True, verbose_name='Этажность') rooms … -
PyQt5 : How to Upload Image using HTTP Request ( Multipart-form )
currently I am working in a project to create a seller application where the seller can upload the menu picture and some additional information such as the price and the name of the menu. but I stuck at the POST request method because in this time I have to upload an image with some text data instead of only text data. I am using PyQt5. This is my API web server. I am using Django Rest Framework to build that. [ I have tried to use this answer: here This is my implementation to that method: def upload(self): file1 = QFile("/home/shalahuddin/Desktop/jamu.jpg") file1.open(QFile.ReadOnly) url = "http://127.0.0.1:8000/api/menu/" nama = QByteArray() nama.append("ABCD") harga = QByteArray() harga.append(str(999)) kategori = QByteArray() kategori.append(str(0)) ada = QByteArray() ada.append(str(True)) idseller = QByteArray() idseller.append(str(2)) data = {"name": nama, "price": harga, "category": kategori, "availability": ada, "sellerID": idseller} files = {"image": file1} multipart = self.construct_multipart(data, files) request_qt = QNetworkRequest(QUrl(url)) request_qt.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, 'multipart/form-data; boundary=%s' % multipart.boundary()) self.manager = QtNetwork.QNetworkAccessManager() self.manager.finished.connect(self.handleResponseMenu) self.manager.post(request_qt, multipart) def handleResponseMenu(self, reply): er = reply.error() data = json.loads(str(reply.readAll(), 'utf-8')) file = open("/home/shalahuddin/Desktop/testfile.txt", "w") file.write(str(reply)) if er == QtNetwork.QNetworkReply.NoError: bytes_string = reply.readAll() data = json.loads(str(bytes_string, 'utf-8')) # print(data) QMessageBox.information(self, "Menu", "Upload Success!") else: errorMessage = "Error occured: " + str(er) + … -
Celery + Redis - Django blocks when triggering a task with delay
I have setup Celery on my Django project with Redis. The scheduled tasks are running without issues. The problems come when triggering an async task using the delay(). The execution stops and it's like is blocked in the loop of kombu.utils.retry_over_time. I checked and Redis is up and running. I don't really know how to debug this issue. Here's some package versions: Django==2.1.2 celery==4.2.1 django-celery-beat==1.4.0 django-celery-results==1.0.4 redis==3.2.0 kombu==4.4.0 The settings: CELERY_REDIS_HOST = 'localhost' CELERY_REDIS_PORT = 6379 CELERY_REDIS_DB = 1 # # Redis DB number, if not provided the default will be 0 CELERY_REDIS_PASSWORD = '' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_BROKER_URL = 'redis://{host}:{port}/{db}'.format(host=CELERY_REDIS_HOST, port=CELERY_REDIS_PORT, db=CELERY_REDIS_DB) CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' # Result serialization format CELERY_TASK_SERIALIZER = 'json' # String identifying the serializer to be used CELERY_BROKER_TRANSPORT_OPTIONS = { 'visibility_timeout': 3600, # 1 hour, default Redis visibility timeout } -
How to annotate a Django QuerySet aggregating annotated Subquery
I have a few Django models with a FK relationship between them: from django.db import models class Order(models.Model): notes = models.TextField(blank=True, null=True) class OrderLine(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() price = models.DecimalField(max_digits=8, blank=True, decimal_places=2) Given an OrderLine you can calculate its total as quantity by price: def get_order_line_total(order_line): return order_line.quantity * order_line.price Given an Order you can calculate its total as the sum of its order lines totals: def get_order_total(order): order_total = 0 for orderline_for in order.orderline_set.all(): order_total += (order_line_for.quantity * order_line_for.price) return order_total I want to annotate that totals in querysets so I can filtrate them, sort them, etc. For the OrderLine models I found it pretty straight forward: from django.db.models import F, FloatField, Sum annotated_orderline_set = OrderLine.objects.annotate(orderline_total=Sum(F('quantity') * F('price'), output_field=FloatField())) Now I want to annotate the total in an Order.objects queryset. I guess I would need to use a Subquery but I can't make it work. My guess is (Not working): from django.db.models import F, FloatField, OuterRef, Subquery, Sum Order.objects.annotate( order_total=Subquery( OrderLine.objects.filter( order=OuterRef('pk') ).annotate( orderline_total=Sum(F('quantity') * F('price'), output_field=FloatField()) ).values( 'orderline_total' ).aggregate( Sum('orderline_total') )['orderline_total__sum'] ) ) # Not working, returns: # ValueError: This queryset contains a reference to an outer query and may only be used in … -
Is it safe to use GZip Middleware in Django >= 1.10?
I am looking to enable text compression in Django. The performance docs reference GZip Middleware as the current solution for text compression. However, it comes with a stern warning: GZipMiddleware Compresses responses for all modern browsers, saving bandwidth and transfer time. Note that GZipMiddleware is currently considered a security risk, and is vulnerable to attacks that nullify the protection provided by TLS/SSL. See the warning in GZipMiddleware for more information. A couple of questions: Are there any text compression alternatives I can use with Django that are not subject to security risks? If I use CSRF tokens when using POST and I have CSRF Middleware enabled am I safe? Again, via the docs: Changed in Django 1.10: In older versions, Django’s CSRF protection mechanism was vulnerable to BREACH attacks when compression was used. This is no longer the case, but you should still take care not to compromise your own secrets this way. -
How to get request parameters from an encoded URL in Django?
I am using Django Rest Framework. The API receives GET requests with json objects encoded into the URL. For example: /endpoint?%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D Where the decoded parameters are { "foo":["bar","baz"] } I can't find anything in the documentation for Django or DRF pointing to how the framework can handle this so that I get a QueryDict with the json objects in it by doing something like: request.query_params # Should yield a dict -> {foo=[bar,baz]} How can I decode JSON encoded URLs in Django Rest Framework? Note that my actual parameters are much more complex. Using POST is not an because the caller relies heavily on caching and bookmarking -
Not able to create object in Django
I am new to Django and I am struggling to create and save an object based on a model in my apps models.py The code I am using: search = Searches(product=product, no_of_sellers=len(listed), valid_search=1, best_price=listed[0]['cost'], worst_price=listed[-1]['cost']) search.save() And my models.py looks like this: class Searches(models.Model): id = models.AutoField(primary_key=True) product = models.CharField(max_length=8) no_of_sellers = models.IntegerField() valid_search = models.BooleanField() best_price = models.FloatField(blank=True) worst_price = models.FloatField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) Additionally, print statements that I have after search.save() are not executed, so it appears the object creation is failing and then not executing the rest of the function. I am no getting any error messages in the console and nothing is happening in my Database. As far as I can see, I'm doing exactly as stated in the Django Docs example: p = Person(name="Fred Flintstone", shirt_size="L") p.save() I'm using a MySQL database, Python 3.6, and Django 2.1.7. Any help on this would be greatly appreciated! -
Object of type 'PhoneNumber' is not JSON serializable
I am trying to save PhoneNumberField in python dictionary, it is giving this error Object of type 'PhoneNumber' is not JSON serializable. it also did same for student_data_dict = { 'first_name':stud_data.firstname, 'last_name':stud_data.lastname, 'gender':stud_data.gender, 'school':stud_data.school.id, 'origin':stud_data.origin, 'dob':stud_data.dob, 'nationality':stud_data.nationality, 'place_of_birth':stud_data.place_of_birth, 'Religion':stud_data.Religion, 'level':stud_data.level, 'any_allergies':stud_data.any_allergies, 'address':stud_data.address, 'phone1':stud_data2.phone1, 'phone2':stud_data2.phone2, } Why is this so?. Please your help on this guys -
Connect domain to pythonanywhere
I did a webpage in pythonanywhere and I'm using the subdomain they gave me (username.pythonanywhere.com) but I have a domain that I want to use for this project (I bought the domain in domain.com). I already expanded my plan in pythonanywhere to put my own domain but I've been trying without sucess. This is the documentation that I've been reading. pythonanywhere documentation Image of the Domain.com panel Is the first time that I make this and a pretty confused. -
How can I sticking django rand reactjs together with SEO and making sure that your wesite will have a big traffic
I want to ask if it is possible to do these two things and keeping them all optimized: website which is having a big traffic and its performance not impaired, alongside SEO all together, if this is possible, how to maintain them at the same time with django and reactjs. I tried to research about it and any documentation i found didn't help me at all. I read this document https://www.valentinog.com/blog/tutorial-api-django-rest-react/ and this question SEO in ReactJS when used with Django unfortnately didn't get any clue. So, I need a help, wether you guide me or you show suggest me any document, it would be of a great use! -
angular redirect to backend app on same host
I've got an app with Angular in the front end and Django in the backend on different ports on the same host, and for authentication, I have this piece of code in my userService.js: authenticateUser: function() { return $window.location.href = 'https://myhost:backend_port/oidc/auth/request/' }, but when I visit my app, it's giving me "cannot GET /oidc/auth/request/" so I think the front end is trying to handle it when it should be going to the backend. Do I need to add the 'location' in the Nginx config for the backend? Here are my current 'locations': location / { proxy_pass https://deets-lnx02.mitre.org:3004; } location /static/ { root /home/MITRE.ORG/pmweeks/deets/deets-env/recruiting/server; } location /media/ { root /data/deets/pmweeks/media; } location /api { -
React Frontend Post/Put Requests to Django Backend Permission Problem
I have full CRUD on my Django backend and am now trying to have full CRUD on my React frontend. Successfully created the form and was able to assign values to a new post and console.log it. When I attempted to post to backend I first got a 403 (Not Allowed, but then I changed my REST_FRAMEWORK from 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' to 'rest_framework.permissions.AllowAny' and am now getting 405 (Method Not Allowed). Some Code Backend REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny' ] } Frontend handleFormSubmit = (event, requestType, circuitID) => { event.preventDefault(); const name = event.target.elements.name.value; const description = event.target.elements.description.value; console.log(name, description) switch ( requestType ) { case 'post': return axios.post('http://localhost:8000/api/', { name: name, description: description }) .then(res => console.log(res)) .catch(error => console.log(error)); case 'put': return axios.put(`http://localhost:8000/api/${circuitID}/`, { name: name, description: description }) .then(res => console.log(res)) .catch(error => console.log(error)); } } url patterns in app backend urlpatterns = [ path('', circuit_list.as_view()), path('create/', circuit_create.as_view()), path('<pk>', circuit_detail.as_view()), path('<pk>/update/', circuit_update.as_view()), path('<pk>/delete/', circuit_delete.as_view()), path('workout/create/', workout_create.as_view()), path('workout/', workout_list.as_view()), path('workout/<pk>', workout_detail.as_view()), path('<pk>/update/', workout_update.as_view()), path('<pk>/delete/', workout_delete.as_view()), ] url patterns in Django urlpatterns = [ path('admin/', admin.site.urls), path('api-auth', include('rest_framework.urls', namespace='rest_framework')), path('api/', include('circuit.api.urls')) ] What I have done … -
django.core.exceptions.ImproperlyConfigured: WSGI application 'api.wsgi.application' could not be loaded; Error importing module
""" Django settings for api project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'v%l%ysx2z^m572s+1g2tap_5k=^2@jl_yucov4gw69pw_ot!9$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'djoser', ] 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'api.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 = 'api.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 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', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True … -
Why does django post stops working over https? It's working over http
So, When I'm trying to change django production server from http to https, by using these settings: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SESSION_SAVE_EVERY_REQUEST = True SESSION_COOKIE_NAME = 'SRSession' The POST requests from the browser just stops working(not even the login from the admin panel), but the get requests are working fine and the site have a valid ssl ceritifcate, I'm using OpenLiteSpeed This is how the request looks in chrome network tab and it goes on like this until I get a timeout error. If I use HTTP on the production server to get the cookies then I use HTTPs the GET request are working fine. -
Django cache framwework - get_or_set()
https://docs.djangoproject.com/en/2.1/topics/cache/ I dont really understand cache.get_or_set(key, default, timeout=DEFAULT_TIMEOUT, version=None) From the name and how i understand it, it gets OR sets the cache. from django.core.cache import cache def test(): print("function") return "some string" If i now run >>> cache.get_or_set('a', test(), 60) function 'some string' And immediatly again >>> cache.get_or_set('a', test(), 60) function 'some string' So, it always sets the cache. So it's more like get_and_set() instead of get_or_set() Or am i missing something? -
Giving admin users flexibility on defining calculation formula for web app... is it a good idea?
I'm designing a Django project, for which I'd like to give administrators flexibility on defining certain calculation formulas. Although I can assume that admins won't do stupid things break the system by defining unappropriate formulas, I'm feeling very uncomfortable on the ways this freedom can be implemented: Saving the code of the formula to the database, fetch it when the formula is needed and apply it. Allowing admin users to write Python modules, save them to a preset location, save the module and function name in the database, fetch it when the formula is needed and apply it. Both ways look like huge security holes to the system, and I'd like to avoid that at all costs... but the only way I can think to prevent code injection attacks (is that the appropriate name?) is: Close the system: No user can define formulas, and If an admin needs to apply a custom formula, then (s)he would need to ask the system administrator to write, test and implement it. So, in short: Is there a way to give a little group of users (administrators) the freedom (and power) to define custom functions that would be applied under certain conditions? If there … -
How to create django model without primary key column and avoiding Id default column
I am using SQL Server as a default database. I replicated the SQL Server table in the model using inspectdb command. Now, SQL Server table does not have any primary key column. So, django model automatically creates id as a primary key and giving me error while posting the data. column "id" does not exist Is there any work around to remove id at the same time not defining primary key on any columns of the model? from django.db import models class ImptCustomer(models.Model): customerid = models.IntegerField(db_column='CustomerId', blank=True, null=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=50, blank=True, null=True) # Field name made lowercase. phonenumber = models.CharField(db_column='PhoneNumber', max_length=20, blank=True, null=True) # Field name made lowercase. emailaddress = models.CharField(db_column='EmailAddress', max_length=100, blank=True, null=True) # Field name made lowercase. streetline = models.CharField(db_column='StreetLine', max_length=50, blank=True, null=True) # Field name made lowercase. city = models.CharField(db_column='City', max_length=50, blank=True, null=True) # Field name made lowercase. statecode = models.CharField(db_column='StateCode', max_length=5, blank=True, null=True) # Field name made lowercase. postalcode = models.CharField(db_column='PostalCode', max_length=20, blank=True, null=True) # Field name made lowercase. customer_key = models.IntegerField(db_column='Customer_Key', blank=True, null=True, editable = False) # Field name made lowercase. class Meta: managed = False db_table = 'IMPT_Customer' -
Django, my for loop is not showing in include template
Hello I am a beginner with Django and Python. I am currently in my project using a for loop in the template but it does not show anything. Could someone help me and explain me what I am doing wrong? models.py class ImageCategory(models.Model): name = models.CharField(blank=False, max_length=120) created_at = models.DateTimeField(default=datetime.now(), blank=True) class Meta: verbose_name_plural = "image categories" def __str__(self): return self.name views.py from .models import ImageCategory def LibraryOverviewView(request): return render(request, 'library_overview.html', {'image_categories': ImageCategory.objects.all()}) library_overview.html library_overview is included in base.html, not extended. {% for category in image_categories %} <a class="tb-btn tb-btn-label tb-btn-radio no-bg slide-forward">-> {{ category.name }}</a> {% empty %} <p> There are no Categories yet </p> {% endfor %} urls.py urlpatterns = [ url(r'^library_overview/', views.LibraryOverviewView, name='LibraryOverviewView'), -
Django FactoryBoy - random choice not working with LazyFunction
I'm building a number of tests for our django application and I'm using FactoryBoy The Profile model has a gender field which is defined as follows: class Profile(models.Model): GENDER_CHOICES = ( (u'm', _(u'Male')), (u'f', _(u'Female')), ) gender = models.CharField( max_length=2, choices=GENDER_CHOICES, verbose_name=_("Gender"), null=True, blank=True ) I wanted to randomize the value of this field in factory boy with the following line of code: gender = factory.LazyFunction(random.choice(['f', 'm'])) However, this throws a TypeError: 'str' object is not callable error Using an old blogpost I then tried the following solution, which worked: gender = factory.LazyAttribute(lambda x: random.choice(['f', 'm'])) This solved the problem, but its unclear to me why it did. The documentation for factory.LazyFunction states that: The LazyFunction is the simplest case where the value of an attribute does not depend on the object being built. It takes as argument a method to call (function, lambda…); that method should not take any argument, though keyword arguments are safe but unused, and return a value. It was my understanding that random.choice(['f', 'm']) constituted a method call and thus should work as I expected it to. But as it did not my understanding of LazyFunction is clearly flawed and I was hoping somebody could … -
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 recieve the following error. type object 'Task' has no attribute 'objects' 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 … -
What is 'batteries included' philosophy in Django?
I recently read this sentence in Django documentation, but couldn't understand the meaning, please explain it in simple words. Django aims to follow Python's “batteries included” philosophy. -
Entered fields not saving to model
I'm trying to create a pastebin clone in Django. I've created a paste app, and a Paste class in my models.py class Paste(models.Model): SYNTAX_CHOICES = { (0, "Plain"), (1, "Python"), (2, "HTML"), (3, "SQL"), (4, "Javascript"), (5, "CSS"), } content = models.TextField() title = models.CharField(blank=True, max_length=30) syntax = models.IntegerField(choices=SYNTAX_CHOICES, default=0) poster = models.CharField(blank=True, max_length=30) timestamp = models.DateTimeField(default=datetime.datetime.now, blank=True) class Meta: ordering = ('-timestamp',) def __unicode__(self): return "%s (%s)" % (self.title or "#%s" % self.id, self.get_syntax_display()) @permalink def get_absolute_url(self): return ('django.views.generic.list_detail.object_detail', None, {'object_id': self.id}) class PasteAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'title', 'poster', 'syntax', 'timestamp') list_filter = ('timestamp', 'syntax') admin.site.register(Paste, PasteAdmin) In one of my templates, I have a form that requires the user enter the required details(name of paste, syntax, paste itself). {% extends "base.html" %} {% block content %} <h1>Your user is</h1> {{ request.user }} {{ request.user.is.authenticated }} <form action="" method="POST"> {% csrf_token %} Title: <textarea rows="1" cols="50" placeholder="Title of paste"></textarea><br> Syntax: <textarea rows="1" cols="50" placeholder="Enter syntax"></textarea><br> {{ form.content }}<br> <textarea rows="4" cols="50" placeholder="Please enter the text you'd wish to paste..."></textarea> <input type="submit" name="submit" value="Paste" id="submit"> {% endblock content %} But when the information is entered, the data is not saved when checking the admin. What am I missing to save … -
mod_wsgi: ImportError: No module named 'encodings' deploying django app
I have looked here for answers to this error: mod_wsgi: ImportError: No module named 'encodings' and it seems i get this error because of permissions not being set. But to me it looks like all of the permissions are set correctly Here is my file structure: home └── user └── projects └── myapp ├── app │ ├── <All Code for Webapp including static dir> ├── env (virtualenv) ├── manage.py ├── new │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── requirements.txt Here is my wsgi.conf file located in /etc/httpd/conf.d Alias /static /home/user/projects/myapp/app/static <Directory /home/user/projects/myapp/app/static> Require all granted </Directory> <Directory /home/user/projects/myapp/new> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/home/user/projects/myapp python-home=/home/user/projects/app/env/lib/python3.6/site-packages user=<user> WSGIProcessGroup myapp WSGIScriptAlias / /home/user/projects/myapp/new/wsgi.py Now here are what the permissions say when i'm in my home directory: $ ls -l total 0 drwxrwxr-x. 5 <user> <group> 41 Mar 7 14:53 project this permission is the same down to projects, now my permissions when i get the myapp directory are as follows: drwxrwxr-x. 7 <user> <group> 4096 Mar 7 13:18 app drwxrwxr-x. 5 <user> <group> 56 Mar 7 14:42 env -rwxrwxr-x. 1 <user> <group> 535 Mar 5 13:33 manage.py drwxrwxr-x. 3 <user> <group> 110 Mar 7 14:27 …