Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, React, Redux: Serving up images
I'm using a React/Redux frontend and a Django backend for a little project. I'm not using anything but the standard Django server for development. I'm trying to add an image field to an already existing UserProfile model. Currently I've got everything working except that Django won't properly serve up my images to either to the main React site or the admin site. When I either attempt to navigate to the url in question or use the Python requests library to directly request the media, the response is of type 'text/html'. Currently my model has the following field: models.py class UserProfile(models.Model): ... ... profile_image = models.ImageField(upload_to='path_to_media') project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/account/', include('account.urls')), url(r'^api/post/', include('post.urls')), url(r'.*', views.root, name='root') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'nattr'), ) account urls.py urlpatterns = ( ..., url(r'^edit_profile/(?P<user_id>[^/]+)/$', views.edit_profile, name='edit_profile'), ) account views.py def edit_profile(request, user_id): try: user = User.objects.get(pk=user_id) form = UserProfileForm(request.POST, request.FILES, instance=user.profile, user=request.user) valid = form.is_valid() if valid: profile = form.save() return JsonResponse(profile.to_user()) else: return JsonResponse({'errors': form.errors}, status=400) except User.DoesNotExist: return JsonResponse({'errors': 'cannot find user with that id'}, status=400) What am I doing wrong? I've assigned my media_url … -
Delete a from from a formset with jquery
I am trying to create a dynamic Django formset, where a user can add or delete forms from the formset. Currently I can successfully add a form but I am struggling to get the delete button to successfully delete a form. My most successful attempt actually did delete but not just the form I wanted to delete but all the forms in the formset. I am currently adding forms by adding an empty-form (provided by the formset) when a user presses the add button. Here is my current template: {% block content %} <div> <h1 class="text-center">Create New Activity</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <div id="formset"> {{ activitykeycharacteristics_formset.management_form }} {% for form in activitykeycharacteristics_formset.forms %} <div id="{{ activitykeycharacteristics_formset.prefix }}-form"> {{ form|crispy }} </div> <div id="form-controls"> <button type="button" class="btn btn-primary" id="add-form"><i class="fa fa-plus"></i></button> </div> <div id="empty-form" style="display: none;"> {{ activitykeycharacteristics_formset.empty_form|crispy }} <button type="button" class="btn btn-danger" id="delete-form"><i class="fa fa-minus"></i></button> <hr> </div> {% endfor %} </div> <hr> <button class="primaryAction btn btn-primary pull-right ml-1" type="submit">{% trans "Submit" %}</button> <a class="btn btn-secondary pull-right" href="{{ request.META.HTTP_REFERER }}" role="button">{% trans "Cancel" %}</a> </form> </div> <div class="col"></div> </div> </div> {% endblock content %} {% block javascript %} <script … -
Django pass post form data to another view
Test model have name and result fields. I get name from user, and call a function (a function or b function) to get tests result. but the function takes too long to finish so I want to start it after redirect /dashboard and while its working populate synchronously some pie chart etc. I cannot save test form with empty fields. how can i pass post fields to dashboard view? Thanks for your help. my view is something like : def aview(requests): if request.method == 'POST': form = MyForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] test = Test(name=name) test.save() #this gives error IntegrityError: null value in column "result_id" violates not-null constraint return HttpResponseRedirect('dash') else: form = MyForm() return render(request, 'a.html', {'form': form}) def bview(requests): if request.method == 'POST': form = MyForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] test = Test(name=name) test.save() return HttpResponseRedirect('dash') else: form = MyForm() return render(request, 'b.html', {'form': form}) def dashboard(request): referer = request.META.get('HTTP_REFERER') if referer.split("/")[-1] == "a": functiona(name) elif referer.split("/")[-1] == "b": functionb(name) -
Django admin :: I want to keep last selected value on adding another item
Context in django administration site I am adding a new item in a model via add button when the form is displayed, I have a dropDown with some options to choose, I choose option B and I fill other fields to complete the form I click on button save and add another When the new "add form view" is displayed I want my dropdown to set on the last choice (B option) I selected before What is your suggestion to implement that as simple is possible? Thank you -
Setting regex pattern for mongoengine 0.9.0 StringField
I use python 2.7.12 with pymongo 2.8.1, django 1.11.7, mongoengine 0.9.0 and mongodb 3.4.10. I am creating a custom user model which inserts documents in a regular mongodb collection. I inherited the 'Document' class from mongoengine to create the string password field. I've been trying to create a regex pattern for the following conditions: Length: 8-25 characters At least 1 uppercase letter At least 1 lowercase letter At least 1 number At least 1 special character I tried using re.compile() in the following way: import re regexp = re.compile('[A-Za-z0-9@#$%^&+=]', max_length=25, min_length=8) password = StringField(regex=regexp) I sent HTTP POST requests with invalid passwords and it only throws an error when the length is lesser than 8 or greater than 25, otherwise they pass. I'm new to mongoengine and I'm not really sure what kind of input the regex parameter takes, neither have I been able to find examples for StringField. So what am I doing wrong? -
Django Autovalidation mixin does not work with Decimal
Following a well know pattern in Django, I created a mixin to ensure full_clean() is called whenever the save() method is triggered. class AutoValidable(models.Model): """ Will force the validation process on save. """ def save(self, *args, **kwargs): self.full_clean() super(AutoValidable, self).save(*args, **kwargs) class Meta: abstract = True Then, I use it in this class: class TaxRate(AutoValidable, models.Model): percentage = models.DecimalField( unique=True, max_digits=4, decimal_places=3, validators=[MinValueValidator(0), MaxValueValidator(1)]) However, creating a TaxRate object raise an Error: >>> TaxRate.objects.create(percentage=0.055) django.core.exceptions.ValidationError: {'percentage': ["Assurez-vous qu'il n'y a pas plus de 4 chiffres au total."]} If I remove the autoValidable class, no problem. -
How to change the form of GCBV?
I have GCBV @method_decorator(login_required, name='dispatch') class PostUpdateView(UpdateView): model = Post fields = ('message', ) template_name = 'edit_post.html' pk_url_kwarg = 'post_pk' context_object_name = 'post' def get_queryset(self): queryset = super(PostUpdateView, self).get_queryset() return queryset.filter(created_by=self.request.user) def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_at = timezone.now() post.save() return redirect('topic_posts', pk=post.topic.board.pk, topic_pk=post.topic.pk) I need to add pagedown widget to the form, where cad I add it? I know how to do it with FBV but with GCBV we dont define the form which we need, How can I define and change it? -
The difference in functions of `**kwargs` and `**initkwargs`
In Django's source code, there are **kwargs and **initkwargs. django/base.py at master · django/django class View: def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.items(): setattr(self, key, value) and @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) What's difference of them in usage? -
Fill Django CreateView form with read only foreignKey value
When showing a CreateView form I would like to fill a foreignKey value using data from the logged in user. I want this to be read only. My models are: # User profile info class Profile(models.Model): # Relationship Fields user = models.OneToOneField(User, on_delete=models.CASCADE) school = models.ForeignKey('eduly.School', default=1) notes = models.TextField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class School(models.Model): # Fields name = models.CharField(max_length=255) address = models.TextField(max_length=500, blank=True) email = models.CharField(max_length=30) phone = models.CharField(max_length=15) contactName = models.CharField(max_length=30) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def __str__(self): return self.name def get_absolute_url(self): return reverse('eduly_school_detail', args=(self.slug,)) def get_update_url(self): return reverse('eduly_school_update', args=(self.slug,)) class Teacher(models.Model): SCHOOL_ADMIN = 0 CLASS_ADMIN = 1 TASK_ADMIN = 2 ROLES = { (SCHOOL_ADMIN, "School administrator"), (CLASS_ADMIN, "Class administrator"), (TASK_ADMIN, "Task administrator") } # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) email = models.CharField(max_length=30) roles = models.IntegerField("Role", choices=ROLES, default=1) # Relationship Fields school = models.ForeignKey('eduly.School', ) class Meta: ordering = ('-created',) def __str__(self): return self.name def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('eduly_teacher_detail', … -
Why django models changes column to INT automatically
This is my models file: class BC_list(models.Model): Bc_id = models.CharField(max_length=25, verbose_name="BC ID") def __unicode__(self): return str(self.Bc_id) class cdList(models.Model): BC = models.ForeignKey( BC_list ) ProcessName = models.CharField(max_length=25, verbose_name="ProcessName") def __unicode__(self): return str(self.BC)+'-'+str(self.ProcessName) And can anyone tell me why the BC column is a INT instead of Varchar ? As you can see, Bc_is is a charfield. I don't understand it, Thanks in advance, Dawid -
Doesn't Nginx support Django admin static files
My django site user-end is running good with the static files but don't know why all the admin panel static files is not working. While it's working normally but not with linux any idea ?? nginx .conf file upstream sample_project_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/me/SPEnv/run/gunicorn.sock fail_timeout=0; } server { listen 800; server_name <your domain name>; client_max_body_size 4G; access_log /home/me/logs/nginx-access.log; error_log /home/me/logs/nginx-error.log; location /static { root /home/me/DjangoProjects/SP/SP; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; # set "proxy_buffering off" *only* for Rainbows! when doing # Comet/long-poll stuff. … -
Deploy Heroku app with package that is not available in pip
I am trying to deploy a new version of my Django application to Heroku, but I am using a package that is not available in pip. So when I put this package in the requirements.txt the deploy fails with the message that this requirement cannot be found by pip (logically). Then I tried to push the directory containing the package to the heroku git repo and istalled the package using the heroku bash and the setup.py file (and removed it from the requirements file). This installation was successful, but when I deploy the application I get the error that this package cannot be found. So my question is: How to properly use python packages not available in pip on Heroku? -
Django: handle CSRF error as form error
When a Django form has a CSRF error, it redirects to a 403 page. Is there any way to handle that as a form error (i.e. showing an error message in the form page) instead of redirecting? -
Load pdf on template django with security
How to load a pdf file that is in a private directory in an embed tag that is not accessible by url ??? <div class="object-file"> <embed class="pdf403" src="{{ object.file.url }}#toolbar=0&navpanes=0&scrollbar=0" style="width:100%;" height="780" Enable comment_users = CourseEntry.list_course_progress_users( ContextMenu='0' type='application/pdf'> </div> -
django,A server error occurred. Please contact the administrator
This Is My settings.py """ Django settings for login project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/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.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '0^q9&^oblkc28287hb-2ub3pnyo9nub@-@=m56)g*mn_u8m@14' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1', '111.222.333.444', 'mywebsite.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'login', 'django_filters', 'bootstrap3', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'login.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'login.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3' } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE … -
How show embed content in Django Templates
I wanted to know how to show url embed content in django template taken from database -
Pagination in django rest, ListAPIView
i'm new in django and i have a little problem in the pagination of objects. my model: class FacebookBien(models.Model): uid = models.IntegerField(primary_key=True) ref_agence = models.IntegerField() loyer = models.FloatField() prix = models.FloatField() ville = models.CharField(max_length=200) code_postal = models.CharField(max_length=200) ref_type_bien = models.IntegerField() surface_totale = models.FloatField() source = models.CharField(max_length=200) nombre_de_pieces = models.IntegerField() date_modification = models.DateTimeField() class Meta: managed = False # db_table = 'public\".\"bien_recherche' db_table = 'recette_facebook\".\"vue_facebook_bien_recherche' my view: class BienAgence(generics.ListAPIView): queryset = FacebookBien.objects pagination_class = SmallPagesPagination def get(self, request, *args, **kwargs): res = request.GET if FacebookBien.objects.filter(ref_agence=int(kwargs['ref_agence'])).exists(): toto = self.queryset.filter(ref_agence=int(kwargs['ref_agence'])) if (res['type'] == 'bien'): toto = toto.filter(prix__gte=int(res['p_mini'])) toto = toto.filter(prix__lte=int(res['p_maxi'])) if (res['prix'] == 'croissant'): toto = toto.order_by('prix') elif (res['prix'] == 'decroissant'): toto = toto.order_by('-prix') else: toto = toto.filter(loyer__gte=int(res['p_mini'])) toto = toto.filter(loyer__lte=int(res['p_maxi'])) if (res['prix'] == 'croissant'): toto = toto.order_by('loyer') elif (res['prix'] == 'decroissant'): toto = toto.order_by('-loyer') if (res['surface'] == 'croissant'): toto = toto.order_by('surface_totale') elif (res['surface'] == 'decroissant'): toto = toto.order_by('-surface_totale') elif (res['date'] == 'croissant'): toto = toto.order_by('date_creation') elif (res['date' == 'decroissant']): toto = toto.order_by('-date_creation') toto = toto.filter(surface__gte=int(res['s_mini'])) toto = toto.filter(surface__lte=int(res['s_maxi'])) serializer = FacebookBienSerializer(toto, many=True) # noqa return Response(serializer.data) else: return Response(None) my pagination.py: class SmallPagesPagination(PageNumberPagination): page_size = 6 The problem is that it does not put me at all 6 objects per page. if … -
Unable to import a repo
I've installed a package using pip install -e git+git://... which is quite expectedly cloned into ./src. Does anyone know how to import it in the django code? All of the (importable) external libraries are in ./lib/python2.7/site-packages, but my code can't seem to see packages in ./src though. Any thought appreciated. -
Django: let request.FILES.get() return an empty string even if no file selected
I have the following HTML form: <form ... enctype="multipart/form-data"> <input name=title> <input type=file name=attachment> <input name=title> <input type=file name=attachment> ... And in Django: titles = request.POST.getlist('title') files = request.FILES.getlist('attachment') The problem is: the user may or may not select a file for each title; hence, the lengths of titles and files may not be the same. Is there a way to force <input type=file...> to return an empty string instead of nothing, such that the lengths of the two lists are always the same? Otherwise, how do I map between the two lists? -
How can I loop through all the properties of an python object in django templates
I have django template and I get a some object. I want apply for in cycle for all atributes this object. {% for point in Object %} <h1>{{ Object[point] }}</h1> {% endfor %} -
Django server 403 Forbidden: incorrect proxy
I've a problem with django server, namely: Server has started correctly: System check identified no issues (0 silenced). November 10, 2017 - 13:39:31 Django version 1.11.4, using settings 'etTagGenerator.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But i'm not able to open it in browser: 403 Forbidden: incorrect proxy service was requested I'm using firefox. Proxy on my machine is set, firefox doesn't use proxy for localhost and 127.0.0.1 -
Django: Changing UTC to timezone aware
I have start_date of DateField() which is in utc.I want to convert it to timezone aware object I tried writing {{ start_date|timezone:'Asia/Calcutta' }} It displays nothing.Is timezone only for DateTimeField()?How can I use it on DateField(). -
About virtualenv and version of python?
I need help in understanding with venv. I have installed venv with virtualenv venv -p python3.6. I have activated it (venv) and install django pip django`install django` And so, when I work with my project should I always activate venv or not? Because I run my manage.py without venv and using python2, but I need python3. And then I run with active venv with python3 I got mistakes like this: ModuleNotFoundError: No module named 'forms' -
What's an instance of class-based views
I am learning Django's class-based views. I don't understand what's the instance of class Views For example: from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request): # <view logic> return HttpResponse('result') What's the instance of class 'MyView' during this request-and-respond process? -
Django - multiple fields lookup [duplicate]
This question already has an answer here: Multiple lookup_fields for django rest framework 2 answers I've an endpoint that accepts either the uuid or the phonenumber of the user url(r'^(?P<uuid>[0-9A-Fa-f+-]+)/$', view_name.as_view()), Now, I've a queryset that filter accordingly. Here it is. class UserDetails(RetrieveUpdateAPIView): serializer_class = UserSerializer lookup_field = 'uuid' def get_queryset(self): """ Over-riding queryset. Filter user based on the user_id(Works for both msisdn & uuid). """ msisdn_or_uuid = self.kwargs[self.lookup_field] queryset = Users.objects try: # checking if the forwarded param is user_id or msisdn. UUID(msisdn_or_uuid) instance = queryset.filter(uuid=msisdn_or_uuid) except ValueError: instance = queryset.filter(msisdn=msisdn_or_uuid) print instance # prints a queryset. But returns 404. return instance Now the problem is whenever phone number is passed, it returns 404 not found. But the objects clearly exist. Is there any setting in DRF that filters on two or more fields simultaneously without over-riding the get_queryset.?? I found a related question, but couldn't make it work. Where am I going wrong?