Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving a Date in a Coisefield - Django?
so what I'm trying to build is basically a calendar. For this, a user has to choose a beginning date and time for an event as well as an end time. Everything then has to be stored - of course - in the database. I want to realize that by using a ChoiseField (unless there is a better solution). How would it be possible to generate all the dates of the month in a coisefield since some months are 30 days others have a different length etc.? Same with the hours of a day? I cant seem to come up with a working approach? How would one approach this problem? suggestions? -
Django ORM: building models of dialog where one member has to be emphasized
It's not so obvious to me how to organise a dialog with django ORM. Especially if I need to know who first started a dialog(because he is a buyer and person who answers is a sales, and we need to know exactly who sales a thing ). So, I see two solutions. First one looks like this: class Dialog(models.Model): buyer = models.ForeignKey(UserProfile, related_name='buyer_reverse') sales = models.ForeignKey(UserProfile, related_name='sales_reverse') But queryset could bring some trouble. As I suppose, query would look something like: dialogs = Dialog.objects.filter(Q(buyer=request.user.userprofile) | Q(sales=request.user.userprofile)) Another solution I guess is: class Dialog(models.Model): members = models.ManyToManyField(UserProfile) sales = models.ForeignKey(UserProfile, related_name='sales_reverse') What is the best solution except there are both wrong? -
ImageField instance doesn't have save method in Django shell. But it does when I'm running the actual server
I'm a Django novice studying with Django By Example by Antonio Mele. I stuck up at chapter 5 where I needed to resort to ImageField's save method. Here is a part of the code edited by me. from urllib import request from django import forms from django.core.files.base import ContentFile from images.forms import ImageCreateForm from images.models import Image class ImageCreateForm(forms.ModelForm): def save(self): img = super(ImageCreateForm, self).save(commit=False) # ... response = request.urlopen(image_url) img.image.save(image_name, ContentFile(response.read(), save=False) # ... class Meta: model = Image # ... And the Image model looks like this. from django.db import models class Image(models.Model): # .... image = models.ImageField(upload_to='images/%Y/%m/%d') # .... So img in save method of ImageCreateForm is an instance of Image and img.image is an instance of models.ImageField, right? I looked it up on the official django document and even inspected django sourcecode but I couldn't find save method. I tried this on django shell but it gave me only an error. It seems like models.ImageField type doesn't have save method. But, somehow when I actually run the server this raises no errors and gets to have save method. How can this be possible? You can find the whole source code here. https://github.com/guinslym/django-by-example-book/tree/master/Django_By_Example_Code/Chapter%205/bookmarks -
How to render a html string in javascript?
In my Django project, I use jQuery ajax to post some data, and then the view function return some other data. I conver the markdown text to html text and return a response to ajax, then I insert the html text to page, but the html text can't be rendered. For example, if the markdown text is:# This is a title, then it would be convered to <h1>This is a title</h1>, but if insert to page, it just the html text<h1>This is a title</h1>, it can't be rendered. Here is my code: javascript code function commentSubmit(username, articleid) { var text = $(".comment-editor-input textarea").val(); var post_data = { 'username': username, 'text': text, 'articleid': articleid, } $.ajax({ type: "POST", url: "commentsubmit/", data: post_data, dataType: 'json', success: function(result) { var html = '<div class="comment-item">' + '<img class="comment-avatar" ' + 'src="">' + '<span class="comment-username">' + result.username + '</span>' + '<div class="comment-item-content">' + result.content_html + '</div><div class="comment-item-foot">' + '<span class="comment-time">' + '2017' + '</span>' + '</div></div>'; $(".comment-list").append(html); $(".comment-editor-input textarea").val(''); } }); } Django view def comment_submit(request): if request.method == 'POST': # post_text is a markdown text post_text = request.POST.get('text') username = request.POST.get('username') article_id = request.POST.get('articleid') user = User.objects.filter(username=username).first() article = get_object_or_404(Article, pk=article_id) # in Comment … -
Django select2 dependent_fields
How can i filter results in ModelSelect2Widget by value from depended select? I have simple form for two select fields: Company and Object class CompanySelect2Widget(ModelSelect2Widget): model = Companies search_fields = ['name__icontains'] def label_from_instance(self, obj): return force_text(obj.name) class CompanySelect2Field(ModelChoiceField): widget = CompanySelect2Widget( max_results=10, attrs={ 'id': "select2_client", 'data-placeholder': "Select client", 'style': 'width: 200px;', } ) class ObjectSelect2Widget(ModelSelect2Widget): model = Objects search_fields = ['name__icontains'] def label_from_instance(self, obj): return force_text(obj.name) class PGSelect2Form(ModelForm): company = CompanySelect2Field(label=u'Client', queryset=Companies.objects.all()) object = ModelChoiceField( queryset=Objects.objects.all(), widget=ModelSelect2Widget( model=Objects, search_fields=['name__icontains', 'company'], label=u'Object', max_results=10, attrs={ 'id': "select2_object", 'data-placeholder': "Select place", 'style': 'width: 200px;', 'dependent_fields': {'company': 'company'} } ) ) class Meta: model = Objects fields = ('company', 'object') Object model has field company company = models.ForeignKey('company.Companies', null=True, blank=False, editable=True) Rendered widgets: But nothing filtered in Object select, if Company selected before or after Object :/ -
Django, variable {{ }} inside {% %}
I'm using Django-instagram for simply display Instagram content on my webpage: {% load instagram_client %} {% instagram_user_recent_media intel %} This example works perfect, but the problem is Instagram name changes depending on selected page. I pass it via context: def about(request, foo_id): article = get_object_or_404(Bar, id=foo_id) return render_to_response('about.html', {'foo' : article}) It works fine if I'm using it without template: <p>{{ foo.instagram }}</p> --> returns valid name How can I pass my "foo.instagram" like this: {% load instagram_client %} {% instagram_user_recent_media {{ foo.instagram }} %} -
implementing a form into header django
hello i was not able to find something on google so I hope someone of you can help me out. I have a header(navigation bar) and when the user clicks on the ''settings'' button a modul pops up. I want to put a form in there but I don't know how to refer the form since I don't have a function in my views.py for my header. Thats what I would like to do but since a function like this would make no sense... def header (request): user = request.user form = UserProfileForm(request.POST or None, instance=user.profile) if form.is_valid(): profile = user.profile form.save() messages.success(request, 'Your new Settings are Updated') return redirect('home') context = { 'form':form, } return render(request,'personal/header.html',context) So can anybody tell me how to implement the form into the header? is this even possible like I imagine it or do I have to pass in the form on every site to make this run? Thanks in advise for any suggestions. -
Using openshift Rest Api in Django framework Python application
i want to strarted to build an application using framework Django in python to consume Openshift rest api that the user will be able to authentication and use their resources. the objectif of this project is to provide a web-based platform to enable Openshift users to create or interact with their online resources using Openshift web api Rest 3.0 . Specifications of project : The required service should enable existing projects and new projects management for any user having an Openshift online account. Management includes: -Authentication and Authorization -Teams , members and subscription plan management -SSH keys management -Gear, cartridge and application management -Deployment All these capabilities must be implemented using the Openshift API and provided using a Django based web interface. i try to read the officiel documentation through URL:https://access.redhat.com/documentation/en-US/OpenShift_Online/2.0/html/REST_API_Guide/index.html but i can't find a way to start building the application and consuming this rest api. have any one an idea to start -
How to get multiple values from a template and update multiple rows in a table? Django
I'm fairly new to Django and Python. I have a inventory management website. I am trying to update multiple values in a database. User should be able to input updated stock values and it should update each item's stock value which has been submitted. Image of page I tried "item[{{item.id}}]" to create a list but i'm not sure how to use this list or how to update multiple rows. My guess is that I need to gather all the values and keys from the template and in POST run a loop and update the relavant rows by ID. template <form action="" method="post"> {% csrf_token %} {% for item in items %} <tr> <td>{{item.name}}</td> <td>{{item.description}}</td> <td>{{item.buyprice}}</td> <td>{{item.sellprice}}</td> <td><input type="number" value="{{item.instock}}" name="item[{{item.id}}]"></td> </tr> {% endfor %} <tr> <td><input type="submit" value="Update"></td> view def stockUpd(request): if request.method == 'GET': items = Item.objects.filter(user=request.user) context = { 'items':items } return render(request,'stock/stockupd.html',context); #if request.method == 'POST': -
How can I count list number length to 1
In django my code is this {% for announcement in announcements %} <tr> <td>{{ count }}</td> <td>{{ announcement.title }}</td> <td>{{ announcement.user.profile.name }}</td> <td>{{ announcement.modified }}</td> </tr> {% endfor %} I want to write the number length of announcements to 1. how can I do that? Thanks. -
Wagtail streamfield block: injecting jQuery into the Wagtail Admin
I'm creating a block for Wagtail streamfields which shows real-time code syntax highlighting using the Prism JS library. It is partially working; when I have a language selected and code in place on an existing page, the code shows up, highlighted as expected: However, when I try to create a new Wagtail page with a new Code Block, I get a JavaScript error: It seems like the library is being delayed on loading when there isn't content there for it to highlight. I've tried both $(document).ready and $(window).load, but this is a different situation since the template containing the Prism library is loaded dynamically when you click the "Code Snippet" button. Here's the ext of the error I'm getting: VM730:2 Uncaught ReferenceError: Prism is not defined at prism_repaint (eval at globalEval (jquery-2.2.1.js:338), <anonymous>:2:5) at populate_target_code (eval at globalEval (jquery-2.2.1.js:338), <anonymous>:9:5) at HTMLDocument.eval (eval at globalEval (jquery-2.2.1.js:338), <anonymous>:2:29) at fire (jquery-2.2.1.js:3182) at Object.add [as done] (jquery-2.2.1.js:3241) at jQuery.fn.init.jQuery.fn.ready (jquery-2.2.1.js:3491) at eval (eval at globalEval (jquery-2.2.1.js:338), <anonymous>:1:13) at eval (<anonymous>) at Function.globalEval (jquery-2.2.1.js:338) at domManip (jquery-2.2.1.js:5285) Here's the Django Wagtail code I'm using for the Wagtail block: class CodeBlock(StructBlock): """ Code Highlighting Block """ WCB_LANGUAGES = get_language_choices() language = ChoiceBlock(choices=WCB_LANGUAGES) code = … -
Django REST Framework - serializer in many to many relationship
models.py from django.db import models from django.contrib.auth.models import User class Element(models.Model): name = models.CharField(max_length=20) class Group(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) elements = models.ManyToManyField(Element) class Meta: unique_together = ('user', 'name') serializers.py class ElementSerializer(serializers.HyperlinkedModelSerializer): # group = serializers.ReadOnlyField(source='group.id') class Meta: model = Element fields = ('name') """ def save(self, group=None, *args, **kwargs): if group is not None: self.group = group super(ElementSerializer, self).save(*args, **kwargs) """ class GroupSerializer(serializers.HyperlinkedModelSerializer): elements = ElementSerializer(many=True) class Meta: model = Group fields = ('url', 'name', 'elements') views.py class AddElement(APIView): def get(self, request, pk, format=None): serializer = ElementSerializer(context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request, pk): group = DBHandler.get_group_from_id(pk) serializer = ElementSerializer(data=request.data, context={'request': request}) if not serializer.is_valid(): return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) serializer.save() # serializer.save(group = group) return Response({}, status=status.HTTP_201_CREATED) In my view, I'd like to create an Element from given data, then assign this Element to existing Group. I tried passing group as a serializer save parameter, and it worked okay (commented code), but I don't know where to go next. How can I get an Element instance from ElementSerializer? Or is there another way of working this out? -
Multiplex list of results from socket
I've setup a socket, and I'm trying to make it multiplex. So far I have got it to return 1 room & its' messages. However, I want it to return a list of rooms in a list, and all the messages in each room. def ws_connect(message): prefix, label = message['path'].strip('/').split('/') # temporarily just getting the room from URL room = Room.objects.get(label=label) # multiroom = Room.objects.all() chathistory = room.messages.all().order_by('timestamp') Group('chat-' + label).add(message.reply_channel) message.channel_session['room'] = room.label message.reply_channel.send({'text': json.dumps([msg.as_dict() for msg in chathistory.all()])}) -
how to implement postgresql replication in django?
I am having some challenge implementing database replication in django using postgresql. I followed the instruction on this page https://github.com/yandex/django_replicated/tree/master/django_replicated but i keep getting the error. 'ReplicationMiddleware' object is not callable -
getting error as "TypeError at /add_follow/1/ __init__() takes 1 positional argument but 2 were given"
urls.py """stratinum URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from imagec import views as imagec_views from contact import views as contact_views from django.conf.urls.static import static from django.conf import settings from django.core.urlresolvers import reverse admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', imagec_views.home, name='home'), url(r'^about/$', imagec_views.about, name='about'), url(r'^detail/$', imagec_views.detail, name='detail'), url(r'^profile/$', imagec_views.userProfile, name='profile'), url(r'^create_form/$', imagec_views.create_form, name='create_form'), url(r'^contact/$', contact_views.contact, name='contact'), url(r'^userProfile/$', contact_views.contact, name='userProfile'), url(r'^accounts/', include('allauth.urls')), url('', include('social.apps.django_app.urls', namespace='social')), url('', include('django.contrib.auth.urls', namespace='auth')), url(r'^$', imagec_views.ListaFollow, name="lista_follow"), url(r'^add_follow/(?P<id>\d{1,})/$', imagec_views.AddFollow, name='add_follow'), url(r'^remove_follow/(?P<id>\d{1,})/$', imagec_views.RemoveFollow, name='remove_follow') ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse from django.shortcuts import render, get_object_or_404 from .forms import AlbumForm from .models import Album … -
Django create user profile at the time of registration from submission
I am working on a Role Based Access Control system on django.where at the signup/register people will be designated to a 'department' and will be assigned a 'role' Hence I created a custom user model models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): DEPARTMENT_CHOICES = ( ('Production', 'Production'), ('Marketing', 'Marketing'), ('IT', 'IT'), ('HR', 'HR'), ('Accounts', 'Accounts'), ) ROLE_CHOICES = ( ('Manager', 'Manager'), ('Team Lead', 'Team Lead'), ('Member', 'Member'), ) user = models.OneToOneField( User,) department = models.CharField( max_length=50, choices=DEPARTMENT_CHOICES, null=True) role = models.CharField(max_length=50, choices=ROLE_CHOICES, null=True) def __unicode__(self): return unicode(self.user.first_name + ' ' + self.user.last_name) def __str__(self): return self.user.first_name + ' ' + self.user.last_name def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Profile.objects.create(user=kwargs['instance']) pass post_save.connect(create_profile, sender=User) Then i created a form like forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Profile class SignUpForm(UserCreationForm): DEPARTMENT_CHOICES = ( ('Production', 'Production'), ('Marketing', 'Marketing'), ('IT', 'IT'), ('HR', 'HR'), ('Accounts', 'Accounts'), ) ROLE_CHOICES = ( ('Manager', 'Manager'), ('Team Lead', 'Team Lead'), ('Member', 'Member'), ) first_name = forms.CharField( max_length=30, required=True, help_text='Optional.') last_name = forms.CharField( max_length=30, required=True, help_text='Optional.') email = forms.EmailField( max_length=254, required=False) department = forms.ChoiceField(choices=DEPARTMENT_CHOICES, ) role = forms.ChoiceField(choices=ROLE_CHOICES, ) … -
Django dynamics ChoiceFields choices from APIs raises ValueError
I found the answer on this How to set choices in dynamic with Django choicefield? maersu post has high vote on my question. The output from get_branch() is ["first_branch", "second_branch"] django==1.11 python 3.6.0 forms.py class FactoryPOSForm(forms.ModelForm): branch_name = forms.ChoiceField(choices=['aa', 'bb']) class Meta: model = FactoryPOS fields = [ 'branch_name', 'dealer_name', 'shop_name', 'factory', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['branch_name'].choices = get_branches() Error: File "/Users/el/.pyenv/versions/eneos-factory/lib/python3.6/site-packages/django/forms/boundfield.py", line 250, in build_widget_attrs if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute: File "/Users/el/.pyenv/versions/eneos-factory/lib/python3.6/site-packages/django/forms/widgets.py", line 690, in use_required_attribute return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) File "/Users/el/.pyenv/versions/eneos-factory/lib/python3.6/site-packages/django/forms/widgets.py", line 673, in _choice_has_empty_value value, _ = choice ValueError: too many values to unpack (expected 2) [22/Apr/2017 16:47:04] ERROR [django.server:124] "GET /admin/factories_pos/factorypos/add/ HTTP/1.1" 500 445135 Where am I miss something? -
Create a fake Database for testing API with wagtail
I need to create some tests against my APIs. APIs use wagtail pages and serve me the contents of them. I'm at the point of creating the database for the tests, but I'm not able to create wagtail pages, because I always get ValidationError: {'path': [u'This field cannot be blank.'], 'depth': [u'This field cannot be null.']} How can I do it? Do I have to create the entire site from the root down to the tree? -
Error: 'JsonResponse' object has no attribute 'read'
I need to pass multiple value to Python in Django and use the value to run the program .The code is below AppName = attendance.html views.py from django.template import loader from django.shortcuts import render from Attendance.models import attrecord, course from Attendance.utils.scripts import use from django.http import JsonResponse def whatever(request): if request.method == 'POST': userid = request.POST.get('userid') + ' ' password = request.POST.get('password') use = JsonResponse({'userid': userid, 'passoword':password}) use_a = use(response) return response_a scripts.py import sys import json import codecs def do_something(val): data = json.load(val) print(data) return (data) After the program is executed, django shows the Error: 'JsonResponse' object has no attribute 'read'. -
Memcached server fails with custom configuration
The following configuration is provided by memcachier: CACHES = { 'default': { # Use pylibmc 'BACKEND': 'django_pylibmc.memcached.PyLibMCCache', # Use binary memcache protocol (needed for authentication) 'BINARY': True, # TIMEOUT is not the connection timeout! It's the default expiration # timeout that should be applied to keys! Setting it to `None` # disables expiration. 'TIMEOUT': None, 'OPTIONS': { # Enable faster IO 'tcp_nodelay': True, # Keep connection alive 'tcp_keepalive': True, # Timeout settings 'connect_timeout': 2000, # ms 'send_timeout': 750 * 1000, # us 'receive_timeout': 750 * 1000, # us '_poll_timeout': 2000, # ms # Better failover 'ketama': True, 'remove_failed': 1, 'retry_timeout': 2, 'dead_timeout': 30, } } } It uses a out-dated third party cache backend. I wrote the following using the built in backend: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'Location': os.environ['MEMCACHIER_SERVERS'].split(','), 'OPTIONS': { 'binary': True, 'username': os.environ['MEMCACHIER_USERNAME'], 'password': os.environ['MEMCACHIER_PASSWORD'], 'behaviors': { 'tcp_nodelay': True, 'ketama': True, 'connect_timeout': 2000, 'send_timeout': 750 * 1000, 'receive_timeout': 750 * 1000, 'remove_failed': 1, 'retry_timeout': 2, 'dead_timeout': 30, } } } With this configuration I always get following error: pylibmc.ServerDown: error 47 from memcached_get(:1:views.decorators.cache.cache_): (0x2b96630) SERVER HAS FAILED AND IS DISABLED UNTIL TIMED RETRY, host: localhost:11211 -> libmemcached/connect.cc:720 -
Cannot Google Cloud VM from external
I have replicated a VM from another VM snapshot. I have assigned static IP. After launching the Django server on this VM, I can ping the static IP, but I cannot access via http://mystaticip I checked the firewall, it looks ok.... How can I solve it ? Django ok -
Django-dynamic-formset - only one select box works
I'm using Django-dynamic-formset to create template that adds formset when I click add button On my formset there are two fields, one is CharField with choice_option and the other is CharField When I click add button it adds formset properly and all my second field ( CharField with no choice_option) works well However on my first field(CharField with choice_option), only the first select box works, and when I click the another select box below, the first select box is selected This is what happens when I click 2nd or below select box How can I make every select box work properly? my code is like this which I followed https://github.com/elo80ka/django-dynamic-formset/blob/master/docs/usage.rst Thanks in advance <form> <table id="id_orders_table" border="0" cellpadding="0" cellspacing="0"> <tbody> {% for inventory_form in inventory_formset %} <tr> <td> {% if inventory_form.instance.pk %}{{ inventory_form.DELETE }}{% endif %} {{ inventory_form.inventory_type }} </td> <td>{{ inventory_form.inventory_description }}</td> </tr> {% endfor %} </tbody> </table> {{ inventory_formset.management_form }} <input type="submit" value="submit" /> </form> <script src="{% static 'js/jquery.formset.js'%}"></script> <script type="text/javascript"> $(function() { $('#id_orders_table').formset({ prefix: '{{ inventory_formset.prefix }}' }); }) </script> -
"Page not found (404)" when i click on follow r unfollow button
urls.py """stratinum URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from imagec import views as imagec_views from contact import views as contact_views from django.conf.urls.static import static from django.conf import settings from django.core.urlresolvers import reverse admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', imagec_views.home, name='home'), url(r'^about/$', imagec_views.about, name='about'), url(r'^detail/$', imagec_views.detail, name='detail'), url(r'^profile/$', imagec_views.userProfile, name='profile'), url(r'^create_form/$', imagec_views.create_form, name='create_form'), url(r'^contact/$', contact_views.contact, name='contact'), url(r'^userProfile/$', contact_views.contact, name='userProfile'), url(r'^accounts/', include('allauth.urls')), url('', include('social.apps.django_app.urls', namespace='social')), url('', include('django.contrib.auth.urls', namespace='auth')), url(r'^$', imagec_views.ListaFollow, name="lista_follow"), url(r'^add_follow/(?P<id>\d{1,})/$', imagec_views.AddFollow, name='add_follow'), url(r'^remove_follow/(?P<id>\d{1,})/$', imagec_views.RemoveFollow, name='remove_follow') ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.urlresolvers import reverse from django.shortcuts import render, get_object_or_404 from .forms import AlbumForm from .models import Album … -
As a backend developer what path should I take to imporve myself?
I want to become a backend developer, I have learned basics of python and django. I have completed some projects on my localhost, but I don't know anything about deploying website and it's problems. What do I do for faster load times, for better load balancing etc. And Secondly, where can I Learn programming concepts and get a better understanding of the architecture of django/python? -
What's the reason for IntegrityError: NOT NULL constraint failed?
I'm doing the polls apps in Django Documentation: Writing your first Django app, part 2. While working with Database API, I've found an IntegrityError. polls/models.py class Question(models.Model): question_text=models.CharField(max_length=200) pub_date=models.DateTimeField('date published') I've tried to create an object of Question model. Question.objects.create(question_text="What's up?") This gives an error IntegrityError: NOT NULL constraint failed: polls_question.pub_date But when i try this Question.objects.create(pub_date=timezone.now()) It creates an object successfully. What's the reason for IntegrityError in the first case and why it doesn't generate any error in the second case?