Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
show forms for model who can have multiple instance
I am creating a simple project which is about creating a resume by user. In resume, a user can have multiple experience, educational background and etc. That is why I have created the following table where experience, educational background, skills are foreignkey to the resume table. class Resume(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=False, null=False, help_text="Full Name") slug = models.SlugField(max_length=50, unique=True) designation = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Education(models.Model): resume = models.ForeignKey(Resume, related_name='education') name = models.CharField(max_length=100, blank=False, null=False, help_text="Name of an institution") course = models.CharField(max_length=200, blank=False, null=False, help_text="Name of a course") description = models.CharField(max_length=400, blank=True, null=True) start_date = models.DateField() end_date = models.DateField() class Experience(models.Model): resume = models.ForeignKey(Resume, related_name='experience') designation = models.CharField(max_length=100, blank=True, null=True) company = models.CharField(max_length=100, blank=True, null=True) description=models.CharField(max_length=400, blank=True, null=True) start_date = models.DateField() end_date = models.DateField() class Skill(models.Model): resume=models.ForeignKey(Resume, related_name="skills") name = models.CharField(max_length=100, blank=True, null=True, help_text="Name of the skill") class Meta: verbose_name='Skill' verbose_name_plural='Skills' def __str__(self): return self.name Now for such situation, do I have to create a ResumeForm, EducationForm, ExperienceForm etc and create an Education, Experience and Skill formset or I have to do something else. I do not have clear idea on how to move forward now for … -
django - Ajax Live Search, What Am I Doing Wrong?
I'm trying to have a live search feature where as soon as you type something in a search box, the results automatically appear right below. I've been following this tutorial with no luck. Nothing seems to be happening when I type a query. Could anybody tell me what I'm doing wrong? urls.py urlpatterns = [ url(r'^$', views.list_of_post, name='list_of_post'), [...] url(r'^search/$', views.search_titles), ] # this is my blog app views. Original view contains # url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), views.py # Main view that displays all my posts def list_of_post(request): post = Post.objects.filter(status='published') categories = Category.objects.all() template = 'blog/post/list_of_post.html' context = { 'posts': posts, 'categories': categories, [...] } return render(request, template, context) # View that should return my results? def search_titles(request): if request.method == 'POST': search_text = request.POST['search_text'] else: search_text = '' classes = Post.objects.filter(title__contains=search_text) return render_to_response('blog/ajax_search.html', {'classes': classes}) template <h3>Search</h3> {% csrf_token %} <input type="text" id="search" name="search"/> <ul id="search-results"> </ul> ajax_search.html {% if classes %} {% for class in classes %} <p>{{ class.title }}</p> {% endfor %} {% else %} <p>No classes found.</p> {% endif %} and finally, ajax.js $(function() { $('#search').keyup(function() { $.ajax({ type: "POST", url: "blog/search/", data: { 'search_text' : $('#search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' … -
Django test Client submitting a form with a POST request
How can I submit a POST request with Django test Client, such that I include form data in it? In particular, I would like to have something like (inspired by How should I write tests for Forms in Django?): from django.tests import TestCase class MyTests(TestCase): def test_forms(self): response = self.client.post("/my/form/", {'something':'something'}) My endpoint /my/form has some internal logic to deal with 'something'. The problem was that when trying to later access request.POST.get('something') I couldn't get anything. I found a solution so I'm sharing below. -
'NoneType' object has no attribute '__getitem__' On Template Render
I know there are questions already answering this but they all seem specific to the project. I have tried to create a MultiValueField, starting with a more complex one and dumbed it down a little to make it easier to understand and implement. So i thought i did it. But now I’m getting 'NoneType' object has no attribute '__getitem__' So first thing is the MultiValueField that has to be a sub class of a MultiWidget class. class LeadTimeWidget(MultiWidget): def __init__(self, attrs=None): widget = [forms.TextInput(), forms.TextInput()] super(LeadTimeWidget, self).__init__(widget, attrs) def decompress(self, value): if value: return value class LeadTimeMultiField(MultiValueField): widget = LeadTimeWidget def __init__(self, *args, **kwargs): list_fields = [forms.fields.CharField(max_length=31), forms.fields.CharField(max_length=31)] super(LeadTimeMultiField, self).__init__(list_fields, *args, **kwargs) def compress(self, data_list): pass After that its conecting the MultiValueField to the form... class AssessmentForm(FrontEndForm): new_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) used_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) repair_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) exchange_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) other_label = forms.CharField(required=False) lead_time = LeadTimeMultiField() other_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) quote_note = forms.CharField(required=False, widget=widgets.Textarea(attrs={"rows": 3, "cols": 50})) inbound_shipping_cost = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) outbound_shipping_cost = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) You can see that i have done that lead_time = LeadTimeMultiField(), The next bit would be to render … -
Working with Boolean QuerySet
I'm having troubles working with a Boolean QuerySet. models.py: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', primary_key=True) firstConnexion = models.BooleanField(default=True) views.py firstConnexion = Profile.objects.filter(user=request.user).values('firstConnexion') if firstConnexion: Profile.objects.filter(user_id=user_id.id).update(firstConnexion=False) return redirect('/one/') else: return redirect('/two/') The problem is I am only getting the first condition even though Profile is updated to False How ? -
NoReverseMatch on Django even when kwargs are provided
The Django cant resovle the url, even though the expected kwarg is provided. Here is root urls.py: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.STATIC_ROOT}), url(r'^(?P<domain>\w+)', include('frontend.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is frontend urls.py: from django.conf.urls import include,patterns,url from . import views from .views import MyprofileView from .views import SuccessView from .views import CompanyView from .views import SubscriptionView from django.views.decorators.csrf import csrf_exempt urlpatterns = patterns('', url(r'/success(/?)$', SuccessView.as_view(), name='success'), url(r'/subscribe(/?)$', SubscriptionView.as_view(), name='subscribe'), url(r'^(/?)$', MyprofileView.as_view(), name='home'), url(r'/api/v1/', include('cpprofile.api.urls')), url(r'/product', include('product_information.urls')), url(r'/corporations/(?P<company>\d+)$', CompanyView.as_view(), name='company_page'), url(r'^/(?P<subscription>\w+)/product/pay/return/(?P<amount>\d+)/(?P<currency>\w+)/(?P<id>\d+)?$', views.payment_return, name='subscription_product_payment_return'), ) And here is how I am trying to reverse call it in view.py MyprofileView: context['subscribe_url'] = redirect('subscribe', kwargs={'domain': 'up'}) What could be wrong here? Thanks -
ImportError: No module named xxxx.settings
i moved a project on a different server and now i got this error everytime i build the project : Traceback (most recent call last): File "E:\Applications\var\www\Gestion_Mouvements\Gestion_Mouvement\clean_html.py", line 4, in <module> directory = settings.CLEAN_DIRECTORY; File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__ self._setup(name) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named Gestion_Mouvements.settings In my wsgi.py : import os import sys project_home = u'E:/Applications/var/www/Gestion_Mouvements/Project_Gestion_Mouvement' if project_home not in sys.path: sys.path.append(project_home) os.environ['DJANGO_SETTINGS_MODULE'] = 'Project_Gestion_Mouvement.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Gestion_Mouvements ├── Project_Gestion_Mouvement │ ├── init.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── Gestion_Mouvement │ ├── init.py │ ├── admin.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py └── manage.py I tried most of the solutions already proposed on the multiples post about that error but nothing seem to work so far. i can still perfectly use the app on a webpage and all, but i can't use any script manualy in the project. Any idea on how to fix this ? Thanks in advance. -
Django - model field value multiple checkbox (default value is checked)
I have a Car model and CarOption model class. class Car(models.Model): car_name = models.Charfield(max_length=20) car_options = models.ManyToMany('CarOption') class CarOption(models.Model): option_name = models.CharField(max_length=20) If user select a car, options that user can add to the car should be displayed as multiple checkbox and default options is checked for each car. How should I implement it? please your valuable opinions... -
How to set new value for a key in Django Session_data
What I have in my encoded session_data is: 'workspaceKey':'8d7f4b3106c740c1a54970a8b67d156d', '_auth_user_hash': '7e024dd67ccb0e2aaab9ac1a92887109f7f020e4', '_auth_user_id': '1', '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend' What I have tried is (1st approach): request.session['workspaceKey'] = "123f4b3106c740c1a54970a8b67d111d" but it is not updating workspaceKey is my existing session_data Another approach what I tried is: sessionid = Session.objects.get(session_key=session_key) sessionid.get_decoded()['workspaceKey'] = "8d7f4b3106c740c1a54970a8b67d111d" Again it is not updating workspaceKey is my existing session_data. I have also tried below combinations with respect to above approach request.session.modified = True SESSION_SAVE_EVERY_REQUEST=False What I expect in my output as (new workspace key should be updated) 'workspaceKey':'123f4b3106c740c1a54970a8b67d111d', '_auth_user_hash': '7e024dd67ccb0e2aaab9ac1a92887109f7f020e4', '_auth_user_id': '1', '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend' -
django admin add view Readonly Dropdown
class CaseAdmin(admin.ModelAdmin): list_display = ['id', 'Status','Title','CaseCategory','Group'] list_filter=['Status'] date_hierarchy = 'CreatedDate' raw_id_fields = ('Customer',) fields= ['Customer', 'Title', 'Priority', 'Status', 'CaseCategory', 'Detail', 'Group', 'User'] here its my admin.py. The User field coming from Users table to the dropdownlist but this dropdown must be just readonly. here its my screenshot screenshot here. -
If statement in my Django template...Is there a better way?
In my Django template: I'm trying to add an extra div around my for loop only if the length of the data being passed to the template is 3. This is what I'm trying right now but it seems like there could be better way than doing two if statements to check for the length: {% if items|length == 3 %} <div class='three-item-wrap'> {% endif %} {% for item in items %} ....... {% endfor %} {% if items|length == 3 %} </div> //close .three-item-wrap {% endif %} -
Loosing timezone on data retrieval over objects
I have a model which has a DateTimeField for a start date. When I'm creating new objects of the model and store them in the postgre database the given timezone is 'Europe/Berlin'. I confirmed it just before calling save() and the entries have the correct offsets in the database. The timezone of the database also matches with the timezone of the objects. But when I retrieve objects of the model over .filter() the timezone is set to 'UTC', so I'm loosing the timezone. Of course it should be 'Europe/Berlin' as well. Inside settings.py is also the correct timezone TIME_ZONE = 'Europe/Berlin' Can anybody help me? -
AttributeError at /blog/index/ 'tuple' object has no attribute 'get'
I'm a beginner in python.I get an error and I have been struggling with for hours. AttributeError at /blog/index/ 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://localhost:8000/blog/index/ Django Version: 1.10.2 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/middleware/clickjacking.py in process_response, line 32 Python Executable:/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python Python Version: 2.7.13 And this is traceback: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/deprecation.py" in __call__ 135. response = self.process_response(request, response) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/middleware/clickjacking.py" in process_response 32. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /blog/index/ Exception Value: 'tuple' object has no attribute 'get' This is a simple project ,I built a new app named blog ,and new directory named templates in blog ,then I built index.html in templates . The index.html : <h1>Hello blog</h1> The blog.views : from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request,'index.html'), The settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog'] enter image description here -
Webpage that imports data, process data with a script and exports data visualisation as pdf or docx
I'm currently working on a webpage where I want to have an application that can through an import button import a csv-file. Then behind the scenes I want to process the data, e.g. using a Python script, and through that get some data visualizations. These data visualizations should be displayed on the webpage combined with a text field, where the user can enter the interpretation of the data visualizations. Finally, the user should be able to export the data visualizations combined with his/her interpretation in a report as a pdf- og docx-file. Currently, I'm using the Python web framework, Django, since it is based on Python and might co-operate better with Python scripts. However, I'm still a bit unsure if this framework is able to do what I want. Does any of you have any experience with importing csv-files, generating data visualizations and exporting pdf's or docx's in Django or would you recommend another framework maybe based on another language? Looking forward to get some feedback plus validation or invalidation of my first steps towards my goal! -
Django admin inline with custom queryset
I've got two models: class Parent: ... class Child: parent = models.ForeignKey(Parent) In the model admin of the Parent I want to show an inline of the Child with a custom queryset, not only the ones related to the parent through the fk field. I've tried: class ChildInline(admin.TabularInline): model = Child def get_queryset(self, request): return Child.objects.filter(<my custom filter>) class ParentAdmin(admin.ModelAdmin): inlines = [ChildInline] But still the only children shown in the inline are the ones related through the fk field. Is it possible to do this? -
Why dispatch method is taking long time to call target method in Django Rest Framework?
I have this method class RunningQuizAuthenticationView(APIView): def dispatch(self, *args, **kwargs): print(time.time()) return super(RunningQuizAuthenticationView, self).dispatch(*args, **kwargs) def get(self, request: Request, key: str) -> Response: print(time.time()) ..... ...... Now, once I get both the time, I take the difference of this time, the difference time is about 30 ms, can you explain to me why this is taking so much time, for the login request it takes about 0 ms but for other requests it takes a long time to reach target method from dispatch method, please help me, Thank you -
Static files not loading on Heroku : Django
I am deploying my Django application on Heroku. It has been deployed successfully. But static files are not loading. I followed this link, but when Whitenoise is included, the command python manage.py collectstatic --noinput fails. my Procfile: python manage.py collectstatic --noinput web:python manage.py runserver web: gunicorn MovieTracker.wsgi --log-file - heroku ps:scale web=1 I have also tried with : heroku config:set DISABLE_COLLECTSTATIC=1 and also : heroku config:set DISABLE_COLLECTSTATIC=0 The settings.py file is: BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tracker', ) MIDDLEWARE_CLASSES = ( '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', # 'whitenoise.middleware.WhiteNoiseMiddleware', ) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/tracker/static") # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' how can I get my static files working in heroku deployment? -
Django how to link a button to http response
I want to create a simple page which requires a login and has a button which on clicking would download a csv file. Below works good, but this directly downloads the file. @login_required(login_url='/admin/login/') def index(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="data.csv"' writer = csv.writer(response) writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) return response I can create a button and link view to it's template, but how to I return the above response from it. <form action="#" method="get"> <input type="submit" value="Click" name="mybtn"> </form> -
Create react app + Django deployment Uncaught SyntaxError: Unexpected token <
I've been trying to deploy an app to pythonanywhere but the page is just blank, because main.6f259c1b.js file throws error` Uncaught SyntaxError: Unexpected token < ` I've been following the instuctions on this article https://www.fusionbox.com/blog/detail/create-react-app-and-django/624/ and this https://www.techiediaries.com/create-react-app-django/ both articles suggest to create a view with following content class FrontendAppView(View): """ Serves the compiled frontend entry point (only works if you have run `yarn run build`). """ def get(self, request): try: with open(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f: return HttpResponse(f.read()) except FileNotFoundError: logging.exception('Production build of app not found') return HttpResponse( """ This URL is only used when you have built the production version of the app. Visit http://localhost:3000/ instead, or run `yarn run build` to test the production version. """, status=501, ) and in app/urls.py urlpatterns = [ url(r'^', FrontendAppView.as_view()) ] Those instructions don't work for me. It's something that related to pushState routing, react-routing, I don't know. My app works ok in development server in localhost:3000, it only seen in pythonanywhere and local apache server with mod_wsgi. This is my config of local apache(from Django documentation): WSGIScriptAlias / /home/user/projects/myproject/myproject/wsgi.py WSGIPythonHome /home/user/.virtualenvs/myproject WSGIPythonPath home/user/projects/myproject/ <Directory /home/user/projects/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> This is root DocumentRoot "/srv/http" Part of my … -
ImportError : no module named 'models'
Hye . im basically very new in python and django . i keep getting this error ImportError : no module named 'models' and i dont know why . please do help me . i try to customize my own registration form in django. the error is in line : from models import CustomUser in forms.py forms.py : from django.contrib.auth.forms import UserCreationForm, UserChangeForm from models import CustomUser class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kargs): super(CustomUserCreationForm, self).__init__( *args, **kargs) del self.fields['username'] class Meta: model = CustomUser fields = ["email",] class CustomUserChangeForm(UserChangeForm): def __init__(self, *args, **kargs): super(CustomUserChangeForm, self).__init__(*args, **kargs) del self.fields['username'] class Meta: model = CustomUser register.html : {% extends "account/base.html" %} {% load crispy_forms_tags %} {% load i18n %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <div class= 'col-md-4 col-md-offset-4'> <h1>{% trans "Register" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <form acction="account/register/" method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Register" /> <button type="submit" class= 'btn btn-default'>{% trans "Sign Up" %} &raquo;</button> </form> </div> {% endblock %} views.py: from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from custom_user.forms import CustomUserCreationForm #Create your views here def home(request): … -
run scrapy from bash and implement it in django
I have a bash script to run a scrapy crawler and that crawler it passes some raw_inputs it asks me the url and the domain and i type them in the command line. now i want to implement that bash script and crawler in a django template. I want that template to collect the url and the domain and send it to the crawler. How can i do it? this is part of my bash script #!/bin/bash cd /.../seo/ PATH=$PATH:/usr/local/bin:/home/omega/.local/bin/ export PATH scrapy crawl test -
Django messages not showing after redirect
I have this piece of code in my view: if _user.objects.user_exists(_email): auth.logout(request) messages.success(request, 'You already hold a verified account with us. Please login.') return redirect('accounts:login') and this in my template: {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} This sadly wouldn't work. But if I change return redirect('accounts:login') to return render(request, 'accounts/login.html'), the message would display. So what is it that's preventing the messages from showing up during a redirect? And for the message storage, I am using: MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' Thanks for the help. -
Task IndexError('string index out of range',) in celery
I have created an asynchronous email sending to the job poster when job seeker applies for the job using celery and rabbitmq. I have used smtp(gmail) for email service.However I am getting an error which I could not figure out where exactly is the error coming from and how do i resolve it. The error is something like this Task job.tasks.send_resume_to_job_poster[a1d2f76e-5e38-4560-8576-0c43accff696] raised unexpected: IndexError('string index out of range',) Here is my code In a nutshell what I am doing is, I am generating the pdf from the html template and sending an email to the job poster but for testing I am using seeker email @shared_task def send_resume_to_job_poster(poster, seeker): resume = User.objects.get(email=seeker).resume html = render_to_string('resume/resume.html', {'resume': resume}) out = BytesIO() response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'filename="resume_{}.pdf"'.format(resume.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[ weasyprint.CSS(settings.STATIC_ROOT + '/css/pdf.css')]) # create resume email subject = "{} has applied for the job".format(resume.name) from_email = settings.EMAIL_HOST_USER to_email = [seeker] job_message = "if you don't want to recieve such message please we can't do anything for you." email = EmailMessage( subject, job_message, from_email, [to_email] ) email.attach("resume_{}.pdf".format(resume.id), out.getvalue(), 'application/pdf') return email.send() Error log in detail [2017-09-27 11:48:23,301: WARNING/ForkPoolWorker-1] html [2017-09-27 11:48:23,302: WARNING/ForkPoolWorker-1] <html> <head> <title>Tushant Khatiwada</title> </head> <body> <h1>Tushant Khatiwada</h1> <h3>Django … -
Use list(map(model_to_dict, queryset_list)) do not map the createtime and updatetime fields
I have a Test04 Model, and I give ctime and uptime fields. class Test04(models.Model): testTime = models.DateTimeField(null=True) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) But when I use the list(map(model_to_dict, queryset_list)) method to convert the queryset to dictionary, I find the ctime and uptime do not convert: from django.forms.models import model_to_dict print (models.Test04.objects.all()) all =models.Test04.objects.all() print (all[0].ctime) # 2017-09-26 07:49:02.012489+00:00 print (list(map(model_to_dict, all))) # [{u'id': 1, 'testTime': datetime.datetime(2017, 9, 26, 7, 49, 1, 973016, tzinfo=<UTC>)}, {u'id': 2, 'testTime': datetime.datetime(2017, 9, 26, 8, 3, 24, 665944, tzinfo=<UTC>)}, {u'id': 3, 'testTime': datetime.datetime(2017, 9, 26, 0, 12, 12, 683801, tzinfo=<UTC>)}, {u'id': 4, 'testTime': datetime.datetime(2017, 9, 26, 0, 12, 43, 2169, tzinfo=<UTC>)}, {u'id': 5, 'testTime': datetime.datetime(2017, 9, 26, 8, 13, 16, 164395, tzinfo=<UTC>)}, {u'id': 6, 'testTime': datetime.datetime(2017, 9, 26, 0, 14, 8, 812063, tzinfo=<UTC>)}, {u'id': 7, 'testTime': datetime.datetime(2017, 9, 26, 0, 15, 32, 945493, tzinfo=<UTC>)}] In the last line's output, you see there is no ctime and uptime in every dictionary. -
Django save base64 string to filesystem using models.ImageField
I am trying to upload image to file system using python django. I dont have any idea on how to proceed further. in my model.py: Class Test(object): mission = models.TextField(blank=True) image = models.ImageField(upload_to='documents/images/',blank=True) account = models.OneToOneField(Account, related_name='account') in my view.py def add_image(request, account): req = get_request_json(request) data = Test.objects.add_image(account, req) in my manager.py Class TestManager(models.Manager): def add_image(self, account, input): acc = self.get(account=account) acc.save() return acc; But I am not sure how to proceed from here. I would like to know how to save the base64 image string to the specified location and store the path/file name in database? I have worked with python where I write the files to a directory and get the path and store in db. Here I want to use the django options. I have to repeat the same process with other file formats too.