Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
want to find data between dates,using query. In database date stores in text format e.g. "Thu may 09 2019"
I want to find data between dates, but problem is that I am using "Thu May 09 2019" this type of format in my database so "date__gte" query is not working. any solution of that problem?? -
Circular import error when I open the Django server
When I open the server(Django) I get this error: "The included URLconf 'admin.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import." I have found out that by removing .views import from urls.py I fix the issue. So I think the problem is inside views.py. App urls.py from django.contrib import admin from django.urls import include from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('/api', include('crud.urls')), ] views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from .models import User from .serializers import UserSerializer class UserView(APIView): def get(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response({"users": users}) serializer.py from rest_framework import serializers class UserSerializer(serializers.Serializer): name = serializers.CharField(max_length=255) email = serializers.EmailField() password = serializers.CharField(max_length=255) disease = serializers.CharField(max_length=255) logo = serializers.TextField() crud urls.py Here, the issue is at the second line: if I remove that line I fix the error from django.urls import path from .views import UserView app_name='crud' # app_name will help us do a reverse look-up latter. urlpatterns = [ path('users/', UserView.as_view()), ] -
Pass Variable From Django to Jquery in HTML File
I want to pass a string variable containin from a django view to a jquery statement in an html file. Example of what I want to do: views.py file: def myview(request): return render(request, 'my_file.html',context={'var':'name_attr'} html file: $('input[name=[{{ var }}]').val('some value') What is the correct syntax or process to get this done? -
django PasswordResetView sending email to users with same email address
I am new to django and I am trying to use the auth.views.PasswordX functionality and it is working except I set up multiple test user accounts with the same email address and it is sending the password reset email to each of them? Is there a way to override this or another way to just send the email to the logged in user? path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password-reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), {% extends "empTime/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Reset Password</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Request Reset</button> </div> </form> </div> {% endblock content %} -
How to reverse a url that is using DefaultRouter()?
I'm trying to use reverse() inside my test. I tried this answer! but it's not working. I still getting the error django.urls.exceptions.NoReverseMatch: Reverse for 'patients-list' with no arguments not found. router = DefaultRouter() router.register(r'patients', views.PatientSet, base_name='patients') url(r'^', include(router.urls)), I'm using this way inside my test url = reverse('patients-list') -
Im getting an error regarding TemplateView in CBV django
Class-based TemplateView are not working, help me find the error from django.shortcuts import render from django.views.generic.base import View,TemplateView from django.http import HttpResponse Create your views here. class home(TemplateView): template_name = 'index.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['injectme'] = 'injected' return context TypeError at / expected str, bytes or os.PathLike object, not tuple Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2 Exception Type: TypeError Exception Value: expected str, bytes or os.PathLike object, not tuple Exception Location: /anaconda3/envs/mydjangoEnv/lib/python3.7/posixpath.py in join, line 80 Python Executable: /anaconda3/envs/mydjangoEnv/bin/python Python Version: 3.7.3 Python Path: ['/Users/faiq/Desktop/exercise/CBV/advance', '/anaconda3/envs/mydjangoEnv/lib/python37.zip', '/anaconda3/envs/mydjangoEnv/lib/python3.7', '/anaconda3/envs/mydjangoEnv/lib/python3.7/lib-dynload', '/anaconda3/envs/mydjangoEnv/lib/python3.7/site-packages'] Server time: Wed, 8 May 2019 23:02:58 +0000 -
Django DateTimeRangeField how to filter by lower only?
Let's say I have a model with the DateTimeRangeField, and I would like to filter by the lower bound greater than now(), regardless whatupper bound is: BackupResource.objects.filter(datetime_range__lower__gt=timezone.now()) It errors out: Unsupported lookup 'lower' for DateTimeRangeField or join on the field not permitted. -
TypeError: 'NoneType' object is not iterable Django Filter Values_List
I've been trying to figure out an error that I can't get past this afternoon. I am using a Class Based View(DetailView). Here is my code... def get_context_data(self, **kwargs): book = list(Author.objects.filter(author_id).values_list('publisher')) When I try to execute my code... I get.... TypeError: 'NoneType' object is not iterable I know at times the values_list('publisher') for an Author may sometimes be blank. How can I get this filter mechanism to bypass the book if the publisher is in fact empty? I tried to do something like... def get_context_data(self, **kwargs): book = list(Author.objects.filter(author_id).values_list(None, 'publisher')) But it didn't seem to help. I also played with the idea of making this reference conditional but that seems unnecessary. Is there some way to get this code bypassed if in fact the lookup is NONE? I'm using PostgreSQL. Thanks in advance for any thoughts. -
How to fix 'Error validation unque field by serializer when update instance'
I have a model of Organisation and three models have Foreign keys to Organisation model. Three nested models is Users ( custom model ), Description and Contacts. Users has unique field email. Description has unique pair of two fields. I have custom serializer to Organisation. class OrganisationSuperAdminSerializer(serializers.ModelSerializer): users = UsersSerializer(many=True, required=False) contacts = ContactsSerializer(many=True, required=False) description = DescriptionOrganisationSerializer(many=False, required=False) class Meta: model = Organisation fields = '__all__' def create(self, validated_data): error_msg = 'Save error' users_data = validated_data.pop('users') contacts_data = validated_data.pop('contacts') description_data = validated_data.pop('description') organisation = Organisation.objects.create(**validated_data) try: for user_data in users_data: Users.objects.create(organisation=organisation, **user_data) for contact_data in contacts_data: Contacts.objects.create(organisation=organisation, **contact_data) DescriptionOrganisation.objects.create(organisation=organisation, **description_data) except: organisation.delete() raise serializers.ValidationError(error_msg) return {} def update(self, instance, validated_data): pass When I save, everything goes well. But when I try to update, the serializer fails validation. The error text in the comments. """ Класс для работы с данными для супер админа """ queryset = Organisation.objects.all() serializer_class = OrganisationSuperAdminSerializer permission_classes = [permissions.AllowAny, ] def update(self, request, pk=None, *args, **kwargs): serializer: serializers.ModelSerializer = self.get_serializer(self.get_object(), data=request.data) print(serializer.is_valid()) # False print(serializer.errors) # {'users': [{'email': [ErrorDetail(string='email must be unique', code='unique')]}], 'description': {'non_field_errors': [ErrorDetail(string='The fields inn, kpp must make a unique set.', code='unique')]}} return response.Response(status=200) I don't want to disable validation of unique fields. … -
DjangoRestFramework: search and sort a element inside a JsonField
Is it possible somehow to search/sort a field inside a JsonField by creating a custom method using django_rest_framework? ---------------------------------------------------------------- | name | my_json_field | ---------------------------------------------------------------- | record_1 | {"field1": "A1", "field2": "A2", "field3": "A3"} | ---------------------------------------------------------------- | record_2 | {"field1": "B2", "field2": "B1" } | ---------------------------------------------------------------- | record_3 | {"field1": "C3", "field2": "C2", "field3": "C1"} | ---------------------------------------------------------------- So that: if filter by my_json_field -> field1 = "A1" I get: ---------------------------------------------------------------- | name | my_json_field | ---------------------------------------------------------------- | record_1 | {"field1": "A1", "field2": "A2", "field3": "A3"} | ---------------------------------------------------------------- if sort DESC by my_json_field -> field3 I get: ---------------------------------------------------------------- | name | my_json_field | ---------------------------------------------------------------- | record_1 | {"field1": "A1", "field2": "A2", "field3": "A3"} | ---------------------------------------------------------------- | record_3 | {"field1": "C3", "field2": "C2", "field3": "C1"} | ---------------------------------------------------------------- | record_2 | {"field1": "B2", "field2": "B1" } | ---------------------------------------------------------------- -
django + nginx on docker bad request (400)
I'm trying to get django (on gunicorn) and nginx running with docker. Unfortunately, I keep getting a Bad Request (400) error after I run docker-compose up -d --build. Help. I have tried changing directories, directory names, volumes, networks and exposed ports to no avail. I also tried adding and removing server_name in my nginx.conf file. In settings.py I have: DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] This is my docker-compose.yml file: version: '3.3' services: web: build: ./app command: gunicorn my_server.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ expose: - 8000 environment: - DATABASE=${DATABASE} - SECRET_KEY=${SECRET} - SQL_DATABASE=${POSTGRES_USER} - SQL_ENGINE=django.db.backends.postgresql - SQL_HOST=${POSTGRES_HOST} - SQL_PASSWORD=${POSTGRES_PASSWORD} - SQL_PORT=${POSTGRES_PORT} - SQL_USER=${POSTGRES_USER} - SU_NAME=${SU_NAME} - SU_EMAIL=${SU_EMAIL} - SU_PASSWORD=${SU_PASSWORD} depends_on: - db logging: driver: "json-file" options: max-size: "100k" max-file: "20" db: image: postgres:11.2-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_USER=${POSTGRES_USER} logging: driver: "json-file" options: max-size: "100k" max-file: "20" nginx: build: ./nginx restart: unless-stopped volumes: - static_volume:/usr/src/app/assets ports: - 80:80 depends_on: - web logging: driver: "json-file" options: max-size: "100k" max-file: "20" volumes: static_volume: postgres_data: external: true and this is my nginx.conf file: upstream my_server { server web:8000; } server { listen 80; location / { proxy_pass http://my_server; proxy_set_header Host $http_host; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP … -
Send a list using django message framework
In short, I am struggling to extract list contents that were passed to the template using the message framework. In long: My webapp has an import transactions capability where the user selects a csv and I upload each record to the database. For records that fail, I am storing these as a list, such that I can display on the next page which transactions weren't successful. Each transaction has a number of fields, so essentially its a list of lists. Simply, I create an 'errorRecords' list, which I then loop over and add to the message framework. The data gets to the template just fine, but I am struggling to use normal list operations to extract the data correctly. Have looked at similar code passing dicts and json, but the similar approach, just using a list doesn't seem to work for me. Creation of the message in the View: for item in errorRecords: messages.add_message(request, messages.WARNING, item) The problem then comes at the template stage: {% for message in messages %} <tr> <td>{{ message[0] }}</td> <td>{{ message[1] }}</td> </tr> {% endfor %} Which gives the following error: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[0]' from 'message[0]' I've also tried message.message[0] which … -
Moving Django configuration
I have some configuration that was done and stored in a database in Django 1.11 running on python 2.7 and I need to move it from dev to production. I wasn't the one who did the work but I am tasked with moving the configuration from dev to prod. Is there anyway to get a diff of content. It is configuration related to social core auth. -
Error handling post request in Django and getting "Too long to shutdown and was killed"
I am running daphne server in production and getting following error Application instance <Task pending coro=<AsgiHandler.__call__() running at /home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/channels/http.py:213> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/lib/python3.6/asyncio/futures.py:403, <TaskWakeupMethWrapper object at 0x7f0b49b6a6a8>()]>> for connection <WebRequest at 0x7f0b48daa438 method=POST uri=/api/getMessages clientproto=HTTP/1.1> took too long to shut down and was killed. It is happening in following POST request: class GetRoomMessages(APIView): def post(self, request): room_no = request.data.get('room_no', None) message_id = request.data.get('message_id', None) order = request.data.get('order', None) message_instance = None if(order == 'old'): try: message_instance = Message.objects.filter(room_no=room_no, id__lt = message_id).order_by('-id') except Exception as e: print(e) return status_500() elif(order == 'new'): try: message_instance = Message.objects.filter(room_no=room_no, id__gt = message_id).order_by('id') except Exception as e: print(e) return status_500() if(message_instance is not None): serializer = MessageSerializer(message_instance, many=True) return status_200("success", serializer.data) else: return status_400("Invalid Request") I am not sure why this is happening, but it happens when there are a lot of messages to serialize. I don't think it is taking time to serialize but rather I think the size of response might be too big. Is that the case in general? If not, can you please tell me what is the reason for same? -
im getting this error while using templateview
TypeError at / expected str, bytes or os.PathLike object, not tuple i just started templateview, CBVs and im getting this issue from django.shortcuts import render from django.views.generic import View,TemplateView from django.http import HttpResponse class indexView(TemplateView): template_name = 'index.html' TypeError at / expected str, bytes or os.PathLike object, not tuple -
How to create a queryset to filter jsonb fields with __ in key name
I have a jsonb field in one of my django model. Somebody has inserted few key value pairs in this json with __ in key name. Eg json: data: {'base_cover__tenure': 2, 'base_cover__variant': '125 Z', } How can I create a queryset to filter on these fields? I have tried this MyModel.objects.filter(data__base_cover__tenure__gte=1), which obviously doesn't work. -
Django project - crispy forms not rendering in the browser
As part of a Django project, I have created the following in the views.py file def profile(request): u_form =UserUpdateForm() p_form =ProfileUpdateForm() context={ 'u-form': u_form, 'p-form': p_form } I am now trying to render these forms on the html page (profile.html) with the following code: {% extends "socialmedia/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Information</legend> {{u_form|crispy}} {{p_form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update....</button> </div> </form> </div> {% endblock content %} Everything else is rendering on the page correctly, except for this bit: {{u_form|crispy}} {{p_form|crispy}} There are no errors on running the server, so I am finding it hard to trouble shoot. The code in the forms.py file is as follows: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): #form that inherits from the usercreationform email = forms.EmailField() class Meta: model = User #when this form validates it creates a new user #type the fields to be shown on your form, in that order. fields … -
Docker Alpine: Error loading MySQLdb module
I am building an Alpine based image of a Django application with MariaDB and I can't figure out which dependency I should add to my Dockerfile so that my app could properly connect to the DB. django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Well, I thought I did. From what I read in this article, in this discussion, mariadb-dev is in Alpine the equivalent of default-libmysqlclient-dev in Debian based system. Furthermore, the mysql-client package in Alpine is merely a dummy package (containing mariadb-dev, mariadb-client, etc etc). Here is the Dockerfile: # pull official base image FROM python:3.7-alpine # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # set work directory WORKDIR /usr/src/cms # install mysqlclient RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add --no-cache mariadb-dev\ && apk del build-deps # install dependencies RUN pip install --upgrade pip RUN pip install pipenv COPY ./Pipfile /usr/src/cms/Pipfile RUN pipenv install --skip-lock --system --dev # copy entrypoint.sh COPY ./entrypoint.sh /usr/src/cms/entrypoint.sh # copy project COPY . /usr/src/cms/ # run entrypoint.sh ENTRYPOINT ["/usr/src/cms/entrypoint.sh"] I tried to add mariadb-client, to use mysql-client instead. I also tried to add RUN pip install django-mysql. Nothing seems to change. … -
How do I verify in a Django unit test that my context contains a form object?
I'm using Django and Python 3.7. I have this view ... def get(request): context = {} if not request.GET: tax_calculator_form = TaxCalculatorForm() else: ... context['form'] = tax_calculator_form return render(request, "tax_calculator.html", context) I want to write some kind of assertion in my unit test that verifies the model contains my form object. How do I do that? So far I have # Simple test to verify we can get the tax form def test_get_tax_form(self): response = self.client.get("/form") self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "tax_calculator.html") -
How to send request.user properly to a model form?
I would like to update the configuration of a device using a Model Form. I suceeded in passing the user to the model form and I can choose device_id which belongs to the current user. But when I submit the Form, i get an error: init() got multiple values for argument 'user' Is there also a way to put the additional Field "your_device" as the first (before all other fields) of the model form? I tried to remove user = request.user from the POST Method in views.py but then I get another error: int() argument must be a string, a bytes-like object or a number, not 'QueryDict' This is my forms.py: class ConfigForm(forms.ModelForm): your_device = forms.ModelChoiceField(queryset=Device.objects.none()) class Meta: model = Config fields = [ 'location', 'meas_pos', 'loudest_pos', 'spl_range', 'weighting', 'tx_int', 'offset', 'limit', 'notification'] def __init__(self, user, *args, **kwargs): super(ConfigForm, self).__init__(*args, **kwargs) self.fields['your_device'].queryset = Device.objects.filter(Q(customer=user) | Q(admin=user)) and my views.py: def config_view(request): if request.method == 'POST': form = ConfigForm(request.POST, user = request.user) if form.is_valid(): instance = form.save(commit=False) object_id = form.cleaned_data.get('your_device') id_ = Index.object.get(id=object_id).device_id instance.device_id = id_ index_id=Index.objects.get(device_id=id_) instance.cfg_nbr=index_id.current_cfg+1 index_id.current_cfg=index_id.current_cfg+1 index_id.cfg_received=False index_id.save() instance.save() messages.success(request, f'Configuration successfully changed!') else: form = ConfigForm(user=request.user) context = { 'form' : form } return render(request, 'my_spl/config.html', context) -
drf extensions serializer field to foreignkey getting default view_name not set base_name
I am working on a sample Django Rest Framework implimentation with drf-extensions for nesting routes. to start off my models are simple class BlogPost(models.Model): owner = models.ForeignKey(User,related_name='bposts',on_delete=models.CASCADE,editable=False) title = models.CharField("Blog Title",max_length = 30) content = models.CharField("Blog content",max_length=200) def __str__(self): return self.title class Comments(models.Model): owner = models.ForeignKey(User,related_name='cposts',on_delete=models.CASCADE,editable=False) comment = models.CharField("Comment",max_length=50) blogpost = models.ForeignKey(BlogPost,related_name='Comments',on_delete=models.CASCADE,editable=True) def __str__(self): return self.comment My Viewsets are also simple, class BlogPostViewSet(NestedViewSetMixin,viewsets.ModelViewSet): queryset = BlogPost.objects.all() serializer_class = BlogPostSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) class CommentViewSet(NestedViewSetMixin,viewsets.ModelViewSet): queryset = Comments.objects.all() serializer_class = CommentSerializer my routes are setup how they are suposed to be, from rest_framework_extensions.routers import ( ExtendedDefaultRouter as DefaultRouter ) router = DefaultRouter() m_router = router.register(r'users', views.UserViewSet, base_name='user') m_router.register(r'BlogPosts', views.BlogPostViewSet, base_name='user-BlogPosts', parents_query_lookups=['owner'] ).register(r'Comments',views.CommentViewSet, base_name='user-BlogPosts-Comments', parents_query_lookups=['owner','blogpost'] ) and lastly my serializers are also a basic setup class BlogPostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BlogPost fields = ('id','owner','title','content') class CommentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Comments fields = ('id','owner','comment',blogpost) when I open up the django rest framework API browser, all the url mappings are correct as needed. The problem I am having is on the CommentsSerializer on the blogpost field, I get the could not Resolve URL error. The issue is due to it looking for blogpost-detail not user-BlogPosts-detail like its suposed to. Is there … -
my django website says "We're sorry, but something went wrong" in production
my django website was working in debuging mode but when I put it on the server and turned it to production mode, my website shows me the error: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. I have checked out my settings, my passenger_wsgi.py file and I wrote it it this line from myproject.wsgi import application and also run the followed commands python manage.py collectstatic python manage.py migrate python manage.py makemigrations and the problem still exist what else can I do? . -
How do I count the number of submitted GET params?
I'm using Django and Python 3.7. I have a view method that I want to serve the page with an empty form if no GET params were submited and otherwise build the form and validate it. def get(request): if no GET params submitted: tax_calculator_form = TaxCalculatorForm() ... else: form = TaxCalculatorForm(request.GET) How do I figure out how many (if any) GET parameters were submitted? -
Can I connect a "Player" class from models to a field in UserCreationForm from the Django library
I am creating an app that allows you to input your name, email, password in a form and it creates a Player with a base integer ELO score, date field, and name and later add a form that creates a Game with 2 Player fields, 2 integer fields for goals scored, and a date field. The app will have 3 main form functionalities: 1) lookup player game history and score 2) add game (I want to add games in a way that they are connected to the Players that are input), and finally register (create a User with a name, password and email login and use the name to create the Player instance that will be bound to the user. I can currently access my admin page and manually choose a user for the Players that I created in the terminal but I am confused how I should create my registration form in a way that the Player is created automatically when the user registers. Hopefully once I see how binding Players to Users works I will be able to figure out how to bind Games to Players I have tried adding a forms.ModelField(Player) and made the field hidden but … -
How to save credit card information and use it for future purchases with Django and Stripe?
I am creating an e-commerce with Django. During the user registration, I would like to get the user's credit card information so that, in the future, when the user tries to buy something, he/she does not have to insert his/her credit card information again. Currently, I am having problems dealing with Stripe (creating this form to get the credit card info and then processing payment with the stored info both in Django and Stripe). Based on the Stripe documentation, I understood that I should save a user's customer id in my Django database, and then, in the future, I will use this customer id to retrieve this user's info from stripe. However, I am very confused about this process: 1) Get card information. 2) Save card information (customer id in Django and create customer in Stripe) 3) Use the saved information for future purchases. This is my checkout view in Django: def checkout_two(request): if request.method == "POST": # Creating a Customer in the stripe platform. customer = stripe.Customer.create( # How to create such form to get the info below? source=request.POST['stripeToken'], # How to get token? # email="john@email.com", # How to get email? ) # Charging the Customer instead of the …