Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Center table after BS 4.0 collapse?
So, I'm having trouble with tables that are displayed after a collapse event from Bootstrap 4.0. This is how they look if they are displayed by default (nice & centered): But if I display them when clicking the "+" icon from the main table, they appear like this (they align to the left window): I can't see why this happens, as I'm using BS row/col-md system to center them: <div class="row mt-4 collapse" id="{{ entitat.codi }}"> <div class="col-md-1"></div> <div class="col-md-10"> <table class="table table-sm"> -
Django Social Auth Google OAuth2 not raising exceptions when user does not exist
I'm having problem with displaying error message when using Python Social Auth in my Django application when associating users by email, but user does not exist in django.contrib.auth.models.User. Objective: I use Social Auth to log in users into my Django app. Alongside I use django.contrib.auth.models.User to let users login with standard username + password. We decided that the admin will first create user account in auth.models.User with username and email. Later if the user uses Google Account (in this case mostly GSuite), he can log in with Google OAuth2 and Django Social Auth associates user with his Gmail's mail (I'm aware of security problems with that but we discussed it over). Problem: Logging in existing users work like charm, but when user does not exist in database auth.models.User, when trying to log in with Social Auth I'm getting redirected to my SOCIAL_AUTH_LOGIN_ERROR_URL, but without any error message (I'm using Django's message system to catch any exceptions). My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... 'social_django', ] 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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], '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', … -
Django timedelta (DurationField) to seconds
How to convert a timedelta to seconds in Django? I have a Django backed serving an API which at some point returns a calculated field: enhanced_client = client.objects.annotate(duration=ExpressionWrapper((F('end_time')-F('start_time')), output_field=DurationField())) with the following value (timedelta): P0DT00H02M00.102730S How can I turn this into seconds in javascript? I'm also using moment js but I can't parse this at all. Thanks -
Django ORM Count individual related field with condition
I have a model Game and a model Line. Line has a foreign key to Game and a DateTimeField called created which records when the line was created I would like to annotate a queryset of Game, to count all Lines in each game that were created after a certain date. something like games = Game.objects.all().annotate( recent_lines=Count(lines, filter=Q(lines__created__gt=date_to_check))) This does not work as it count ALL the lines as valid... How can I achieve what I am trying to achieve? -
Using Multiple models with Class Based Views and pagination
I have 2 models Categories and Products. A Category have multiple products and a Product can be in multiple categories. A Category has a FK to itself. `class Product(models.Model): categories = models.ManyToManyField(Category, related_name='products') class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE)` For a template I need: the Category data and hist children data The Product in the category and subcategories Pagination I'm using Class Based Views, and I don't know which to use as model attribute for the class,because: if I use Category a I don't know how to set Pagination by Product and not by Category if I use Product, I need to get the category slug/id from url and filter Product queryset by category and also pass them to context -
Django model form: reverse side of m2m not saving
After upgrading from Django 1.8 (python 2.7) to Django 2.0 (python 3.6) I have an error with this form and reverse m2m widget: models.py class Treatment(Model): ... class Specialty(Model): treatment = models.ManyToManyField(Treatment, related_name='specialties', blank=True) ... . This is the Form for the treatment model. It allows to also edit the specialties (reverse m2m). It worked fine before the upgrade. forms.py class TreatDetail(forms.ModelForm): specialties = forms.ModelMultipleChoiceField( queryset=Specialty.objects.all().order_by('specialty_de'), required=False, widget=FilteredSelectMultiple('Specialties', False), ) def save(self, commit=True): treatment = super(TreatDetail, self).save(commit=False) if commit: treatment.save() if treatment.pk: treatment.specialties = self.cleaned_data['specialties'] self.save_m2m() return treatment def __init__(self, *args, **kwargs): super(TreatDetail, self).__init__(*args, **kwargs) if self.instance and self.instance.pk: self.fields['specialties'].initial = self.instance.specialties.all() class Meta: model = Treatment fields = ( 'top_treatment', 'treatment_de', ....) I get this Error: TypeError at /customadmin/treatdetail/2/de/ Direct assignment to the reverse side of a many-to-many set is prohibited. Use specialties.set() instead. treatment.specialties = self.cleaned_data['specialties'] Of course I tried: treatment.specialties.set = self.cleaned_data['specialties'] The error disappears, but the reverse m2m relation is not saved. Can anybody help here? -
Lost some wagtail group permissons after remove_stale_contenttypes - how to get them back?
After refactoring some models in my Django/Wagtail project I had some stale contenttypes, triggering errors in the wagtail search app. These errors could be fixed by running a contenttypes management command: ./manage.py remove_stale_contenttypes Ok, I got warned about what will be deleted and there were indeed some group permission objects listed. Anyway, remove_stale_contenttypes did it's job and the wagtail search was back. But now some permissions are missing: e.g. the "Can access wagtail admin" Group permission is completely missing, even for new Group instances. How do I get the default permissions back (some were migrated once via wagtail/admin/migration)? Ideally, I would like to restore all "default" permissions on my production site... -
Django Admin: multi-table inheritance child model with many-to-many through inline fails with "Please correct the error below"
I'm not sure if this is a bug, limitation or error on my part, but I would like to get feedback on if there is a solution or work around to this issue... In Django Admin, I have created a many-to-many inline based on a 'through' model ReleaseCardCount. The inline is linked to a parent class Card which is used for numerous child models. In Django Admin, I am only interested in configuring the child classes of Card, for example, ActionCard. If I configure Django Admin for the parent Card model and ReleaseCardCount inline, I am able to add, remove and modify parent and inline objects without issue. If I configure the same set up for a child object of card, for example ActionCard, I can add inline objects if there are none or delete all inline objects, but I am unable to modify ActionCard or an inline object if an inline exists. If an inline object is present and I attempt to modify and save any data I get a "Please correct the error below" message, with no error present. I've minimised the code needed to recreate the issue to the following... models.py: from django.db import models class Release2(models.Model): … -
Why my model field is getting prepopulated in admin?
I have created a model as below. class UserPost(models.Model): author = models.ForeignKey(User, related_name='userpost', null=True, on_delete=models.CASCADE) post_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=150, blank=False) post_body = models.TextField(blank=True, null=True, default='text') image = models.ImageField(upload_to='post_pics', blank=True) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') I am not populating likes field anywhere, my admin screenshot is below.Why my likes field is getting populated with all the users created? admin screenshot admin.py from django.contrib import admin from feed.models import UserPost # Register your models here. admin.site.register(UserPost) -
How to compare timedelta in django template
From here, I made testmodel like this: class TestModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) I made a html code like this: <p>It's made {{ user.testmodel.created|timesince }} ago</p> <!-- and here is what I ask--> <p>{% if user.testmodel.created|timesince > 72hours %}Too long time ago{% endif %}</p> <!-- How can I do this part? --> I want to compare timedelta between now and testmodel.created and 72 hours on django template. Is there any good way to do this on django template tags? -
How to generate a unique div id for django objects displayed in template
So i am working on a django project . I have a template which displays all the available posts. Users can like a post. Everything is working fine. But i am facing a problem .Since i am using ajax to change the status of the like button when user clicks on it, i noticed that all the like buttons of the displayed posts object are affected, when a user clicks on the like button of one of the displayed posts. I want changes to occur just on the like button the user has clicked . Not all the like buttons of the displayed post object Example of my html template looks something of this sort . {% for post in allpost %} <!--for loop to get all post objects in data base--> {{post.tittle}} {{post.content}} {{post.type}} <!-- like button for users to be able to like post they fine interesting--> <a href="" data-href="{% url 'post:api_like' slug=post.slug %}"> <button id="like">like</button></a> {% endfor %} So you can see my like button id is not dynamic , which is one of the reasons i am facing this problem . How can i go about generating a dynamic button id for each like button in … -
django nginx gunicorn config needs to work on ip:port
I have currently config nginx gunicorn everything is working fine i am building a rest api the django should work something like this ip:port but instead if i enter the IP address in the browser the django application is working there is no port used how to change it to run on a specified port. -
How to save signed in username with the form to database? Django
All other data is saved ideally but as shown below, the user id part shows as a pull down bar and a null value which should be a signed-in username. What's wrong with my code? The database page Thank you in advance! Here's my code. Views.py from .models import Markers from .forms import AddMarkersInfo from django.http import HttpResponse def addinfo(request): if request.method == 'POST': mks = AddMarkersInfo(request.POST) if mks.is_valid(): submit = mks.save(commit=False) submit.user = request.user submit.save() name = mks.cleaned_data['name'] address = mks.cleaned_data['address'] description = mks.cleaned_data['description'] type = mks.cleaned_data['type'] lat = mks.cleaned_data['lat'] lng = mks.cleaned_data['lng'] Markers.objects.get_or_create(name=name, address=address, description=description, type=type, lat=lat, lng=lng) return render(request, 'home.html', {'mks': mks }) else: mks = AddMarkersInfo() return render(request, 'home.html', {'mks': mks}) models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.contrib.auth import get_user_model def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted')[0] class Markers(models.Model): User = settings.AUTH_USER_MODEL use_id= models.ForeignKey(User, null=True, on_delete=models.SET(get_sentinel_user),) name = models.CharField(max_length=60,default = 'name') address = models.CharField(max_length=100,default = 'address') description = models.CharField(max_length=150, default='description') types = ( ('m', 'museum'), ('s', 'school'), ('r', 'restaurant'), ('o', 'other'), ) type = models.CharField(max_length=60, choices=types, default='museum') lat = models.IntegerField() lng = models.IntegerField() forms.py from django import forms from maps.models import Markers class AddMarkersInfo(forms.ModelForm): class Meta: model = Markers fields = … -
django template blocks within blocks
I have a main page base.html. Inside of it, there is a {% block main_content %}: <main> <div class="container-fluid p-3"> {% block main_content %} {% endblock %} </div> </main> I slot my pages into that main content block. I now have to create a lot of pages for some internal documentation, that would probably end up being small enough. I then created a documentation.html page with another {% block documentation %} inside of the {% block main_content %}: {% extends 'base.html' %} {% load staticfiles %} {% load crispy_forms_filters %} {% block title %}Documentation{% endblock %} {% block styles %} <!-- CSS specific to documentation goes here --> {% endblock %} {% block main_content %} {% block documentation %} {% endblock documentation %} {% endblock main_content %} {% block end_scripts %} <!-- Scripts specific to documentation go here --> {% endblock end_scripts %} I do it this way because there will be some scripts and css specific changes to this documentation section of my page that will be shared among a whole buch of sub-pages. I would then include them once in this documentation.html page, and just change the content inside the {% block documentation %} tags. Then I created … -
Session data lost after a HttpResponseRedirect
I have this redirect view that sets session variables. But it's as if the session is flushed before the view that is being redirected to is called, as the whole session is empty there. (Btw, this is the real code, I've cut stuff to find the cause but still can't find it). class ActivateUserView(RedirectView): def get(self, request, *args, **kwargs): # activates user and redirects to listing listing = Listing.objects.get(id=2) request.session['test'] = 'icle' print("Session set to: ", request.session.get('test', "Nothing!")) return HttpResponseRedirect(reverse('listing-detail', kwargs={'pk': listing_pk, 'slug': listing.slug})) The view the above is redirected to: class ListingDetailView(TemplateView): template_name = "frontend/detail.html" @method_decorator(ensure_csrf_cookie) def get(self, request, *args, **kwargs): print("Session data: ", request.session.get('test', "Nothing!")) return super(ListingDetailView, self).get(request, *args, **kwargs) In the console, I get: Session set to: icle Session data: Nothing! I've checked with django-debug-toolbar, raising Exceptions here and there, and somewhere between the redirect call and the view, all session data is deleted. -
How to export a xlxs file written with xlsxwriter
I have written some data in xlxs file with help of xlsxwriter I want to export it so that it can be downloaded how is this possible def export(request,pk): import xlsxwriter product_resources = ProductType.objects.get(pk=pk) print(product_resources) attr = product_resources.product_attributes.all() r1=[] r1.append(str(product_resources)) for i in range(0,len(attr)): r1.append(str(attr[i])) print(r1) if(request.GET): col=0 row=0 workbook = xlsxwriter.Workbook('Product.xlsx') worksheet = workbook.add_worksheet() for item in r1: worksheet.write_string(row,col, item) col+=1 response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="product.xlsx"' workbook.close() return response This is my method but I am getting a file which is empty can could not be opened -
Heroku deployment succes but no module found
I am deploying the polls app from django tutorial to heroku. My project seen from Pycharm have the following distribution: My requirements file looks as: Django==2.0.5 scikit-learn==0.19.1 numpy==1.13.3 pandas==0.22.0 pymysql==0.8.1 gunicorn==19.0.0 Runtime as: python-3.6.5 Procfile as: web: gunicorn inf-shf-373.wsgi:application --log-file - When I deploy the app and goes to the browser I get an application error that says: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. I retrieve the log using the heroku logs --tail --app inf-shf-373 statement. Log 2018-06-15T10:08:51.529196+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-06-15T10:08:51.529198+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 356, in import_app 2018-06-15T10:08:51.529201+00:00 app[web.1]: ModuleNotFoundError: No module named 'inf-shf-373' 2018-06-15T10:08:51.529199+00:00 app[web.1]: __import__(module) 2018-06-15T10:08:51.529202+00:00 app[web.1]: Traceback (most recent call last): 2018-06-15T10:08:51.529203+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 502, in spawn_worker 2018-06-15T10:08:51.529205+00:00 app[web.1]: worker.init_process() 2018-06-15T10:08:51.529206+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 114, in init_process 2018-06-15T10:08:51.529208+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-06-15T10:08:51.529209+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 66, in wsgi 2018-06-15T10:08:51.529211+00:00 app[web.1]: self.callable = self.load() 2018-06-15T10:08:51.529212+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2018-06-15T10:08:51.529216+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2018-06-15T10:08:51.529214+00:00 app[web.1]: return self.load_wsgiapp() 2018-06-15T10:08:51.529218+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-06-15T10:08:51.529219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 356, in import_app 2018-06-15T10:08:51.529221+00:00 app[web.1]: __import__(module) 2018-06-15T10:08:51.529222+00:00 app[web.1]: ModuleNotFoundError: No … -
Save datetime value from Django to Postgres
This is my views.py: class UpdateListMyShipmentView(UpdateView): model = models.Shipment fields = [] def get_success_url(self): return reverse_lazy('request:my_shipment') def form_valid(self, form): print(timezone.localtime(timezone.now())) form.instance.time_finished_shipment = timezone.localtime(timezone.now()) form.save() return super().form_valid(form) This is the value of print() method in command line: 2018-06-15 16:54:29.499707+07:00 And this is the result in database after saved value into database: 2018-06-15 09:43:39.025761+00 Why it is different? -
tornado deploy django and the log repeat output
In my project i deployed my django-project with tornado server, and my tornado main function is: def main(): tornado.options.options.logging = None tornado.options.parse_command_line() os.environ['DJANGO_SETTINGS_MODULE'] = 'Zero.settings' application = get_wsgi_application() container = tornado.wsgi.WSGIContainer(application) http_server = tornado.httpserver.HTTPServer(container, xheaders=True) http_server.listen(tornado.options.options.port) tornado.ioloop.IOLoop.current().start() When i use tornado.options.options.logging = None to disabled tornado logging output, but it still output the log message in my console with twice, my django logging config is: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s [%(threadName)s] [%(name)s:%(funcName)s] [%(levelname)s]- %(message)s'} }, 'filters': { }, 'handlers': { 'error': { 'level': 'ERROR', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'log', 'error.log'), 'maxBytes': 1024*1024*5, 'backupCount': 5, 'formatter': 'standard', }, 'console':{ 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True }, } } The final result is: 2018-06-15 17:40:55,724 [MainThread] [base_views:get] [INFO]- get message correct INFO:base_views:get message correct so what can i do to solve this problem. Thank U. -
Not able to access details of dishes using related name in Django
I am trying to get all the dishes for a corresponding restaurant but it keeps on showing restaurant.FoodItem.None Models.py: class Restaurant(models.Model): name = models.CharField(max_length = 200) email = models.EmailField(max_length = 254) address = models.CharField(max_length=100) city = models.CharField(max_length=100) website = models.TextField(validators=[URLValidator()]) telephone = models.PositiveIntegerField() owner = models.ForeignKey(Owner , on_delete = models.CASCADE) def __str__(self): return self.name class FoodItem(models.Model): name = models.CharField(max_length = 200) price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) description = models.TextField(blank=True, null=True) restaurant = models.ForeignKey('restaurant.Restaurant', null=True, related_name='dishes' , on_delete = models.CASCADE) def __str__(self): return self.name; views.py: class FoodItemDetailView(DetailView): model = Restaurant def get_context_data(self , *args , **kwargs): context = super(FoodItemDetailView , self).get_context_data(*args , **kwargs) print(context) return context restaurant_detail.html: In below no name of dish is getting printed but the name of restaurant is getting printed {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col col-sm-6 "> restaurant and serving food item {{ object.name }} {% for dish in object.dishes.all %} {{ dish.name }} {% endfor %} </div> </div> </div> {% endblock %} -
form.is_valid() failing in Django unit test
I'm running a unit test for a Django form, and form.is_valid() keeps returning False and I cannot find the error. Here's the code for forms.py: class CustomClearableFileInput(forms.ClearableFileInput): template_name = 'forums/templates/clearable_file_input.html' class NewQuestionForm(forms.ModelForm): category = forms.ModelChoiceField(widget = forms.Select(attrs = {}), queryset = FossCategory.objects.order_by('name'), empty_label = "Select a Foss category", required = True, error_messages = {'required':'Select a category'}) title = forms.CharField(widget = forms.TextInput(), required = True, error_messages = {'required':'Title field required'}, strip=True) body = forms.CharField(widget = forms.Textarea(), required = True, error_messages = {'required':'Question field required'}, strip=True) is_spam = forms.BooleanField(required = False) spam_honeypot_field = HoneypotField() image = forms.ImageField(widget = CustomClearableFileInput(), help_text = "Upload image", required = False) def clean_title(self): title = str(self.cleaned_data['title']) if title.isspace(): raise forms.ValidationError("Title cannot be only spaces") if len(title) < 12: raise forms.ValidationError("Title should be longer than 12 characters") if Question.objects.filter(title = title).exists(): raise forms.ValidationError("This title already exist.") return title def clean_body(self): body = str(self.cleaned_data['body']) if body.isspace(): raise forms.ValidationError("Body cannot be only spaces") if len(body) < 12: raise forms.ValidationError("Body should be minimum 12 characters long") body = body.replace('&nbsp;', ' ') body = body.replace('<br>', '\n') return body class Meta(object): model = Question fields = ['category', 'title', 'body', 'is_spam', 'image'] And here's the code for tests.py: class NewQuestionFormTest(TestCase): def test_too_short_title(self): category = … -
urlopen error [Errno 54] Connection reset by peer
Exception Location: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py in do_open, line 1198 Mac OS X, Python 2, Django 1.8 Hi, does anybody resolve the problem? "pip install pyopenssl ndg-httpsclient pyasn1" and "pip install requests[security]" didn't help me, if you need some more information i will wright it. -
Facebook login with Angular 2 and Django REST Framework
From angular I am using ngx-facebook module which helps me to get access token easily. So my function inside angular component and it looks something like: constructor(private fb: FacebookService) { let initParams: InitParams = { appId: '62283110472xxxx', status: true, cookie: true, xfbml: true, version: 'v2.8' }; fb.init(initParams); } When using this, I am able to get access token (After allowing those permissions) and it returns JSON as: authResponse: { accessToken: <access_token>, expiresIn: ... } Now when I get accessToken, I am passing this to DRF. For managing facebook auth I am using django-allauth. So I have already created the api for it like: url(r'^rest-auth/facebook/$', views.FacebookLogin.as_view(), name='fb_login'), But as soon as I make POST request to that url with the given accessToken from Angular app I get error: "POST /rest-auth/facebook/ HTTP/1.1" 400 38 With error text as: '{"nonFieldErrors":["Incorrect value"]}' Now obviously my accessToken is correct but still I am getting error. So one thing is for sure that is my configuration is not correct. So in my settings.py I have this: SOCIALACCOUNT_PROVIDERS = \ {'facebook': { 'METHOD': 'js_sdk', 'SCOPE': ['email', 'public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time', … -
Use cases of csrf_exempt
May I know where could we use Django csrf_exempt. In my current application, I have seen many places where programmers have used csrf_exempt. I suspect there could be a security flaw. So it would be helpful if I'm able to understand different use cases. -
Add multiple class objects from another class
I want to generate multiple country objects with the similar language object without going through the admin UI. models.py from django.db import models class World(models.Model): country = models.CharField(max_length=200) Language = models.CharField(max_length=200) class add_countries(models.Model): sub_part1 = ['USA','ENGLAND','AUSTRALIA','CANADA'] for sub in sub_part1: sub = World.country World.Language = "English" add_countries()