Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Choosing Flask For Large Web Application in 2017 is secure?
I've been working on Flask for few months now & I love the simplicity of it and decision making power it gives. I'm thinking to build a social networking app for mobile devices and I'll use REST API with both mysql and mongodb for backend integration. Tried flask-restful & find out pretty interesting and simple. Today I was searching for some token-based authentication resource to implement with Flask. But when I checked some of it's powerful extensions github page like Flask-oAuth & Flask-JWT, I saw huge lack of contribution. For example oAuth last commit was 5 years ago & JWT last commit was 2 years ago. Technology changing everyday & I'm working on my own & don't have a big team to keep updating everything from scratch. I know Flask isn't going anywhere near future but I'm worried about it's extensions future support should I really choose Flask for my project? on the other hand I checked Django I know Django is very powerful and it has lot's of active extensions support. But as I only need REST API so I thought Flask would be better choice. But now I'm really confused deciding which tools to choose. I'm ready to … -
Django: how to retrieve a form search parameters in a django generic listView
how to retrieve a form search parameters in a django generic listView. My url is: url(r'postsearch$', views.PostsList.as_view(), name='postsearch'), My generic listview is: class PostsList(generic.ListView): model = Post template_name = 'posts/post_list.html' def get_queryset(self): localisation = #how to get location discipline = #how to get discipline return Post.objects.filter(.......) and my form is: <form class="form-inline text-center" action="{% url 'posts:postsearch' %}" id="form-searchLessons" method="get"> <div class="form-group"> <input type="text" class="form-control" id="typeCours" list="matieres" placeholder="Matieres: e.g. Math, Physique,.." name="discipline"> <datalist id="matieres"> <option value="value1"> <option value="value2"> </datalist> </div> <div class="form-group"> <input type="text" class="form-control" id="Localisation" placeholder="Lieu: Bousaada, Douaouda,.." name="localisation" onFocus="geolocate()"> </div> <button type="submit" class="btn btn-default" id="btn-getLessons"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Trouver ! </button> </form> I want to get the Posts by applying a filter according to the lacalisation and matieres introduced in the search fields (in the form) -
Error send message
Try send enail html = get_html_mail(self.request, order) email = EmailMultiAlternatives('Subject', html, 'no-reply@natarelochke.ru', # to=[order.shop.email]) to=['......@gmail.com']) email.attach_alternative(html, "text/html") email.send() But have error, when i try send email: AttributeError at /success/ 'HttpResponse' object has no attribute 'splitlines' How i can fix it? -
Django error: IntegrityError: NOT NULL constraint failed: app_candidato.avaliacao_id
I'm trying to make a form using Django model that saves the data when I click the button and redirect it to a page, I was able to do the form page, only after putting the necessary data and clicking the save button I get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: app_candidato.avaliacao_id models.py from django.db import models from site_.settings import MEDIA_ROOT class Criterio(models.Model): label = models.CharField(max_length=100) def __str__(self): return self.label class Candidato(models.Model): name = models.CharField(max_length=100) e_mail = models.EmailField(max_length=100, default = '') github = models.URLField(default = '') linkedin = models.URLField(max_length=100, default = '') cover_letter = models.TextField(default = '') Ensino_superior = models.BooleanField(default = False) avaliacao = models.ForeignKey(Criterio, default = '') med = models.IntegerField(default = 0) #talvez tenha que alterrar essa linha docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True) def __str__(self): return self.name urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.canditato_list, name='canditato_list'), url(r'^candidato/(?P<pk>[0-9]+)/$', views.candidato_detalhe, name='candidato_detalhe'), url(r'^cadastrar/$', views.cadastrar, name='cadastrar'), url(r'^candidato/[0-9]+/avaliacao/$', views.avaliar, name='avaliar'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Candidato, Criterio from django import forms from .forms import CandForm, AvalForm from django.shortcuts import redirect def canditato_list(request): candidatos = Candidato.objects.all() return render(request, 'app/candidato_list.html', {'candidatos': candidatos}) def candidato_detalhe(request, pk): candidato = get_object_or_404(Candidato, pk=pk) return render(request, 'app/candidato_detalhe.html', {'candidato': … -
Django Assigning ID from Count: Avoiding Race Condition
I have a simple web app with posts and comments. For each commenter on a post I want to assign them an identifier based on the number of distinct commenters that have come before them (commenter 1, commenter 2 ect.) This is my initial attempt: comment = Comment.objects.create(**data) comment.user_identifier = comment.post.comments.distinct('author').count() + 1 comment.save() which works but leads to a race condition where if two comments are created simultaneously they have the same identifier. What's the best way to avoid this? -
How to pass a primary key from a class based view to a form?
Is there a way to get kwargs in a form? I just need the pk that has been passed to the view in my form. I tried get form kwargs with init but I wasn't able to use the pk outside of the init method. I need the pk in order to query my database and populate the form with the user's current information. I need the pk kwargs to be used where "salon_id= 18" is in the form. View.py class SalonHours(SuccessMessageMixin, LoginRequiredMixin, generic.FormView): form_class = forms.SalonHours template_name = "accounts/salon-hours.html" success_message = "Your hours have been updated!" def get_form_kwargs(self): kwargs = super(SalonHours, self).get_form_kwargs() kwargs.update({'salon': self.kwargs['pk']}) return kwargs def form_valid(self, form): monday = models.SalonHours.objects.update_or_create(day=1, salon_id=self.kwargs['pk'], defaults={'open_time': convertTime(form.cleaned_data['mondaystart'], form.cleaned_data['mondayAM']), 'close_time': convertTime(form.cleaned_data['mondayend'], form.cleaned_data['mondayPM']), 'closed': form.cleaned_data['mondayClosed']}) forms.py class SalonHours(forms.Form): def __init__(self, *args, **kwargs): self.salon = kwargs.pop('salon') super(SalonHours, self).__init__(*args, **kwargs) if models.SalonHours.objects.filter(salon_id=18).exists(): monday = models.SalonHours.objects.get(day=1, salon_id=18) mondaystart = forms.TimeField(widget = forms.TimeInput(format='%H:%M', attrs={'class': "form-control small"}), initial=convertTime(monday.open_time), required=False) mondayend = forms.TimeField(widget = forms.TimeInput(format='%H:%M', attrs={'class': "form-control small"}), initial=convertTime(monday.close_time), required=False) mondayAM = forms.ChoiceField(choices=ampm, required=True, initial=getAMPM(monday.open_time)) mondayPM = forms.ChoiceField(choices=ampm, required=True, initial=getAMPM(monday.close_time)) mondayClosed = forms.BooleanField(widget = forms.CheckboxInput(), required=False, initial=monday.closed) -
Should I test view's attributes in unit tests?
I am wondering what is a proper way to unit test a Django view, for example this one: class UserListView(LoginRequiredMixin, ListView): model = get_user_model() template_name = 'users/user_list.html' ordering = 'last_name' def get_queryset(self): self.queryset = self.model.objects.all().annotate( full_name=Concat('first_name', Value(' '), 'last_name') ) return super().get_queryset() I'm currently unit testing the get_queryset method. This gives me 100% coverage of this view, but should I also test, for example, default ordering in a unit test? Or should this be tested in an integration/system test only (e.g. using Selenium or Django's Client)? On one side, it's part of the view that influences it's behaviour, on the other side, it's used by a third party code only. -
Getting ERR_INCOMPLETE_CHUNKED_ENCODING on server when Django APIView is used
We are using Django rest_framework gunicorn Postgres Everything is working locally. But on server, when I hit request from Chrome then I got ERR_INCOMPLETE_CHUNKED_ENCODING error and when I did curl then response was curl: (18) transfer closed with outstanding read data remaining Even when I restart gunicorn then I immediately get the response for 1st request but then it hangs somewhere and further requests do not work. I am returning a blank array in response to test which is not working so response length is not the concern. In Django, I am inheriting MyView class from APIView(from rest_framework.views import APIView). When I changed APIView to View(from django.views import View) everything started working fine on server. Not sure what is causing issue? Is it APIView library or gunicorn. I tried gunicorn locally and it works. -
How I can send JSON on Django request to create a new User and Profile?
From django rest framework site examples I write my UserSerializer.py is like that: class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user And I'am sending JSON request like this: { "username": "admin", "email": "e@e.com", "password": 12345678, "profile": { "status": 1, "level": 1, "facebook_id": 1, "facebook_token": 1, "push_device_token": 1, "photo": "url.com" } } But I only get the error: Got AttributeError when attempting to get a value for field `profile` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'profile'. -
Filter data from queryset in Django wihtout returning the entire queryset
I'm trying get an attribute from a given object in Djano. I'm getting the value properly but I'm curious as if there is a better way to grab this data. I'm getting the name attribute by using: owner_name = Owner.objects.filter(id=id).values('name') And it properly returns the name attribute I'm looking for, but it is in the form of: <QuerySet [{'name': u'John Doe'}]> How can I get it to just return "John Doe" instead of <QuerySet [{'name': u'John Doe'}]>? -
How to show name instead of ID in django raw_id_field?
I have a model where the User is the ForeignKey. I have thousands of user in the database. I have added raw_id_field for search in data field and would like to know if I can use name instead of ID. -
How do I get 'hidden' property for a div with crispy forms?
I would like my html to render with 'hidden' as a property of the div: <div class="some-class" hidden> <input id="field1"....... form stuff> </div> If my form looks like this: class SomeForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div(Field('field1'), css_class="some-class"), ) How would I go about doing this? I can't seem to find this in the Crispy documentation. Right now I am doing it with jquery (after the page loads), and I could also add a class and then hide it in css, but how do I add the 'hidden' attribute to the div? -
django rest framework "put" method inserts "raw content" instead of image
when i use this method with a "post" it saves the image, but when i use "put" to update the image, it saves "raw content" on the database. i got this method "Base64ImageField" from the django rest framework api, and from what i have read this is a common error. can you help? class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): if isinstance(data, six.string_types): if 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: self.fail('invalid_image') file_name = str(uuid.uuid4())[:12] file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension class UserProfileSerializer(serializers.ModelSerializer): profile_picture = Base64ImageField( max_length=None, use_url=True, ) username = serializers.CharField(source="user.username", required=True, max_length=30) first_name = serializers.CharField(source="user.first_name", required=True, max_length=30) last_name = serializers.CharField(source="user.last_name", required=True, max_length=30) email = serializers.EmailField(source="user.email", required=True, max_length=254) password = serializers.CharField(source="user.password", required=True, max_length=254, write_only=True) access_token = serializers.CharField(source='__access_token__', read_only=True) class Meta: model = UserProfile fields = ( 'id', 'first_name', 'last_name', 'email', 'username', 'profile_picture', 'category', 'cloud_size', 'status', 'birth_date', 'death_date', 'last_access_source', 'ssn', 'password', 'access_token', ) depth = 1 read_only_fields = ('id', ) def validate(self, data): result = super(UserProfileSerializer, self).validate(data) user_data = … -
analyze DAJNGO's population script in python?
PLZ understanding me all... import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings') import django django.setup() from rango.models import Category, Page def populate(): python_pages = [ {"title": "Official Python Tutorial", "url":"http://docs.python.org/2/tutorial/"}, {"title":"How to Think like a Computer Scientist", "url":"http://www.greenteapress.com/thinkpython/"}, {"title":"Learn Python in 10 Minutes", "url":"http://www.korokithakis.net/tutorials/python/"} ] django_pages = [ {"title":"Official Django Tutorial","url":"https://docs.djangoproject.com/en/1.9/intro/tutorial01/"}, {"title":"Django Rocks", "url":"http://www.djangorocks.com/"}, {"title":"How to Tango with Django", "url":"http://www.tangowithdjango.com/"} ] other_pages = [ {"title":"Bottle", "url":"http://bottlepy.org/docs/dev/"}, {"title":"Flask", "url":"http://flask.pocoo.org"} ] cats = {"Python": {"pages": python_pages}, "Django": {"pages": django_pages}, "Other Frameworks": {"pages": other_pages} } for cat, cat_data in cats.items(): c = add_cat(cat) for p in cat_data["pages"]: add_page(c, p["title"], p["url"]) for c in Category.objects.all(): for p in Page.objects.filter(category=c): print("- {0} - {1}".format(str(c), str(p))) def add_page(cat, title, url, views=0): p = Page.objects.get_or_create(category=cat, title=title)[0] p.url=url p.views=views p.save() return p def add_cat(name): c = Category.objects.get_or_create(name=name)[0] c.save() return c if __name__ == '__main__': print("Starting Rango population script...") populate() -
Problems with using Select2 and Bootstrap styling
I'm trying to style my form using Bootstrap. I have a django-autocomplete-light control that uses Select2 and querys the database at the back-end. I have tried to use the [Bootstrap Select 2 theme][1] [1]: https://github.com/select2/select2-bootstrap-theme however this breaks the remote data link, so all I get when I search is the Bootstrap placeholder for dropdowns. Here is the relevant code: ** CSS / JS declarations <link href="/static/collected/autocomplete_light/select2.css" type="text/css" media="all" rel="stylesheet" /> <link href="/static/collected/autocomplete_light/vendor/select2/dist/css/select2.css" type="text/css" media="all" rel="stylesheet" /> <link href = "https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.6/select2-bootstrap.css" type = "text/css" media = "all" rel = "stylesheet" /> <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> <script type="text/javascript" src="/static/collected/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/collected/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/collected/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/collected/autocomplete_light/vendor/select2/dist/js/select2.full.js"></script> <script type="text/javascript" src="/static/collected/autocomplete_light/forward.js"></script> ** JQuery code in document.ready ("#id_search").select2({theme:"bootstrap"}); ** code in Django template ** <div class="p-2" body style="margin: 0;"> {{ form.search.errors }} {{ form.search }} </div> ** code in forms.py ** search = forms.ModelChoiceField( queryset=myobject.objects.all(), widget=autocomplete.ModelSelect2(url='my-autocomplete'), required = False ) ** and finally, the rendered html ** <div class="p-2" body style="margin: 0;"> <select data-autocomplete-light-function="select2" data-autocomplete-light-url="/my-autocomplete/" id="id_search" name="search"> <option value="" selected="selected">---------</option> </select> </div> Please forgive my dreadful code - been out of the web dev game for 15 years and this project is my way of acclimatising myself back in! Thank … -
'cannot import name tokenTypes' while django-wiki installation
I'm installing django-wiki exactly as shown in the docs http://django-wiki.readthedocs.io/en/latest/installation.html When I try to perform 'python manage.py migrate', I get the following error: Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/var/www/unihotel/common_apps_1/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/var/www/unihotel/common_apps_1/django/core/management/__init__.py", line 312, in execute django.setup() File "/var/www/unihotel/common_apps_1/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/unihotel/common_apps_1/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/var/www/unihotel/common_apps_1/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/lib/python2.7/site-packages/wiki/models/__init__.py", line 10, in <module> from .article import * # noqa File "/usr/lib/python2.7/site-packages/wiki/models/article.py", line 14, in <module> from wiki.conf import settings File "/usr/lib/python2.7/site-packages/wiki/conf/settings.py", line 3, in <module> import bleach File "/usr/lib/python2.7/site-packages/bleach/__init__.py", line 19, in <module> from .sanitizer import BleachSanitizer File "/usr/lib/python2.7/site-packages/bleach/sanitizer.py", line 5, in <module> from html5lib.constants import tokenTypes ImportError: cannot import name tokenTypes But when I import it with the python shell... >>> from html5lib.constants import tokenTypes >>> print(tokenTypes) {u'Comment': 6, u'StartTag': 3, u'EmptyTag': 5, u'Characters': 1, u'EndTag': 4, u'ParseError': 7, u'Doctype': 0, u'SpaceCharacters': 2} ...it works just fine. Please, any help on this would be useful! -
Django Inconsistent Migration History deleted all migrations, yet still showing in migration history: Postgress sql
I have received this error when making migrations file "/home/rickus/.local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 285, in check_consistent_history migration[0], migration[1], parent[0], parent[1], django.db.migrations.exceptions.InconsistentMigrationHistory: Migration authtoken.0001_initial is applied before its dependency users.0001_initial so I deleted all the migrations on my project and tried again. before I ran make migrations again I ran show migrations and all the migration files are showing in the show migrations output even though I deleted the actual files admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length authtoken [X] 0001_initial [X] 0002_auto_20160226_1747 contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial users (no migrations) I'm trying to fix this error but I am unsure of what to do. How is it that my show migrations is showing files I deleted? What is the best way to solve this problem? Also I am unable to locate my database, I would guess because at this point it has yet to be created? But I am sure that is wrong. -
Can django-impersonate be used cross-origin?
I'm attempting to use django-impersonate with my django-rest based server. The server is a pure REST server, and this is a fairly typical single-page app, so my statically-compiled JavaScript is hosted on a different server that's on another subdomain. However, it appears that django-impersonate cannot work cross-origin. Here's my understanding of what is going on: when you attempt to call the impersonate endpoint, it does a redirect. However, the standard browser behavior is that cross-origin redirections strip off the "Authorization" header. Which kind of defeats the purpose of the endpoint. Here's the error message I am getting: XMLHttpRequest cannot load http://192.168.33.10:8000/impersonate/1/. Redirect from 'http://192.168.33.10:8000/impersonate/1/' to 'http://192.168.33.10:8000/accounts/login/?next=/impersonate/1/' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect. My question is whether there is any workaround for this. Since the django-impersonate package controls the endpoint, I can't manipulate the CORS headers myself, and to be honest I'm not even sure it would work if I could. -
How to show forms.py file in HTML
I've created the forms.py file from the Django tutorial here, But it doesn't show how to display this in HTML. I'm using Django 1.9 and would really appreciate the help. I'm trying to create a question with 4 choices for said question. Thanks forms.py Question_CHOICES = ( ('1', '2', '3', '4',) ) class QuestionForm(forms.Form): Q1 = forms.MultipleChoiceField( required=True, widget=forms.CheckboxSelectMultiple, choices=Question_CHOICES, -
Upload Photo using Django Rest Framework
I'm trying to upload a photo using Django Rest Framework and Android Studio, but I'm getting always null when I try to retrieve this image. Models.py: class FotoCliente(models.Model): image = models.ImageField(upload_to='userpic/%Y/%m/%d/', null = true, max_length = 255) Serializer.py class FotoClienteSerializer(serializers.HyperlinkedModelSerializer): #id_cliente_cliente = ClienteSerializer() class Meta: model = FotoCliente fields = ('id','image','url') Views.py class PhotoList(APIView): def get(self, request, format = None): photo = FotoCliente.objects.all() serializer = FotoClienteSerializer(photo, many = True) return Response(data= serializer.data, status = status.HTTP_200_OK) def post(self, request, format = None): serializer = FotoClienteSerializer(data=request.data, context={'request':request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) class PhotoDetail(APIView): def get_object(self, pk): try: return FotoCliente.objects.get(pk=pk) except: return Http404 def get(self, request, pk,format=None): photo = self.get_object(pk) serializer = FotoClienteSerializer(photo,context={'request':request}) return Response(data=serializer.data, status = status.HTTP_200_OK) def post(self, request, format = None): serializer = FotoClienteSerializer(data=request.data, files = request.FILES) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) else: return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format= None): photo = self.get_object(pk) photo.delete() return Response(status=status.HTTP_204_NO_CONTENT) def put (self, request, pk, format= None): photo = self.get_object(pk) serializer = FotoClienteSerializer(photo, data= request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status = status.status.HTTP_400_BAD_REQUEST) Urls.py url(r'^api/fotos/$', views.PhotoList.as_view(), name ='fotocliente-list'), url(r'api/fotos/(?P<pk>[0-9]+)/$', views.PhotoDetail.as_view(), name = 'fotocliente-detail'), Result: { "id": … -
Django - ImageField url byte string
My model contains an ImageField as below models.py class Facility(models.Model): ... image = models.ImageField(upload_to='images/facilities', default='images/placeholder.jpg') ... I have my media root and urls set to serve media files, and I can access the placeholder.jpg image by navigating to http://my.project.ip/media/images/placeholder.jpg Here is my media root settings settings.py MEDIA_URL = '/media/' MEDIA_ROOT = 'media' MEDIAFILES_DIRS = ( os.path.join(BASE_DIR, 'media/'), ) Here is my url pattern for media files urls.py url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), And finally in my template I use the ImageField url for the src attribute of my image tag list.html <img id="facil-img" src="{{ detail_facility.image.url }}" width="227" height="150"> Now when The page is loaded I get a 404 response on the request for the image. By taking a look at the html generated by my template I have found that the url in the src attribute of the image is broken: src="/media/b'images/placeholder.jpg'" Now it looks as if it is inserting the relative path as a byte string into the media url, but I have not been able to find a solution. I have tried applying a utf-8 decode to the ImageField url string, and have also attempted to cast it as a unicode string. Any suggestions would be greatly appreciated. -
Debugging the Django Admin in PyCharm
Is it possible to debug the Django admin in PyCharm? When debugging a normal app, the templates, etc. can be accessed to put breakpoints in. However the templates for the Django admin are not listed in the Remote Libraries section of Django's file listings. N.B. I am not talking about django-admin.py, I mean this thing. -
How can I set user full name in foreignkey field with User Model using on_delete attribute?
I have a model in django that have foreignkey with User model. class News(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.SET(???)) message - models.TextField() So When any user account delete from database then in News table entries also deleted according to user. So I want that When any user account deleted then I need to set his/her full name in user field using 'on_delete=models.SET(???)' Example: If I have user that first_name = 'Neeraj' and last_name='Kumar' When I want to delete that user account then in News table I want to save his name. -
docker-compose not downloading additions to requirements.txt file
I have a Django project running in docker. When I add some packages to my requirments.txt file, they don't get downloaded when I run docker-compose up Here is the relevant commands from my Dockerfile: ADD ./evdc/requirements.txt /opt/evdc-venv/ ADD ./env-requirements.txt /opt/evdc-venv/ # Active venv RUN . /opt/evdc-venv/bin/activate && pip install -r /opt/evdc- venv/requirements.txt RUN . /opt/evdc-venv/bin/activate && pip install -r /opt/evdc-venv/env-requirements.txt It seems docker is using a cached version of my requirements.txt file, as when I shell into the container, the requirements.txt file in /opt/evdc-venv/requirements.txt does not include the new packages. Is there some way I can delete this cached version of requirements.txt? Dev OS: Windows 10 Docker: 17.03.0-ce docker-compose: 1.11.2 -
django 1.9 change username max_lenght in Django_Auth
How can I simply add more characters to Model Django_User field Username? now is limited to 30.