Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple forms in forms.py
This is a Django project. forms.py class BigForm(forms.Form): template = forms.CharField(label='Template', widget=forms.Select(choices=CHOICES)) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout( Field('template'), Submit('submit', 'Submit', css_class='btn-success') ) class DateForm(forms.Form): start_date = forms.CharField(label='Start date') end_date = forms.CharField(label='End date') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper self.helper.form_method = 'post' self.helper.layout = Layout( Field('start_date', css_class='form-control'), Field('end_date', css_class='form-control') ) views.py def myForm(request): main_form = BigForm() date_form = DateForm() return render(request, 'polls/main.html', {'main_form': main_form, 'date_form': date_form}) Is there something wrong with this? I keep getting KeyError: "Key 'end_date' not found in 'BigForm'. Choices are: template." I just want two separate form classes (for two separate forms) -
How to know some object's order in django queryset
qs1 = QueryModel.objects.all().order_by('?') obj1 = QueryModel.objects.get(pk=123) def order_stuff(queryset, obj) return print(#obj_order_from_queryset) order_stuff(qs1, obj1) >>> some ordering number How to know some object's order on some queryset? For example, if queryset are like: print(qs1) >>> {'pk': 1}, {'pk': 3}, {'pk': 4}, {'pk': 123} ... So that: order_stuff(qs1, obj1) >>> 4 if queryset are like: print(qs1) >>> {'pk': 123}, {'pk': 3}, {'pk': 4}, {'pk': 13} ... So that: order_stuff(qs1, obj1) >>> 1 if queryset are like: print(qs1) >>> {'pk': 13}, {'pk': 123}, {'pk': 4}, {'pk': 13} ... So that: order_stuff(qs1, obj1) >>> 2 How to do this? -
Difference between range and lte/gte django filters
I am using filters for a model with following two ways: Model.objects.filter(created_date__gt=datetime(2018, 1, 11, 00, 00, 00), created_date__lte=datetime(2018, 11, 11, 23, 59, 59), user_id=135) And Model.objects.filter(user_id=135, created_date__range=["2018-11-1 00:00:00", "2018-11-11 23:59:59"]) When i check the count of the both filters there is huge difference of count. The main question is what is difference between range and gte/lte in filters ? -
Django : CommandError: You appear not to have the 'mysql' program installed or on your path
I'm trying to setup a django project with mysql backend . I have my environment variable set , so i'm able to run mysql command from the command prompt. Following settings have been done in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'anprgatedcommunity', 'USER': 'root', 'PASSWORD': 'root123', 'HOST': 'localhost', 'PORT': '3306', } } when i try to run python manage.py dbshell it throws me CommandError: You appear not to have the 'mysql' program installed or on your path. error. -
groups.Groups.created_by: (fields.E303) Reverse query name for 'Groups.created_by' clashes withfield name 'User.groups'
I am trying to migrate these two models: from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. # Groups Model class Groups(models.Model): grp_name = models.CharField(max_length=100) grp_status = models.CharField(max_length=100) grp_description = models.TextField() created_on = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) members = models.ManyToManyField(User, through='UserGroup') def __str__(self): return self.grp_name #user groups class UserGroup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Groups, on_delete=models.CASCADE) date_joined = models.DateTimeField(default=timezone.now) But I have got this error: ERRORS: groups.Groups.created_by: (fields.E303) Reverse query name for 'Groups.created_by' clashes withfield name 'User.groups'. HINT: Rename field 'User.groups', or add/change a related_name argument to the definition for field 'Groups.created_by'. groups.Groups.created_by: (fields.E304) Reverse accessor for 'Groups.created_by' clashes with reverse accessor for 'Groups.members'. HINT: Add or change a related_name argument to the definition for 'Groups.created_by' or 'Groups.members'. groups.Groups.members: (fields.E303) Reverse query name for 'Groups.members' clashes with fieldname 'User.groups'. HINT: Rename field 'User.groups', or add/change a related_name argument to the definition for field 'Groups.members'. groups.Groups.members: (fields.E304) Reverse accessor for 'Groups.members' clashes with reverseaccessor for 'Groups.created_by'. HINT: Add or change a related_name argument to the definition for 'Groups.members' or 'Groups.created_by'. I want to make many-to-many relationship between the users and groups. That is the users can be in … -
django_otp custom OTP Middleware does not detect an already authenticated user
I want to add OTP verification by using the django_otp library. Per each request I want to verify if the user has been initially authenticated and in that case check whether it has any OTP device associated. I have manually implemented the API endpoint for the OTP device creation and it successfully creates the device and associates to the user used for the creation. This is my simplified MIDDLEWARE stack MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'otp.middleware.FMSOTPMiddleware', ) First the AuthenticationMiddleware would add the user object to the request, and then the OAuth2TokenMiddleware would authenticate() the user against the backend. The code for the FMSOTPMiddleware middleware is: class FMSOTPMiddleware(OTPMiddleware): def process_request(self, request, *args, **kwargs): super().process_request(request, *args, **kwargs) user = request.user print(user) print(user.is_authenticated) The OTPMiddleware from django_otp adds the user.otp_device attr and user.is_verified() method. After manually adding the OTP device and calling this methods it works properly, but from within the middleware user always returns AnonymousUser. -
Django: Manage execution of same script by different users
I have a script that is generating some excel reports from my django database. Currently the script is scheduled in cron and runs every 15 minutes and it backs up the reports from previous run and puts in into our backup dump. What I need to do is instead of it running every 15 minutes, provide a button that executes the script so the users can run it as and when required. But the problem would be if multiple users try to generate the report around the same time because the same script will run one after the other on the same server. Is it possible to somehow manage this? Like if the script is already running, block the other user from running it again or lock the script? I read somewhere that celery and rabbitmq can be used for this but that looks like an overhead. Any help is appreciated! Thanks. -
Django tests display traceback of expected exception in assertRaises
I'm testing a django view with APIClient. One of the test cases checks whether an exception is raised: self.assertRaises( IntegrityError, self.client.post, path='/some/url/to/view/', data={ 'test': 'data' }, format='json' ) Although the test passes, the client call raises the expected exception with printing the full traceback. Can I somehow change this behaviour? I don't want to see numbers of tracebacks in my test run as this is a common test case. -
django chaning filter continuously
I'm trying to make continuous django filtering. Let's assume that I have some model: class TextModel(models.Model): text = models.TextField(max_length=1000, null=True, blank=True, default=None) created = models.DateTimeField(auto_now_add=True) And now, I'll make TextModel's objects like it: {'text': '1'}, {'text': '2'} ... {'text': '99'}, {'text': '100'} Here starts what I want to do. I'll find objects that text field include '1' by 4 Querysets. As you know final result will be this: {'text': '1'}, {'text':'10'}, {'text':'11'} ... {'text':'91'}, {'text':'100'} Maybe it's length will be 20? maybe 20 result. I want to make this result divided by 4 Querysets that has 5 results individually. And I want to make results be ordered by their text length, not pk or created. But if text length is the same, then it is good to be ordered by 'pk' or 'created'. Most urgent ordering standard is text length I tried: from django.db.models import TextField from django.db.models.functions import Length TextField.register_lookup(Length) qs1 = TextModel.objects.filter(Q(text__icontains='1')).order_by( Length('text').asc(), 'pk')[:5] qs2 = TextModel.objects.filter(Q(text__icontains='1') & Q(text__lte=len(qs1.last().text)).order_by( Length('text').asc(), 'pk')[:5] qs3 = TextModel.objects.filter(Q(text__icontains='1') & Q(text__lte=len(qs2.last().text)).order_by( Length('text').asc(), 'pk')[:5] qs4 = TextModel.objects.filter(Q(text__icontains='1') & Q(text__lte=len(qs3.last().text)).order_by( Length('text').asc(), 'pk')[:5] This has failed. Because qs2 also has the result that is also in qs1. To prevent this, I thought this way: qs1 = … -
How to relate fields in Django Admin?
In a model, I have a DecimalField "first_arg", and a multiple choice CharField "second_arg". I'd like to achieve the following: In the admin panel, if a particular option (let's say "B") is selected for "second_arg" field, increment any value that is inserted to "first_arg" form field by 2. What's the right way to go about it? Since it's part of the admin UI, modifying the model should be wrong. On the other hand, I couldn't find anything about it in the documentation. I thought about simply using some JS in a static file, but that's kinda hacky. Is there an elegant way to do these things in Django Admin? Model code: class MyModel(models.Model): first_arg = models.DecimalField( max_digits=4, decimal_places=2, blank=True, null=True ) second_arg = MultipleChoicesField( models.CharField( choices=constants.RELEVANT_OPTIONS, max_length=20 ), blank=True, null=True ) class Meta: abstract = True # The following is irrelevant for the question, just to prevent any confusion: class MultipleChoicesField(ArrayField): def formfield(self, **kwargs): defaults = { 'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices, } defaults.update(kwargs) return super(ArrayField, self).formfield(**defaults) a = "a" b = "b" etc = "etc" RELEVANT_OPTIONS = ( (a, "A"), (b, "B"), (etc, "etc") ) -
Cleaning up CBV
I've got this class which works as intended class UpdateView(TemplateView): def get(self, request, username): id = User.objects.get(username = username).id user = get_object_or_404(User, id = id) employee = get_object_or_404(Employee, user_id = id) form_user = UserForm(instance=user) form_employee = EmployeeForm(instance=employee) args = {'form_user': form_user,'form_employee': form_employee, 'username': username} return render(request, 'user/update.html', args) def post(self, request, username): id = User.objects.get(username = username).id user = get_object_or_404(User, id = id) employee = get_object_or_404(Employee, user_id = id) form_user = UserForm(request.POST, instance=user) form_employee = EmployeeForm(request.POST, instance=employee) if form_user.is_valid() and form_employee.is_valid(): form_user.save() form_employee.save() return redirect('user:list') args = {'form_user': form_user, 'form_employee': form_employee, 'username': username} return render(request, 'user/update.html', args) My issue is that both the get and post methods use the same id, user and employee variables. How can I clean this up? I know I can create a render method like def render(self, request, username): args = {'form_user': form_user, 'form_employee': form_employee, 'username': username} return render(request, 'user/update.html', args) and then call return self.render(request) at the end of the get and post methods, so I don't have to define the args twice either, but currently this conflicts with the username. That's why I want to tackle the problem with the 3 variables first. -
Is it possible in Django admin to make a model out of an intermediate table and create a one to one relationship with another model?
I have 2 tables that have a many to many relationship. I want to know if it is possible for me to make a model out of it and then create a one to one relationship out of it with another model. What I want to do is to have this model from the intermediate table display its fields in a list display together with the fields of the other model where it has a one to one relationship. -
Django-Filter returns return the request object
I was trying to dynamically filter the queryset in Django using Django-filters library in DRF but the filters send the response exactly as the same to request ie if i choose mode = transfer the response is { "data": { "mode": "transfer" } } the filterset_class is defined in the views and queryset is passed on to it along with the request type. views.py from .filters import DataFilter def get(self, request): query_set = ModelName.objects.all() queryset_filter = DataFilter( request.GET, queryset=query_set) return Response({"data": queryset_filter.data}, status=status.HTTP_200_OK) filters.py from django_filters import rest_framework as filters from .models import ModelName from common.models import MODE_CHOICES class DataFilter(filters.FilterSet): currency = filters.ModelMultipleChoiceFilter(lookup_expr='iexact') coin_type = filters.ModelMultipleChoiceFilter(lookup_expr='iexact') mode = filters.ModelChoiceFilter( lookup_expr='iexact', choices=MODE_CHOICES) max_amount = filters.NumberFilter( field_name='price', lookup_expr='gt') min_amount = filters.NumberFilter( field_name='amount', lookup_expr='lt') class Meta: model = ModelName fields = ('currency', 'coin_type', 'mode', 'max_amount', 'min_amount') The django-filters documentation suggests django-filter backend can be used by default by adding it to the DEFAULT_FILTER_BACKENDS. Is there some configuration that i am missing or something -
i am importing news api in my django project i can print it data in my terminal but i can't print in my html template
I am importing news api in my Django project.my can print my data in my terminal but can't print through my news.html i have something problem in importing the data in html.I need some help to get it. from django.shortcuts import render import requests def news(request): url = ('https://newsapi.org/v2/top-headlines?' 'sources=bbc-news&' 'apiKey=647505e4506e425994ac0dc310221d04') response = requests.get(url) print(response.json()) news = response.json() return render(request,'new/new.html',{'news':news}) this base.html <html> <head> <title></title> </head> <body> {% block content %} {% endblock %} </body> </html> news.html {% extends 'base.html' %} {% block content %} <h2>news API</h2> {% if news %} <p><strong>{{ news.title }}</strong><strong>{{ news.name}}</strong> public repositories.</p> {% endif %} {% endblock %} This my terminal output with my API output System check identified no issues (0 silenced). November 28, 2018 - 12:31:07 Django version 2.1.3, using settings 'map.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. {'status': 'ok', 'totalResults': 10, 'articles': [{'source': {'id': 'bbc-news', 'name': 'BBC News'}, 'author': 'BBC News', 'title': 'Sri Lanka defence chief held over murders', 'description': "The country's top officer is in custody, accused of covering up illegal killings in the civil war.", 'url': 'http://www.bbc.co.uk/news/world-asia-46374111', 'urlToImage': 'https://ichef.bbci.co.uk/news/1024/branded_news/1010/production/_104521140_26571c51-e151-41b9-85a3-d6e441f5262b.jpg', 'publishedAt': '2018-11-28T12:12:05Z', 'content': "Image copyright AFP Image caption Adm Wijeguneratne denies the charges Sri Lanka's top military … -
Django 2.1.3 reset password link not displaying
After upgrading to Django 2.1.3, I noticed the "Forgotten your password or username?" link was missing from the admin login page. After some investigating, I found the that the django.contrib.auth.urls.py module used the name password_reset for the reset url, while in the django/contrib/admin/templates/admin/login.html template the url was named admin_password_reset: django.contrib.auth.urls.py (line 16) path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), django/contrib/admin/templates/admin/login.html (starting at line 54) {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} <div class="password-reset-link"> <a href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a> </div> {% endif %} When I changed admin_password_reset to password_reset in Django's login.html, the link showed up on the login page and worked as expected. In my urls.py I have: path('lodging/', include('django.contrib.auth.urls')), My project has no other modifications to the authentication system. Is this a bug or am I missing something? -
"python social auth" adding a backend
I'm trying to add a new social backend based on the python social auth library but when I click my "Login with X" or "Sign up with X" button it always redirects me back to the login page without logging in. The ACCESS_TOKEN_URL is never called. I wrote the following as new social backend: class xOAuth2(BaseOAuth2): name = 'x' API_URL = 'http://localhost:8000/api/' AUTHORIZATION_URL = 'http://localhost:8000/' ACCESS_TOKEN_URL = 'http://localhost:8000/api/login/oauth/access_token' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ',' REDIRECT_STATE = False STATE_PARAMETER = True def get_user_details(self, response): return {'username': response['username'], 'email': response['email'], 'fullname': response['fullname'], 'first_name': response['first_name'], 'last_name': response['last_name']} def user_data(self, access_token, *args, **kwargs): user_info = self.get_json('http://localhost:8000/api/oauth/resources?access_token=' + format(access_token)) return user_info and class xAuthBackend(SocialAuthMixin, xOAuth2): auth_backend_name = "X" def get_verified_emails(self, *args: Any, **kwargs: Any) -> List[str]: access_token = kwargs["response"]["access_token"] try: emails = self._user_data(access_token, '/emails') except (HTTPError, ValueError, TypeError): emails = [] verified_emails = [] for email_obj in emails: if not email_obj.get("verified"): continue if not email_obj.get("primary"): continue verified_emails.append(email_obj["email"]) return verified_emails def user_data(self, access_token: str, *args: Any, **kwargs: Any) -> Dict[str, str]: return super().user_data( access_token, *args, **kwargs ) I'm using a custom written IdP, which has the following code for exchanging a auth token for an access token: public function generate_access_token(Request $request){ $auth_token = $request->get('code'); $x_user = … -
Django: admin.site.site_header set, but not visible for own pages
I set admin.site.site_header = 'Fooo' like explained in the docs: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.AdminSite.site_header This works very nice for all normal admin-pages. I have an additional (custom) page which I want to look like the admin page. I use {% extends 'admin/base_site.html' %} in my template. On this page site_header 'Fooo' is not displayed. The normal/default django string is visible. What am I doing wrong? -
How to get existing values from the database into the django model field for django admin
I need help to get existing questions from the field question_name into the field dependent_question (with dropdown) from the Questions model class. It will help user to select dependent question when they add any new question from django admin panel. # model.py class Questions(models.Model): question_id = models.AutoField(primary_key=True) question_name = models.CharField(max_length=300) dependent_question = models.CharField(max_length=300,blank=True, null=True) -
django SMTPServerDisconnected using gmail account
Can you please me I have tried this code but unfortunately its not working Having Error : SMTPServerDisconnected at / Connection unexpectedly closed: [Errno 104] Connection reset by peer Setting.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'shabbirfast@gmail.com' EMAIL_HOST_PASSWORD = '*****' EMAIL_PORT = 587 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Views.py from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings from django.http import HttpResponse def sendemail(request): subject = 'Test Mail' message = 'This is an automatic massage HELLO from django.' email_from = settings.EMAIL_HOST_USER recipient_list = ['shabbir@xcodes.net'] try: send_mail(subject, message, email_from, recipient_list,fail_silently=False) return HttpResponse("SEND Confirm") except Exception as e: raise e -
Django template default filter with nullable boolean values
I need to pass a boolean variable to a template. To convert it to js boolean you usually do: {{ boolval|yesno:'true,false' }} Now my boolvar may not exist. In that case I need it to default to true, so I am trying this: {{ boolval|default_if_none:'true'|yesno:'true,false' }} Unexpectedly, the result of this is false. I am trying to debug what {{ boolval|default_if_none:'true' }} produces but I am getting syntax errors. Not sure what's going on, but it is definitely not producing true. How can I achieve with filters the behavior I'm after? -
Hitting an API from Django admin Panel
In Django admin Panel. I have a model which has fields like userID, name, status. I want to call an API (e.g:- www.xyx.com?user=userID&status='approved') when status="approved" is selected and click on save button. -
Which apache modules are necessary when running Django application via mod_wsgi?
We are running Django application behind Apache using mod_wsgi. We also need to serve HTTPS requests. Are the following modules sufficient ? mod_alias.so mod_authz_host.so mod_deflate.so mod_mime.so mod_negotiation.so mod_rewrite.so mod_wsgi.so -
Which approach is better in Django Jsonfield or ForeignKey?
Such a question, I want to create a price comparison site, there are two ideas how to implement a list of prices from different stores. First via ForeignKey class Price(models.Model): price = models.DecimalField() shop = models.CharField() class Product(models.Model): name = models.CharField(max_length=255) prices = models.ForeignKey() JSONfield second method class Product(models.Model): name = models.CharField(max_length=255) data = JSONField() """ Product.objects.create(name='product', data={'price': 999, 'shop': 'Amazon.com'} def __str__(self): return self.name If anyone has experience, what works faster and more reliable if a large number of goods? Thanks for the early ones. -
Trigger a modal on django form submit
I have a series of Django forms and formsets that are connected together in a series of steps. When the final form step is submitted a celery task is started to create an entity based on all the information provided. The way this is currently working, is that the final form is submitted (and the task starts) and then redirects to a page which lets the user know that the entity is being created and then redirects once this is complete. However, I now want to have this loading page show up as a modal on the previous page, rather than show on an entirely new page. I have previously been doing this almost solely in Django. When I submit the final form the form_valid looks like this (I am using django-extra-views to make formsets so it is slighlty different from normal): def forms_valid(self, form, inlines): self.object = form.save() models.ActivityBaseNext.objects.create( activity_base=self.activity_base, order=self.activity_base.get_next_next_step_order(), activity_configure=self.object, ) for formset in inlines: formset.save() transaction.on_commit( tasks.activity_configure.s( id=self.object.pk, ).delay ) return HttpResponseRedirect(self.object.get_current_next_url()) which causes the redirect to the loading page, which looks like so: class ActivityConfigureStatus(LoginRequiredMixin, DetailView): model = models.Activity template_name = 'alert.html' title = 'Create Activity' display_text = 'Importing activity data' refresh_secs = 1 def … -
django-threadlocals stopped working upgrading from django 1.11 to django 2.1.3
I'm trying to upgrade for a project the django framework from 1.11 to 2.13. The project depends on django-threadlocals. (https://github.com/benrobster/django-threadlocals). After upgrade, request is not set by threadlocals middleware anymore so any call to threadlocals.get_current_user() threadlocals.get_current_request() returns None Did not find any issue on github Have you any hints? I'm running python 3.5.2