Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Looping dynamic content on bootstrap4 rows
I guess I have a simple question regarding using a for loop and indexes I am trying to set up dynamic row and column using bootstrap4 and Python (Django). I am looping through a list and What I am trying to do is to print each value in a column with a maximum of 3 columns. I tried using : {% for member in project.team_id.members.all %} {% if loop.index % 3 == 0 %} <div class="row"> {% endif%} ... ... ... ... {% if (loop.index % 3 == 0 or loop.last) %} </div> {% endif %} {% endfor %} but it does not work.. Could you help me to figure it out please ? Thx you ;) -
return self.user as foreignkey
I have a model with foreignkeys. For this model I want to set the 'def str' as the user. I have done this from django.contrib.auth import get_user_model User = get_user_model() class Rosters(models.Model): place = models.ForeignKey('Places') position = models.ForeignKey('Positions', blank=True, null=True) user = models.ForeignKey(User, related_name='roster') validfrom = models.DateTimeField(blank=True, null=True) validto = models.DateTimeField(blank=True, null=True) def __str__(self): return self.user This will fetch username and show in admin pages. But when I try to create a new Roster. I get a TypeError __str__ returned non-string (type User) I can remove the 'def str...' and create a Roster with no problem. But each Roster shows as Object in admin pages. So I can add back the 'def str..' to see the usernames of each roster. I want them to always display as usernames. And I can't figure out why it's not working when I'm adding rosters. -
Couldn't solve the django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured
Read before marking as duplicate please. I encountered with this annoying and classic problem. Then, I've tried everything that was suggested on the other topics over and over again. Then, I've decided to create a simpler project just to check if the same problem would occur at the beginnig steps of the project and yes it did. Now, I want to share my .py files with you and hopefully you can point out my mistake. I can't continue coding because of this problem since hours. Python version: 3.6 Django version: 1.10.6 Project's name: blog App's name: home This is settings.py file: 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.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'f+12*o0a+=^=)w=#a8xp-z3r1*)akxc&ob07+t3c$a!sguo8eb' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
Wrong form is being displayed in a Django project
I have a django project I created. This django project is split into two apps, the user and common. I have a method in the user app that allows the user to submit a form which will create a new Django user. Once the form is submitted and process I want to redirect the user to the testing page in the common app and display a html template that says testing page. Everything is working, the form is being processed and the redirect is occuring. I know this because the url changed to the expected url which will display the html testing page. For some reason, even though the url is transfering to the correct one, the html template being displayed is actually the signup form html template not the correct template. Here is the code from the common app: views.py # testing method def test(request): return render(request, 'common/test.html') urls.py: urlpatterns = [ url(r'^test/$', views.test, name='test'), ] test.html: {% extends "base.html" %} {% block standard %} <p>testing page</p> {% endblock %} here is the redirect from the users app: this is in the signup def after the user has been created return redirect('test') -
location.reload() not working properly in mobile devices
location.reload() not working properly in mobile devices... location.reload() is working fine on desktop browsers but not working on mobile browsers (android)... i work in Django selected fileds that come from ajax selections of modelchoicefields querysets are lost after window.location.reload(). everthing works fine in desktops but not in mobile devices. what should i change or add??? you can see the difference in added image...difference between desktop and mobile device working.. code is a standart ajax call for Django to dynamically select fields that are related to the previous selection... <script> function prosecFunction() { var response = ''; var selected = document.getElementById("id_proje").value; console.log(selected); $.ajax({ url : "demirbas_ariza_listesi/", type : "GET", dataType: "text", data : { 'selected' : selected, }, success: function() { window.location.reload(); }, failure: function() { alert("hata var....veri aktarılamadı..."); } }); /* ajax kapa...*/ } </script> <script> -
Django disabled field with initial data raises validation errors
I have a field in my form that is given an initial data and disabled if a user is staff (admin can choose from a list). I have this field disabled for staff with the code line below. self.fields[''].disabled = True After uprading to django 1.11.7 it started raising validation errors. I tried making it read only with self.fields[''].widget.attrs['readonly'] = True Css becomes read only, but i can still make changes. Is this a 1.11.7 bug or something has happened in the changes on how the disabled function works. I couldn't find anything new in the documentation -
why i am not able to post the data in db through form, views and models?
forms.py : from django import forms from django.forms import ModelForm from django.utils import timezone from .models import Book class BookCreateForm(forms.Form): title = forms.CharField(required=True) author = forms.CharField(required=True) description = forms.CharField(widget=forms.Textarea) genre = forms.CharField(required=True) book_image = forms.ImageField(required=True) publishedDate = forms.DateField(widget=forms.widgets.DateInput(format="%m/%d/%Y")) price =forms.DecimalField(decimal_places=2,max_digits=8) stock = forms.DecimalField(decimal_places=2, max_digits=8) models.py: from django.db import models from django.utils import timezone # Create your models here. class Book(models.Model): title = models.CharField(max_length=250) author = models.CharField(max_length=250) description = models.TextField() genre = models.CharField(max_length=60) book_image = models.ImageField() publishedDate = models.DateField(default=timezone.now) price = models.DecimalField(decimal_places=2, max_digits=8) stock = models.DecimalField(decimal_places=2, max_digits=8) class Quote(models.Model): quote_name = models.TextField() quote_author = models.CharField(max_length=250) views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse,HttpResponseRedirect from django.views.generic import TemplateView,ListView,DetailView from .models import Book from .forms import BookCreateForm # Create your views here. def book_createview(request): template_name='bookstores/addbook.html' # print (request.GET) # print (request.POST) if request.method == "GET": print ("Get ") print(request.GET) if request.method == "POST": print("post data") print (request.POST) formed=BookCreateForm() form = BookCreateForm(request.POST) if form.is_valid(): obj =Book.objects.create( title=form.cleaned_data.get('title'), author=form.cleaned_data.get('author'), description=form.cleaned_data.get('description'), genre=form.cleaned_data.get('genre'), book_image = form.cleaned_data.get('book_image'), publishedDate = form.cleaned_data.get('publishedData'), price = form.cleaned_data.get('price'), stock = form.cleaned_data.get('stock') ) if form.errors: print (form.errors) #return HttpResponseRedirect("/store/") context ={} return render(request,template_name,context) TemplateView: {% extends "home.html" %} {% block head_title %}Adding book || {{ block.super }} {% endblock head_title %} {% … -
Django: Which Apache modules are required for my application
Good day everyone, I have a clean installation of a Django application with an Apache server. I have noticed that Apache have a lot of modules loaded. I want to know which ones are the required to run my Django application. My intention is to disable the unnecessary modules to make Apache a little faster. -
Triggering and use template to send sms
class CMSSmsTemplate(models.Model): """ This is the internal template Which will have the SMS Trigger field/the SmS body/the SmS Template """ sms_trigger = models.CharField(max_length=128) sms_body = models.CharField(max_length=255) sms_Body = models.TextField(blank=True, null=True) sms_template_name = models.CharField(max_length=128) I have this model, which i'm using to send my sms, what triggers my sms to be sent is mainly the sms_template_name, how can i efficiently use,to trigger and send the sms. Any advices? -
Django MonitorField() not working with Foreign Key if when condition is added
Greeting, as mention in the question, my MonitorField stop updating the date when I add a when condition in it, below is my code : class A(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class B(models.Model): status = models.ForeignKey(A, on_delete=models.CASCADE, default=4, null=True) monitor = fields.MonitorField(monitor='status' when=[1]) -
Django class based DeleteView check constraints
In a django application, there are two model with 1-M relationship, e.g. Parent and Child. I need to delete the Parent model object using DeleteView class. Before deleting the object, I need to check if it has any child objects and if there was, it returns an error message instead of deleting the object. Currently my DeleteView, like the default is: class ParentDeleteView(DeleteView): model = Parent def get_success_url(self): return reverse_lazy('parent-list') Which methods should I implement to check constraints? -
Assigning template tag in base template
I want to get a value in my base.html template which every other template extends. Here's my custom tag code: #my_tags.py from django import template register = template.Library() @register.simple_tag # or assignment tag, doesn't matter def is_true(): return True And when used in base.html as such: <!-- base.html --> {% load my_tags %} {% is_true %} The string "True" is printed. However if I try to do this <!-- base.html --> {% load my_tags %} {% is_true as my_var %} <h1>{{my_var}}</h1> I get TypeError at /'WSGIRequest' object does not support item assignment. Following the stack trace it appears that "context" just isn't available at base.html. If I put this in any of the templates extending base, I can assign the variable and print it as I desire. Assignment is important because I need to condition on the value returned. Is this a known limitation that as doesn't work in a base template? How can I get the returned value in base.html? -
How to create Form in Django admin
I wish to process uploaded data in django admin and post the processed data on the same window. Let me explain you in brief. In django admin panel, There will be text field to enter his name. He will enter his name and click on submit button. Once he clicks, on the same page his name will get printed (may be posted by program). Can you help me to implement this. Actually I want to implement another application. But this will solve all my problems. -
How To serialize the nested json objects in Django rest framework
{ "KEY1":[ { "B1":"Value of b1", "B2":"Value of b2" } ], "KEY2":["first element of key2","second element of key2"] } and once we validate the JSON, I have to convert it into class object -
Universally usable files for django project - Django
I am making a django project and within the project I have 3 different apps. registration, users, groups. I dont want to have to print all of the import statements in the views.py file for each app. I also dont want to have to retype any of the methods for functions in each of the views.py file for small functions like generatingRandomNumbers. Is there a way to create a single file within the project directory that has all of the import statements or all of the methods that i can call at the beginning of each views.py file.... Also where would i put the file if possible, and how can i call the fill with all of the import statements at the top of each of the views.py file so i dont have to keep retyping all of it... Here is my current directory: Another question is how can i setup the urls in a way that i can redirect to any url within the project no matter which app it is localated in... Django documentation does not explain any of this at all... an example would be a view in the registration app redirects to a url in the … -
Can't import external libraries in Django
I have an app that needs pygal to create the graph it's gonna display. /VotingApp /mysite /main /register /results /migrations /templates __init__.py admin.py apps.py models.py tests.py urls.py views.py /voting manage.py In results.views.py I have, as a means of testing: from __future__ import unicode_literals import pygal from pygal.style import Style from django.shortcuts import render def index(request): pie_chart = pygal.Pie(inner_radius=.75, style=Style(font_family='quiroh, sans-serif')) pie_chart.title = 'Browser usage in February 2012 (in %)' pie_chart.add('IE', 19.5) pie_chart.add('Firefox', 36.6) pie_chart.add('Chrome', 36.3) pie_chart.add('Safari', 4.5) pie_chart.add('Opera', 2.3) return render(request, 'results/results.html', {'pie': pie_chart}) And on results.html {{ pie.render()|safe }} However I get this error when I go to the index view: ImportError: No module named pygal I've already installed and tested pygal outside of the django folder and it works fine, so I don't know what else can I do. Bokeh doesn't work either. I don't know what else can I do. If it serves for anything, I didn't use a virtual environment when I started the project. -
Django /subdirectory/admin/ redirects to /admin/login/?next=/admin/
I set up a Django server on port 8011, and have a nginx serving it as a subdirectory on port 80. Static files, good. Pages, good. But when I access /subdirectory/admin/, it takes me to: /admin/login/?next=/admin/ Which is of course a 404 error, but if I access /subdirectory/admin/login/?next=/admin/, it works fine. Any ideas? Do I need to set a variable in the settings.py? urls.py: url(r'^admin/', admin.site.urls), -
Django permission belongs to group, but user on that group has no group's permission
I decided to not use django-guardian because If my customer delete/create Group I have to add more overhead on my ModelManager to transfer the existing permissions to new group. Therefore let the instances got filtered by filter_queryset through Django REST is fine for my case. FailedTestCase: https://gist.github.com/elcolie/178c6cfa3f980cf6ca9d39bba29a9e33 Remark: Somehow I cannot post my tests.py here. SO says my post contain code this is not properly formatted as code. Question: Where am I wrong? Gists: https://gist.github.com/elcolie/684ba34391d0a94df7ca98855cea765b https://gist.github.com/elcolie/64a3a3daf22240b2072e113eb10164e2 https://gist.github.com/elcolie/d28e7fcf54334a9f13df5fff1b7d9fe0 References: Django user has_perm returning false even though group has permission Django user not getting the assigned group's permissions django group permission -
Django: make_password outputs different password than django.auth
I am trying to implement a user password history, so that the user can not use the same passwords twice when updating his password. I am using the Django auth module for this. To achieve that I just save the new passwords the user creates in an additional sql table my_userpasswordhistory. After that, I created a new PasswordValidator to check the new password against the old passwords. They way I intend to do that, is to take all old passwords from the user in the database, split off the salt and run make_password(newpassword, salt). See the following code: pass_list = UserPasswordHistory.objects.all().filter(user=user) for old_pass in pass_list: #split password so we get the hash and the salt split_pass = old_pass.password.split('$') salt = split_pass[2] pw = split_pass[-1] if make_password(password, salt) == pw: raise ValidationError( _('Your new Password needs to be different from your old one!'), code='password_identic' ) Problem The problem I am having is that somehow, the password generated by Django in the admin backend (via interface) is different from the password I create with using make_password(). The value in the database for my password is: select password from my_userpasswordhistory; pbkdf2_sha256$36000$trlHVdErn23Z$BAxX9p3o54QGovIWluP3dM7q73HQNZy9VuYOA6rv268= However, using the salt trlHVdErn23Z on the an identic raw password, I … -
Saving django object with foreign key returns not null constraint failure on foreign key ID
I am trying to save a django object which is connected to another model via foreign key. useThisTopology = SaveTopology.objects.filter(name = topName)[0] newSaveDev = SaveDev() newSaveDev.savetopology = useThisTopology newSaveDev.save() When the .save() function is used, it returns a not null constraint failure at saveDev.saveTopology_id but I have validated that the useThisTopology object contains an ID Here are the models that I use class SaveDev(models.Model): saveTopology = models.ForeignKey( SaveTopology, on_delete=models.CASCADE, ) class SaveTopology(models.Model): name = models.CharField( max_length = 40 ) -
Webform to input a table with variable number of rows and columns in Django
I am creating a web form using Python Django and I want to create a web form that allows users to input a table with their own column and row names. User should be able to add row or columns as well. I have read django formsets documentation but I am confused as to how to implement this dynamic table. Any help would be appreciated! Thank you. I also have a model object to which I want this table to be an attribute of, if possible. -
Move Files with S3BotoStorage
I'm using S3BotoStorage from django-storages to handle my media and static files on my S3 Bucket for my Django backend. Everything works as expected, but the backend raises a not ImplementedError because it is not a local filesystem when I call self.image.path on a where Image is a models.Image Field. This is expected behavior. However I'm using the path to move the image with os.rename (which wouldnt work on my bucket as well). What would be the approach to move that file on the bucket? -
Django Serializer redirect
I'm freshman in the Restful,I have some issues to figure out about 'Serializer page jump',the class is as follows, I want to know how to decide brand_instance return to which page and how I can redirect other page with some object data? class NameInteractiveSerializer(serializers.ModelSerializer): class Meta: model = Name fields = '__all__' def create(self, validated_data): if validated_data['Name'] and validated_data['Name_SC']: pref_flag = "2" pref_name = validated_data['Name'] elif validated_data['Brand_Name_SC']: pref_flag = "1" pref_name = validated_data['Name_SC'] else: pref_flag = "2" pref_name = "" Name_instance = Name( Name=validated_data['Name'], Name_SC=validated_data['Name_SC'], Pref_Name_Flg=pref_flag, Status = '1', ) name_instance.save() name=name_instance.save() return name -
Django query sets using CAST
Hello guys I'm trying to order a string in a django queryset using CAST but I can not achieve the order, I need a hand. s = Empresas.objects.filter(codigo__startswith="B") \ .extra({'codigo_uint': "CAST(codigo as INTEGER)"}) \ .order_by('-codigo_uint') for x in s: print x.codigo what I got is: B-001 B-999 B-1000 B-897 B-010 B-099 B-100 B-500 B-9999 How can I get the correct order of this ? I really appreciate the help -
"Next" and "Previous" button on Django, on posts with Slugs
What I want is to create "Next Post" and "Previous Post" on Django. What I have managed to do until now is to link the button to a page where the primary key is one above or one below the current post: <a class="btn btn-default" href="{% url 'post_detail' slug=post.slug pk=post.pk|add:'1' %}">Next</a> There are two issues: one is with the Slug and with the URL, and the other is with the showing (or hiding) of the button. When I click next, I am took to the next post (if it exists. If it doens't I receive an error telling me that such a page doesn't exist). The URL remains the same as the previous post, correspondingly: If I click it three times, the URL displayed will be the one of the second post. What I would like is to somehow also display the corresponding slug. The second problem, is that I want to disable the button if there is no post before or after. But the following piece of code: {% if post.pk|add:'1' %} Which is what I have come up with up until now, but apparently what it does is to check if such a number exists, not if the …