Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Database Migration
Hi have a django project a full project now I want to migrate to mysql from the default Sqlite3 which is the default database. I am on a Mac OS and I don't know how to achieve this process. Any one with a complete guide on how to make the switch would be appreciated. -
Why is there a string of garbled words about Django's URL?
enter image description here 麻烦用小白的角度来想哈,Thank you ! -
Multiple files through django model
Please help. I am Trying to add multiple files to my database using jquery(one file at a time). In my project each user must be able to upload multiple files. For some reason my code doesnt upload any files. Given below is my models.py file from django.contrib.auth.models import User def get_upload_path(instance, filename): return 'users/{0}/{1}'.format(instance.user.username, filename) class MusicCollection(models.Model): user = models.ForeignKey(User) document = models.FileField(upload_to=get_upload_path) def __unicode__(self): return self.user.username Could it be, the models is causing the problem? -
Multilingual model error messages aren't translated
I'm using Multilingual Models. The problem is that the errors messages doesn't get translated in the template. this is the multilingual forms.py from __future__ import unicode_literals import logging logger = logging.getLogger(__name__) from django.utils.translation import ugettext_lazy as _ from django.forms.models import BaseInlineFormSet from django import forms from . import settings class TranslationFormSet(BaseInlineFormSet): """ FormSet for TranslationInlines, making sure that at least one translation is required and that sensible default values are selected for the language choice. """ def clean(self): """ Make sure there is at least a translation has been filled in. If a default language has been specified, make sure that it exists amongst translations. """ # First make sure the super's clean method is called upon. super(TranslationFormSet, self).clean() if settings.HIDE_LANGUAGE: return if len(self.forms) < 2 and not any(self.errors): raise forms.ValidationError( _('All translations should be provided.') ) .................... for example : _('All translations should be provided.') message doesn't get translated in the template. I don't know what's wrong, since the use of _(..) is there. Any help? -
NoReverseMatch at / (reverse logout)
I get this error on the homepage of my website: NoReverseMatch at / Reverse for 'logout' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []. Here is my urls.py: from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin from profiles import views as profiles_views from contact import views as contact_views from checkout import views as checkout_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', profiles_views.home, name='home'), url(r'^about/$', profiles_views.about, name='about'), url(r'^profile/$', profiles_views.userProfile, name='profile'), url(r'^checkout/$', checkout_views.checkout, name='checkout'), url(r'^contact/$', contact_views.contact, name='contact'), url(r'^accounts/', include('allauth.urls')), ] 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 #Create your views here def home(request): context = {} template = 'home.html' return render(request,template,context) def about(request): context = {} template = 'about.html' return render(request,template,context) @login_required def userProfile(request): user = request.user context = {'user': user} template = 'profile.html' return render(request,template,context) the traceback: File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers \exception.py" in inner 39. response = get_response(request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers \base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\profiles\views.py" in home 8. return render(request,template,context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) … -
Django and Pymongo connection not getting established
I am running an application where I need to have connection between the MongoDB and the Django application. I am running the application with the command: python manage.py runserver I am using Python 3.5 on windows 10 OS Here is my settings.py file part where I am trying to attempt the connectivity between the MongoDB and Django from pymongo import MongoClient # MONGO_DATABASE_NAME = 'testdb' # MONGO_HOST = 'localhost' # MONGO_PORT = 27017 MongoClient("mongodb://localhost:27017") SESSION_ENGINE = 'mongoengine.django.sessions' SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer' The part where I am getting the connection error is : if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: # print (form.cleaned_data['for_analysis']) mongo = API_Mongo() mongo.content = form.cleaned_data['for_analysis'] mongo.save() logger.debug('Text Data saved to Mongo DB') data = form.cleaned_data['for_analysis'].encode("utf-8") The error occur at mongo.save() The following is the error: Exception Type: ConnectionError at /analyze/ Exception Value: You have not defined a default connection My complete TraceBack is available here: TraceBack -
Class Based Views (CBV), CreateView and request.user with a many-to-many relation
Based on the examples from https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/#models-and-request-user - but with a many-to-many relation instead of a foreign key relation: models.py from django.contrib.auth.models import User from django.db import models class Author(models.Model): name = models.CharField(max_length=200) owners = models.ManyToManyField(User, related_name='owners_') views.py from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(CreateView): model = Author fields = ['name'] def form_valid(self, form): form.instance.owners = self.request.user return super(AuthorCreate, self).form_valid(form) Will output "<Author: test>" needs to have a value for field "id" before this many-to-many relationship can be used. How to avoid this? -
Django Haystack - unable to build solr schema
I got following error when I tried to build solr schema: (my_env) pecan@tux ~/Documents/Django/mysite $ python manage.py build_solr_schema Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/build_solr_schema.py", line 29, in handle schema_xml = self.build_template(using=using) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/build_solr_schema.py", line 57, in build_template return t.render(c) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/template/backends/django.py", line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/template/context.py", line 287, in make_context raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than Context. Maybe these informations will be useful: mysite/settings.py file: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.11.5. 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 # 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 = '****' # SECURITY WARNING: … -
Django Admin Proxy Model Permission Django 1.11
I have created a model in one app and created a proxy model in another app. Now I want to give only view permission to a group of users for this proxy model in Django admin. #core app class Dress(models.Model): name = models.CharField("Nome", max_length=80) #enza app class EnzaDress(Dress): class Meta: proxy = True In permission gird of Django user group record page, I did not see any entry to give view permission for this proxy model(EnzaDress) in Django admin. My Django version is 1.11.5 -
Server not running
I'm a beginner in programming and I am trying run finished project in pycharm. However on trying to run the server. I was getting the following error. So can someone please explain? "C:\Program Files\JetBrains\PyCharm 2017.2.2\bin\runnerw.exe" C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\python.exe E:/download/manage.py runserver 8000 Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0330ED68> Traceback (most recent call last): File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\apps\config.py", line 120, in create mod = import_module(mod_path) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' -
How can I authenticate user using Django websockets?
I try to create a chatbot. Every user can create an account and authenticate using Tokens. This is done in Django Rest Framework. After creating an account every user has own ID in PostgreSQL database. However chat is based on a websockets. I wonder how can I set session in websockets because I need to know which user sends message. So it seems to me that the best solution would be to have the same ID using both DRF and websockets. Or maybe am I wrong? I try in the way shown below but without positive results. @channel_session_user_from_http def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) @channel_session_user_from_http def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) # @enforce_ordering @channel_session_user_from_http def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Can we start?' }) }) @channel_session_user_from_http def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
How to customize fields in django rest framework serializer
I want to create a new record in database, I set a model like below: class FooModel(models.Model) subject_key= models.CharField(max_length=2) subject= modeels.CharField(max_length=100) What I want to do is this: field 'subject_key' should be given by the client, and using the subject_key, the server will find value 'subject' and put it in the database. So I tried to use ModelSerializer to create a new record. class FooSerializer(serializers.ModelSerializer): class Meta: model = FooModel def get_subject(self, obj): if obj.subject == 'SO': return 'Stack Overflow' else: return 'Nothing in here' and main running code inside view rest api is: def create(self, request, *args, **kwargs): serializer = FooSerializer(data=request.data) if serializer.is_valid(raise_exception=True) serializer.save() foo = serializer.data I checked it successfully create a new record in database, but the new record has NULL with the column 'subject' What should I do to dynamically set the field value inside serializer? -
class based view attributes
is it necessary to fill-in fields while having form_class for form.is_valid to work? because it ain't saving. class MedicalCreateView(CreateView): template_name = 'patient/medical_create.html' model = MedicalHistory form_class = MedicalForm def get(self, request, pk): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request, pk): form = forms.MedicalForm .form_class(request.POST) if form.is_valid(): client = form.save(commit=False) # cleaned normalize data physician_name = form.cleaned_data['physician_name'] physician_address = form.cleaned_data['physician_address'] client.save() return redirect('index') -
Is there anything else I can do to this for better performance?
Am trying to write an API using Django Rest Framework, which many applications will look up to, but I think what I have done is not robust enough for Production. Coming from a Ruby environment, its advisable to add indexes to db in few cases so as not to have a very slow response. Running around to see if am on the right track, I can across this link and I felt this could be better refactored. Is there anything I can do to this to make is production worth it? Am as new as new in Python/Django. models.py from django.db import models class Cleaners(models.Model): created = models.DateTimeField(auto_now=True) firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) location = models.CharField(max_length=50) address = models.CharField(max_length=100) bankName = models.CharField(max_length=100,default='zenith') bvn = models.IntegerField(null=True) verificationStatus = models.BooleanField(default=False) image = models.ImageField(upload_to='uploads/',height_field=50, width_field=50, max_length=100) phone = models.CharField(max_length=11,primary_key=True) class Meta: ordering = ('created',) class CleanersWork(models.Model): created = models.DateTimeField(auto_now_add=True) cleanerId = models.ForeignKey('Cleaners', on_delete=models.CASCADE) ratings = models.IntegerField() availability = models.BooleanField(default=True) jobHistory = models.IntegerField() currentEarning = models.DecimalField(max_digits=7,decimal_places=2) class Meta: ordering = ('created',) class Client(models.Model): created = models.DateTimeField(auto_now_add=True) firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) address = models.CharField(max_length=100) verificationStatus = models.BooleanField(default=True) bvn = models.IntegerField(null=True) bankName = models.CharField(max_length=100,default='') image = models.ImageField(upload_to='uploads/',height_field=50,width_field=50,max_length=100) phone = models.CharField(max_length=11,primary_key=True) class Meta: ordering … -
How to get a video snapshot (thumbnail) of a video being uploaded?
There seems to be a large variety of answers, and a lot of outdated packages so some direction would be nice. What's the best way to go about it? Here's my code: models class Post(models.Model): ... image = models.FileField(null=True, blank=True) video = models.BooleanField(default=False) views if instance.image: f = instance.image.read(1024) file_type = magic.from_buffer(f, mime=True) if file_type == 'video/mp4': instance.video = True template {% if instance.video %} <video width="400" height="420" controls> <source src="{{instance.image.url}}" type="video/mp4"> <source src="{{instance.image.url}}" type="video/ogg"> Your browser does not support the video tag. </video> {% else %} {% if instance.image %} <img src="{{instance.image.url}}"> {% else %} <img src="{% static 'images/symbol.png' %}"> {% endif %} {% endif %} -
Access model instance in generic.DetailView
Is there a way to access the model instance that is going to be presented in a generic.DetailView in views.py before the template gets rendered? Something like the hypothetical function here: class MyModelDetailView(LoginRequiredMixin, generic.DetailView): model = MyModel template_name_suffix = '_details' def do_some_initial_stuff(model_instance): # do stuff to model_instace, # like assigning fields, creating context variables based on existing fields, etc. Ultimately, I would like have a user click a button for a specific model instance in one template, then get directed to this generic.DetailView template where the model is presented with some of its field values changed and some other stuff (eg. the model may have a field that acknowledges that the this user clicked the button in the previous template). Suggestions on the most efficient way to do this would be appreciated. Thanks :) -
Obtaining DRF-jwt token
Currently I am generating tokens manually, but I want to to use jwt tokens, I followed the official docs and other references but I am still unable to figure out the problem. serializers.py, in which after authenticating token is generated manually. class UserLoginSerializer(serializers.ModelSerializer): token = serializers.CharField(allow_blank=True, read_only=True) class Meta: model = User fields = [ 'username', 'password', 'token', ] extra_kwargs = {"password": {"write_only": True} } def validate(self, data): username = data.get('username', None) password = data.get('password', None) try: usern = Account.objects.get(username=username) except ObjectDoesNotExist: raise serializers.ValidationError("User does not exists") if usern.check_password(password): data["token"] = "asdasdasdasd" else: raise serializers.ValidationError("password invalid") return data urls.py from django.conf.urls import url from .views import AuthRegister, AuthLogin from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ url(r'^register/$', AuthRegister.as_view()), url(r'^login/$', AuthLogin.as_view()), url(r'^api-token-auth/', obtain_jwt_token), ] In settings I have included 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', I have used url(r'^api-token-auth/', obtain_jwt_token), but I am unable to figure out how will I generate jwt tokens. Please anyone help me out! -
Django - Almost all tests failing with the same error (NoReverseMatch)
I used to contribute to a django project, https://github.com/Cloud-CV/evalai and everything used to work fine. After doing a fresh install of XUbuntu 16.04, I tried to configure the project again. This time all commands work fine, except while I run the test suite. python manage.py test --settings=settings.dev Out of 283 tests 236 tests failed with the similar error message but the development server is working fine. This is one of the test which failed def test_unstar_challenge(self): self.url = reverse_lazy('challenges:star_challenge', kwargs={'challenge_pk': self.challenge.pk}) self.star_challenge.is_starred = False expected = { 'user': self.user.pk, 'challenge': self.challenge.pk, 'count': 0, 'is_starred': self.star_challenge.is_starred, } response = self.client.post(self.url, {}) self.assertEqual(response.data, expected) self.assertEqual(response.status_code, status.HTTP_200_OK) This is its error message. . . . . ====================================================================== ERROR: test_particular_challenge_update_with_no_data (tests.unit.challenges.test_views.UpdateParticularChallengePhase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/jeff/evalai/tests/unit/challenges/test_views.py", line 1320, in test_particular_challenge_update_with_no_data response = self.client.put(self.url, self.data) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 298, in put path, data=data, format=format, content_type=content_type, **extra) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 216, in put return self.generic('PUT', path, data, content_type, **extra) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/django/test/client.py", line 409, in generic return self.request(**r) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 279, in request return super(APIClient, self).request(**kwargs) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 231, in request request = super(APIRequestFactory, self).request(**kwargs) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/django/test/client.py", line 476, in request response = self.handler(environ) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/django/test/client.py", line 129, in __call__ self.load_middleware() File … -
Django GUnicorn in production is calling setup.php
I was checking my logs with supervisor and I got this Not Found: /phpmyadmin/scripts/setup.php WARNING:django.request:Not Found: /phpmyadmin/scripts/setup.php does someone know why this is trying to reach a php file? I'm running django 11.06 with gninx and gunicorn. Thanks -
Querying the Database: Django
Here's my code, question = Question.objects.annotate(ans_count=Count('answer')).filter(ans_count=True).order_by('-answer').distinct() I'm filtering the Questions which received answers most recently! I'm using "sqlite3". .distinct() is not working and it's repeating the questions, means if a question gets 2 answers suddenly it will appear twice in the feed. How can I prevent one question from appearing multiple times in the feed? Thank You :) -
Chosen jQuery Plugin Only Shows a Broken List
Here is my code: <div id="div_id_code" class="form-group"> <label for="id_code" class="form-control-label requiredField"> Language<span class="asteriskField">*</span> </label> <div class=""> <select class="select form-control" id="id_code" name="code" required> <option value="" selected="selected">---------</option> <option value="en">Inglés</option> <option value="zh-hans">Chino simplificado</option> <option value="zh-hant">Chino tradicional</option> <option value="es">Español</option> <option value="hi">Hindi</option> <option value="ar">Árabe</option> <option value="pt-br">Portugués de Brasil</option> ... ... </select> </div> </div> </div> ... ... <script src="{% static 'js/jquery.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/chosen.jquery.min.js' %}"></script> <script type="text/javascript"> $( document ).ready(function() { $('#id_code').chosen(); $('#id_fluency').chosen({disable_search_threshold: 10}); }); </script> When chosen() is not called, the page shows the default select widget. Otherwise it shows a broken list as below: Am I doing anything wrong here? Thank you. -
Django or conventional PHP?
Currently, I am the president and the code head of my school's IT club. The thing is, I made a website for club (which is yet to be surfaced online). I used basic HTML, CSS, JS and PHP. For now, I got the website running on Apache localhost with phpmyadmin. The dilemma I'm facing is, should I use Django instead? For now, I can code really well in Python, but have no experience in Django. The specifications of the website are: The website has a registration page using which school admins can register students for the IT fest that we are organizing. The website has an 'Events' page where all the events we have conducted or will conduct will be displayed. This info will be stored and retrieved from the database. For now I got my Events page to work by implementing a PHP loop for creating divs. The homepage has some good looking CSS and JS scroll animations. This definitely is a small scale website (don't get me wrong, complete website has not been described above). The trouble is, no one seems to take interest in coding or event organizing or anything that our group stands for. I have … -
Django 1.9 can't pass data from filled form to view
I have the form: class ContactUsForm(forms.Form): name = forms.CharField(label='Your name') phone = forms.CharField(label='Your phone') email = forms.CharField(label='Your email') and this is html code of the form: <form action="/contact_us/" method="POST"> {% csrf_token %} {{contact_us.non_field_errors}} {{contact_us.errors}} {{contact_us}} <input type="submit" class="button large" value="Submit"> </form> this form should send the data on email, so this is my view: def contact_us(request): if request.POST: contact_us = ContactUsForm(request.POST) if contact_us.is_valid(): name = contact_us.cleaned_data['name'] phone = contact_us.cleaned_data['phone'] mail = contact_us.cleaned_data['email'] message = "Name: " + name + "Phone: " + phone + "Email" + mail send_mail('Contact Us Form', message, settings.EMAIL_HOST_USER, ['my@email.com']) return HttpResponseRedirect('/thanks/') else: return render (request, 'article/index.html', {'contact_us':contact_us}) else: contact_us = ContactUsForm() return render(request, 'article/index.html', {'contact_us':contact_us}) when i fill the form i got en error that all fields are required. But all the fields there was filled. when i add required=False to every field of the form, then i receive email with empty fields. I don't know whats wrong with my form. Can you help me with that. Thanks a lot UPD: this is how look like url: url(r'^contact_us/', contact_us, name='contact_us'), -
Sphinx-apidoc strange output for django app/models.py
I get some missed info in generated documentation of django project, for example first_name and last_name, email are missed (although they are defined in a parent abstract class). How to control what gets added into documentation based on sphinx-apidoc scan? My goal is to auto-generate the docs based on documentation, but it seems that sphinx-apidoc is supposed to be used only one time for initial scaffolding I execute the following command sphinx-apidoc -f -e -d 2 -M -o docs/code apps '*tests*' '*migrations*' Output my apps/users/models.py from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import HStoreField from imagekit import models as imagekitmodels from imagekit.processors import ResizeToFill from libs import utils # Solution to avoid unique_together for email AbstractUser._meta.get_field('email')._unique = True def upload_user_media_to(instance, filename): """Upload media files to this folder""" return '{}/{}/{}'.format(instance.__class__.__name__.lower(), instance.id, utils.get_random_filename(filename)) __all__ = ['AppUser'] class AppUser(AbstractUser): """Custom user model. Attributes: avatar (file): user's avatar, cropeed to fill 300x300 px notifications (dict): settings for notifications to user """ avatar = imagekitmodels.ProcessedImageField( upload_to=upload_user_media_to, processors=[ResizeToFill(300, 300)], format='PNG', options={'quality': 100}, editable=False, null=True, blank=False) notifications = HStoreField(null=True) # so authentication happens by email instead of username # and username becomes sort of nick USERNAME_FIELD = 'email' # Make sure to exclude email from required fields if … -
Difference between installing by pip and installing globally
I am workikng with Python/Django web application, in Amazon EC2 / Debian series operating system. Application has Python setuptools library as dependency. So I installed setup this lib by this command globally: sudo apt-get install setuptools But this didn't work - application says dependency didn't resolved correctly. After some googling, I have found solution, like this: pip install setuptools. This worked for me. But I have a question - what's difference between these two? Of course, I didn't activated virtualenv, so it seems setuptools is installed globally. Would you like to bring me your experience? Please help me.