Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Python : Using json.loads in the template
I am trying to use json.loads in my template in order to get a python's dictionnary. But unfortunately, i encounter the same error : Could not parse the remainder: ' = json.loads(entry.saved_data)' from 'everyEntry = json.loads(entry.saved_data)' Here is my code from the template : <tbody> <tr> {% for entry in entries %} {{everyEntry = json.loads(entry.saved_data)}} {{ everyEntry.items}} {% for clef, valeura in headersLoop %} {% for chiave, valore in everyEntry %} {% if clef = chiave %} <td> <p>{{clef}} {{valore}}</p> </td> {% endif %} {% endfor %} {% endfor %} {% endfor %} </tbody> An at this line : {{everyEntry = json.loads(entry.saved_data)}} the problem occurs. How may i fix this ? Thank you guys. -
I have a bound ModelForm that is invalid
I am trying to create a ModelForm that links to an external database, and when you submit the form the external database gets updated. The problem comes when I check the validity of the form, it is invalid. I have done some researching into this and found the most common problem was that the form is not bound, but when I use print(form.non_field_errors) I get: <bound method BaseForm.non_field_errors of <EmailForm bound=True, valid=False, fields=(subject;body;name;altsubject;utm_source;utm_content;utm_campaign)> models.py: class MarketingEmails(models.Model): messageid = models.AutoField(db_column='column1', primary_key=True) subject = models.CharField(db_column='column2', max_length=2000) body = models.TextField(db_column='column3') #using a text field as there is no maximum length name = models.CharField(db_column='column4', max_length=25) altsubject = models.CharField(db_column='column5', max_length=2000) utm_source = models.CharField(db_column='column6', max_length=25) utm_content = models.CharField(db_column='column7', max_length=25) utm_campaign = models.CharField(db_column='column8', max_length=25) class Meta: managed = False db_table = '' forms.py: class EmailForm(forms.ModelForm): class Meta: model = MarketingEmails fields = ['messageid','subject','body','name','altsubject','utm_source','utm_content','utm_campaign'] views.py: def emailinfo(request, pk): if request.session.has_key('shortname'): shortname = request.session['shortname'] rows = get_object_or_404(MarketingEmails, pk=pk) if request.method == 'POST': form = EmailForm(request.POST) print(form.errors) print(form.non_field_errors) if form.is_valid(): form.save() print("form is valid") return redirect('marketingemails:emailinfo', pk = rows.messageid) return render(request, 'marketingemails/emailinfo.html',{'shortname': shortname, 'rows': rows}) else: return HttpResponseRedirect(reverse('common:login')) urls.py: app_name = 'marketingemails' urlpatterns = [ url(r'^marketing/emails/(?P<pk>[0-9]+)/$', marketingviews.emailinfo, name='emailinfo'), ] html: <form method="POST" class="post-form" action =""> {% csrf_token %} <label for="exampleTextarea">Name</label> … -
Automatic inheritance for django models
I have a django project which has models like this. class Part(models.Model): attr1 = models.CharField(max_length=50) attr2 = models.CharField(max_length=50) class Document(models.Model): part = models.ForeignKey(Part) attr1 = models.CharField(max_length=50) and so on. There are a lot of models in one single module and I need for each model a separate model with the same attributes plus one or more additional attributes. How would I do that without writing every single class by hand? -
Django 1.11 and Django CMS 3.4.4 MIDDLEWARE vs MIDDLEWARE_CLASSES
I was doing a Django CMS setup, and had to change the MIDDLEWARE to MIDDLEWARE_CLASSES to get it working. Does anyone know why MIDDLEWARE_CLASSES is required in the settings.py file and not just MIDDLEWARE? This is not a older settings file, was generated with Django 1.11 """ Django settings for project project. Generated by 'django-admin startproject' using Django 1.11.3. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os SITE_ID = 1 # 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/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'fbyo_48g6q+w&2ewq4lazogva*tpt=4fof7xt!_uvcied&m6k$' # 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', 'django.contrib.sites', 'cms', 'treebeard', 'menus', 'sekizai', 'djangocms_admin_style', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', ] MIDDLEWARE_CLASSES = [ 'cms.middleware.utils.ApphookReloadMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ] THUMBNAIL_HIGH_RESOLUTION = True THUMBNAIL_PROCESSORS = ( 'easy_thumbnails.processors.colorspace', 'easy_thumbnails.processors.autocrop', 'filer.thumbnail_processors.scale_and_crop_with_subject_location', 'easy_thumbnails.processors.filters' ) CMS_TEMPLATES = ( ('template_1.html', … -
Pinax account do not show Display name from admin in navbar
I have a pinax account project and I would like to not display my own nav bar. For that I can overwrite the {% block nav %} and I am able to add more things to the bar. But the Display Name (mandatory field) that is in the Django admin is still appearing in the bar. How can I delete it? -
Connect() to .sock failed, no such file
I have a Django app that runs fine on localhost with python manage.py runserver 0.0.0.0:8443. Now, I have a server on which I wish to run the app. To do so, i followed this guide. Here I set up a virtualenv, configured uWSGI and nginx. As far as I can tell, everything is set up correctly, yet when i try to reach my address it returns 502. The following error is found in the error.log 2017/07/13 11:24:11 [crit] 4825#0: *1 connect() to unix:/home/django/sample/sample.sock failed (2: No such file or directory) while connecting to upstream, client: 131.180.112.131, server: annotatie01.io.tudelft.nl, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://unix:/data_nfs/data_collection_project.sock:", host: "annotatie01.io.tudelft.nl:8443", referrer: "http://annotatie01.io.tudelft.nl:8443/" It appears that the .sock file is never created. I can not find it in the directories either. Where should this file be created? I've seen a few questions related to this, but for those it appears that either the .socks does exist, or they're not using uWSGI uWSGI: File : /etc/uwsgi/sites/data_collection_project.ini [uwsgi] project = data_collection_project base = /data_nfs chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 2 socket = %(base)/%(project)/%(project).sock chmod-socket = 664 vacuum = true File: /etc/init/uwsgi.conf description "uWSGI" start on runlevel [2345] stop … -
Django ORM query, distinct values and join the same table
I would like to return all columns based on distinct values from column site where hide = 0 and order it by date from created. I'm aware that distinct() call with specified field names is currently supported only by PostgresSQL but I'm running MySQL. I've got a working SQL query (it's probably not very efficient) but not sure how to convert it to Django ORM. Table structure: mysql > SHOW CREATE TABLE sites\G *************************** 1. row *************************** Table: sites Create Table: CREATE TABLE `sites` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_ip` char(39) NOT NULL, `site_ip` char(39) NOT NULL, `site` varchar(200) NOT NULL, `reason` varchar(50) NOT NULL, `hide` tinyint(1) NOT NULL, `created` datetime(6) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=836 DEFAULT CHARSET=utf8 1 row in set (0.00 sec) SQL query: SELECT * FROM (SELECT site, MAX(created) created FROM hget_scan GROUP BY site ORDER BY MAX(created) DESC LIMIT 10) _d JOIN hget_scan USING (site, created) ORDER BY _d.created DESC -
How to write query for join two table in django query
Table1: id cam temp 1 hi 10 2 he 2 Table2: cam count hi 5 select t2.count from Table2 t2 inner join Table1 t1 on t1.cam=t2.cam where t1.temp=10 Can anyone help to write the above query using django query. -
How to return the file data to browser using Python and Django
I need some help. I need to return the file data while running the URL to the browser using Python. I am explaining my code below. def createfile(request): if request.method == 'GET' and 'q' in request.GET: param = request.GET['param'] if param is not None and param != '': execfile(param) Here When user will run http://127.0.0.1:8000/createfile/?param=/opt/lampp/htdocs/Nuclear_reactor/d25/nuclear_vulnerable/hello.py on the browser the content inside the hello.py file should return to the browser. Please help. -
Django makemessages command generates error: "xgettext: Non-ASCII string"
I have a simple django project. I am attempting to translate the site into Russian. Here is my settings.py file: 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/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'n_gc#7lsv48h-b$)9aw6eer6z$zia#@da=bdwgova1=6u!8uvh' # 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', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'omefx.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+'/omefx/templates'], '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', 'django.template.context_processors.i18n', ], }, }, ] WSGI_APPLICATION = 'omefx.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } LANGUAGES = ( ('en', ('English')), ('ru', ('Russian')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR +'/omefx/', 'locale'), 'locale', # os.path.join(PROJECT_DIR, 'locale'), ) # Password validation # https://docs.djangoproject.com/en/1.10/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/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = … -
Django date is different in template than the database
I have a curious issue in my Django template. I have model/table and for each entry I record the date/time for it. No problem, the date is correct in the database and in the Django admin pannel : However, when I want to display the date/time in my template, this is different : {{post.date|date:"d F H:m"}} Time zone in my settings.py : # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'fr-fr' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True -
ImportError: cannot import custom module to celery tasks, how to improve?
I need to import a model from my application, then make a request, and send a sms, but I can not import my model, although the name is specified correctly, who can help ask, I will wait, thank you all! Full traceback > Traceback (most recent call last): File > "c:\users\p.a.n.d.e.m.i.c\appdata\local\programs\python\python36-32\Lib\runpy.py", > line 193, in _run_module_as_main > "__main__", mod_spec) File "c:\users\p.a.n.d.e.m.i.c\appdata\local\programs\python\python36-32\Lib\runpy.py", > line 85, in _run_code > exec(code, run_globals) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\Scripts\celery.exe\__main__.py", > line 9, in <module> File > "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\__main__.py", > line 30, in main > main() File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bin\celery.py", > line 81, in main > cmd.execute_from_commandline(argv) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bin\celery.py", > line 769, in execute_from_commandline > super(CeleryCommand, self).execute_from_commandline(argv))) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bin\base.py", > line 311, in execute_from_commandline > return self.handle_argv(self.prog_name, argv[1:]) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bin\celery.py", > line 761, in handle_argv > return self.execute(command, argv) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bin\celery.py", > line 693, in execute > ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bin\worker.py", > line 179, in run_from_argv > return self(*args, **options) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bin\base.py", > line 274, in __call__ > ret = self.run(*args, **kwargs) File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\bin\worker.py", > line 212, in run > state_db=self.node_format(state_db, hostname), **kwargs File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\worker\__init__.py", > line 95, in __init__ > self.app.loader.init_worker() File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\loaders\base.py", > line 128, in init_worker > self.import_default_modules() File "c:\users\p.a.n.d.e.m.i.c\desktop\td11\lib\site-packages\celery\loaders\base.py", > line 116, in import_default_modules > signals.import_modules.send(sender=self.app) File … -
Django calls other template instead of default
I've made my own login.html name to login1.html instead of deleting it, and now I'm using Django-registration and Django-registration-views from Github, but still, Django calls registration/login1.html. how can I restore it to call the login.html ?? as we can change the default path of templates, is there any way to change default name of a template from login1.html to login.html ? -
Django - Wrong Validation Error Message when using self-written Validator
I have written my own validator as I have several fields in my form where the same validation is applicable and I wanted to reduce my code with clean_field() methods. My Form looks like this: class EducationProjectAjaxForm(forms.Form): study_fees_year_1 = forms.IntegerField(required=False, validators=[validate_study_fees]) study_fees_year_2 = forms.IntegerField(required=False, validators=[validate_study_fees]) study_fees_year_3 = forms.IntegerField(required=False, validators=[validate_study_fees]) study_fees_year_4 = forms.IntegerField(required=False, validators=[validate_study_fees]) My validator looks like this: def validate_study_fees(data): if data: if data > 100000: raise ValidationError(_('Falscher Wert: %(value)s'), code='invalid', params={ 'value': 'Es sind maximal 100.000 € Studiengebühren pro Jahr erlaubt.'}, ) if data % 10 != 0: raise ValidationError(_('Falscher Wert: %(value)s'), code='invalid', params={ 'value': 'Der eingetragene Wert muss durch 10 teilbar sein.'}, ) if data < 0: raise ValidationError(_('Falscher Wert: %(value)s'), code='invalid', params={'value': 'Der Finanzierungsbedarf darf nicht negativ sein'}, ) return data My problem is that even though the validation itself is correctly applied I get the wrong error message: "Please choose a whole number". The message comes probably from the normal validation for IntegerFields but something like 123 throws the same message even though it is a whole number. If go the way with clean_study_fees_year_1(self), ... The error message is correctly shown. Is there something to fix my problem so I can have cleaner code? Thanks in … -
Postfix envelope sender has no MX record, SpamAssasin says
So, here's the email i'm sending: Return-Path: <support@huvu.ru> Received: from mail.huvu.ru (188.225.78.9) by verifier.port25.com id hcsjqe2bkd0m for <check-auth@verifier.port25.com>; Thu, 13 Jul 2017 03:56:23 -0400 (envelope-from <support@huvu.ru>) Authentication-Results: verifier.port25.com; spf=pass smtp.mailfrom=support@huvu.ru; dkim=pass (matches From: support@huvu.ru) header.d=huvu.ru Received: from huvu.ru (huvu.ru [188.225.78.9]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.huvu.ru (Postfix) with ESMTPSA id A5BD01881F for <check-auth@verifier.port25.com>; Thu, 13 Jul 2017 07:54:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=huvu.ru; s=mail; t=1499932457; bh=XQ+bk1OYUjzL5nu93cEzQJDGlO5RjydiljqRVWK87Eo=; h=Subject:From:To:Reply-To:Date:From; b=AlE0kl5mvxHGRQk5ir1yGByvjCyyOZrCO5ol8lyb2nyNTISlm5/qu4ngwsbmS87t1 VoiNGADici0cNs/22sDEN+fgvW3W1T36fmPaztDT/Sf/v5BY6/LczRkIDTBWzO5Tpm 9fHPr+M2D5b2NQvLIGymAsTsePGgByHERBJq/Ic8= Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject! From: support@huvu.ru To: check-auth@verifier.port25.com Reply-To: support@huvu.ru Date: Thu, 13 Jul 2017 07:54:17 -0000 Message-ID: <20170713075417.7018.53609@huvu.ru> Email Body I most likely wrong, but as i understand it, envelope sender here is: support@huvu.ru huvu.ru definitely has MX record. My DNS zone file (removed SPF, DKIM, DMARC): $TTL 60 @ IN SOA ns1.huvu.ru. support.huvu.ru. ( 2017071301 ; Serial 1800 ; Refresh 600 ; Retry 2419200 ; Expire 60 ) ; Negative Cache TTL ; huvu.ru. IN NS ns1.huvu.ru. huvu.ru. IN NS ns2.huvu.ru. huvu.ru. IN A 188.225.78.9 huvu.ru. IN MX 10 mail.huvu.ru. ns1 IN A 188.225.78.9 ns2 IN A 188.225.32.17 www IN CNAME huvu.ru. ftp IN CNAME huvu.ru. mail IN CNAME huvu.ru. My guess is that … -
local variable 'content_type' referenced before assignment
I have a problem with function post in my views.py. The problem is when I send a POST form. UnboundLocalError at /pl/ local variable 'content_type' referenced before assignment I installed new app for rating new contents and I need to add some code in my views.py to the function def post. Now it works only for CommentForm (Comments). views.py: class IndexView(AllAdsViewMixin, ListView): model = UserContent template_name = 'user_content/list.html' context_object_name = 'object' def get_queryset(self): """Return the last all five published contents""" return UserContent.objects.filter(state='1').order_by('-published')[:5] def get_context_data(self, **kwargs): comment_initial_data = { 'content_type': ContentType.objects.get_for_model(self.model).id } reply_initial_data = { 'content_type': ContentType.objects.get_for_model(Comment).id } comment_form = CommentForm(initial=comment_initial_data) reply_form = CommentForm(initial=reply_initial_data) mainpage_images = MainPageImages.objects.first() rate_form = RateForm() context = super(IndexView, self).get_context_data(**kwargs) context['comment_form'] = comment_form context['reply_form'] = reply_form context['mainpage_images'] = mainpage_images context['rate_form'] = rate_form return context def post(self, request, **kwargs): comment_form = CommentForm(request.POST) if comment_form.is_valid(): content_type_id = comment_form.cleaned_data.get('content_type') object_id_data = comment_form.cleaned_data.get('object_id') content_data = comment_form.cleaned_data.get('content') content_type = ContentType.objects.get_for_id(content_type_id) print(object_id_data) print(content_data) else: print(comment_form.errors) new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=object_id_data, content=content_data, ) return self.get(request, **kwargs) As you can see guys I need edit this function for add RateForm, because now it's only for CommentForm. Can someone help me? -
Django: filter by aggregate
I am trying to filter by a value calculated using aggregates. Currently I am doing this: max_val = some_queryset.aggregate(max_val=Max('some_prop'))['max_val'] some_queryset.filter(some_prop=max_val) Is there a way I can use max_val to filter, all done in a single query? Unfortunately I am using Django 1.4. and no, I cannot update it, it is simply not up to me. -
How to make certain characters read-only in a Django charfield?
I'm trying to create a charfield in my model with a prefix read-only characters: class Leader(models.Model): name = models.CharField(max_length=100) slack_id = models.CharField(max_length=50, null=False, unique=True, default="@slack.com") def __unicode__(self): return self.name In this model, I'm finding a way to make my slack_id instance to have a prefix read-only character '@' so that my users only have to fill out their username without the symbol, mimicking the way gmail sign up form below. -
django-allauth social registration
I have followed the instructions given on the django-allauth site and have managed to create a simple page with links to signup. However, the default page (/accounts/signup) shows only registration by email. I want the ability to signup by social media (Twitter, Facebook etc). What URL do I need to use to perform social media login using all-auth Which section of the code actually creates the new user in the django database - I need to understand how the user is being created - as I may want to add additional custom logic. -
How user gets automatically logged in on different server domain web application when they are sharing same authentication system like oAuth 2.
Situation :- I have an Authentication system developed in django python 0Auth2. I have 3 angular web application with different server domain which use same authentication system for user login or signup. For eg: 'webapp1', 'webapp2', 'webapp3'. Want To Do : If user xyz login on webapp1 and open webapp2 in new tab of same browser then user xyz should login automatically on webapp2 and same for webapp3. Question :- How user gets automatically logged in on different server domain web application when they are sharing same authentication system like oAuth 2 designed in django python. -
How to get image from django form ImageField input
I'm trying to get an image from a input ImageFile to display in the template and also save that ImageFile to the models ImageField. The code below spits out an error: upload_img_temp.write(uploaded_image) TypeError: a bytes-like object is required, not 'str' Form class UploadImageForm(forms.ModelForm): class Meta: model = Image fields = ['image'] View def uploadImageView(request): form = UploadImageForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid: request.session['image'] = request.POST['image'] return redirect('image:create') def imageCreateView(request): uploaded_image = request.session.get('image') upload_img_temp = NamedTemporaryFile() upload_img_temp.write(uploaded_image) upload_img_temp.flush() form_create = ImageModelCreateForm(request.POST or None, request.FILES or None,) if form_create.is_valid(): instance = form_create.save(commit=False) instance.image = upload_img_temp Template <img class="image" src="{{ upload_img_temp }}"> -
Django api without REST frame work
How can I do the following task using Django but without rest-framework? This is my current code: serializers from rest_framework import serializers from .models import User,Blog class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('std_num','password' , 'first_name', 'last_name', 'email') views from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import User from .serializers import UserSerializer class register (generic.FormView): def post(self, request): serializer = UserSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=111) return Response(serializer.errors, status=100) -
Django get id of specific div class
I am trying to build up a website with Django which showes the web-traffic of another website in realtime. Though the user shall be able to sort the data in a view different ways I would have to make a huge amount of nested folders in my project folder and I don't think that is the best solution for it. I have another idea and therefore, let's say we have created a website which contains following code: ... <div class='size' id='big> <div class='fish' id='yellow'> <a href='some_link'> LINK </a> ... For dynamically changing the site I need to know the ids of the size- and the fish-class. Is there any possiblity to get the ids of the div-classes (with Django) when the link is pressed? Something like (pseudo-code): id = request.get_id_of(div class='fish') BeautifulSoup is no solution for this problem because it's getting some conflicts with Django. -
Filter rows by non-databse fields in django
I have PostgreSQL and Django and theese models: class TranslationService(models.Model): class Meta: abstract = True service_name = models.CharField(max_length=40) class GoogleTranslator(TranslationService): service_name = "Google" lang = models.CharField(max_length=10, blank=False) text = models.TextField(blank=False) I wanna filter TranslatorService by service_name, but field isn't in database, how can I perform this? Only storing field in DB and set default field? -
How to get all messages of outgoing mail in Django
I am finding a way to grab emails and attachments by email address. With Incoming mail, i am getting all messages of Inbox mail through IMAP or POP3 via django-mailbox backage. But How to get all messages of Outgoing mail (SMTP).