Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serverless WSGI not working in pipelines (works locally)
I have the following steps configured in our bitbucket pipeline: # Configure Serverless - cp requirements.txt src/requirements.txt - serverless config credentials --provider aws --key ${AWS_KEY} --secret ${AWS_SECRET} - cd src - sls plugin install -n serverless-python-requirements - sls plugin install -n serverless-wsgi - sls plugin install -n serverless-dotenv-plugin # Perform the Deployment - sls deploy --stage ${LOCAL_SERVERLESS_STAGE} - sls deploy list functions # Prep the environment - sls wsgi manage --command "migrate" - sls wsgi manage --command "collectstatic --noinput" When the pipeline runs, the sls deploy works perfectly fine and the deployed function operates exactly as expected. The sls wsgi manage commands throw the following error, however: Serverless Error ---------------------------------------- Function "undefined" doesn't exist in this Service Get Support -------------------------------------------- Docs: docs.serverless.com Bugs: github.com/serverless/serverless/issues Issues: forum.serverless.com Your Environment Information --------------------------- Operating System: linux Node Version: 11.13.0 Framework Version: 2.35.0 Plugin Version: 4.5.3 SDK Version: 4.2.2 Components Version: 3.8.2 I can run the sls wsgi manage commands locally (with same AWS keys) without issue. The issue only seems to happen in the pipeline. Thoughts? -
how can I connect my image processing application in my android application
I have image processing application written in python consists of CRNN model, and I want to take an image from my android application and send it to the image processing and receive back a response from it. what should I use to make it done. -
Django Python annotate ManyToMany Relationship with additional information
my problem is the following. I have two models in the database, which I link together using a ManyToMany relationship. For the admin page I currently use "admin.TabularInline" to bind different objects to one via the graphic. I still want to specify an order in the connections, preferably numbers which represent an order for processing. A bit more figuratively described I have the model "Survey" and the model "SurveyQuestion". So I connect many SurveyQuestions with the Survey. But I can't specify an order, because I don't have an additional field for it. It is not known before how many questions will be in a survey. Nor is it known which questions will be inserted. Usually they are built during the compilation of the survey and may be used later for another survey. I am grateful for every tip! -
Django 3 - Add Context to admin base.html
Django 3: I have a Django Project and i want to modeify the admin page. I can edit the base.html for the admin page. Now i want to pass some context from my models to the base.html. How can i do that? Any ideas? -
I'e just started learning Django and i got stuck while creating a virtrualenv for some project,What does this mean?
Evalyns-iMac:trydjango2 Evalyn$ virtualenv -p python3 usage: virtualenv [--version] [--with-traceback] [-v | -q] [--read-only-app-data] [--app-data APP_DATA] [--reset-app-data] [--upgrade-embed-wheels] [--discovery {builtin}] [-p py] [--try-first-with py_exe] [--creator {builtin,cpython3-posix,venv}] [--seeder {app-data,pip}] [--no-seed] [--activators comma_sep_list] [--clear] [--no-vcs-ignore] [--system-site-packages] [--symlinks | --copies] [--no-download | --download] [--extra-search-dir d [d ...]] [--pip version] [--setuptools version] [--wheel version] [--no-pip] [--no-setuptools] [--no-wheel] [--no-periodic-update] [--symlink-app-data] [--prompt prompt] [-h] dest virtualenv: error: the following arguments are required: dest SystemExit: 2 -
Django 2.2 + AttributeError: 'str' object has no attribute 'decode'
We have done Django Upgrade from 1.11 to 2.2 version, we have almost completed, but there is one issue is present, when we run migrations by using the command "python manage.py makemigrations" then we are getting following error. but when we follow the below link issue is resolved. Migrations error in django 2; AttributeError: 'str' object has no attribute 'decode' but, I just want to know is there any other way to resolve this issue ?, I am feeling like there will be library to update which is causing this issue ? kindly advise Error message is : (env4) user2@SK385 pro % python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/Users/user2/Desktop/env4/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) … -
Django - Model form view does not display custom labels
I'm trying to change the labels of my form but for some reasons it does not work. models.py class Csv(models.Model): file_name = models.FileField(upload_to='csvs', max_length = 100) public = models.BooleanField(default = False) process_data = models.BooleanField(default = False) user = models.ForeignKey(User, on_delete = models.CASCADE, null = True) dataset_name = models.CharField(max_length = 100) library = models.CharField(max_length = 100, null = True) views.py class CsvFormView(SuccessMessageMixin, CreateView): model = Csv template_name = 'upload/upload.html' success_url = '/upload' success_message = "File Successfully uploaded." fields = ['file_name'] labels = {'file_name' : 'Browse'} upload.html <form action = "" method = "POST" enctype="multipart/form-data"> {% csrf_token %} {{form}} <button type = "submit">Upload File</button> </form> instead of labeling file_name as "browse", django just labels it as "File name" -
How do I properly pass KWARG keyword to get_context_data?
I am narrowing down an issue with my formset handling and I feel like this solution could be my answer. Django passing form_valid inline formset context to get_context_data() However, when I try it, I am getting an error trying to add the enrollmentErrors = kwargs['enrollment'].errors It says... KeyError: 'enrollment' I'm not new to Django...but formsets have me thoroughly challenged. Thanks in advance for any thoughts. -
Implementing Redsys InApp payment's in Flutter
I was wondering how to integrate Redsys InApp payment's into my Flutter project, I can find very good instructions for creating this process in Java but in Flutter it seem's like they're is barely to no information regarding this issue i'm having. In case it is not a good idea to integrate InApp payment's in Flutter would you suggest to use Redsys InSite payment method instead and manage the payment's on the backend using something like DJango? Thank you all for your time. -
Invalid syntax django
I'm trying to run a django code an imx6 yocto build that i made. The basic example went fine and smooth. So i decided to run my own django production from a project im working and i get the following: root@imx6ulevk:/home/mdwb-main# python manage.py runserver 147.106.17.9:8000 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/lib/python3.5/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/usr/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/usr/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3.5/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/lib/python3.5/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 693, in exec_module File "<frozen importlib._bootstrap_external>", line 799, in get_code File "<frozen importlib._bootstrap_external>", line 759, in source_to_code File "<frozen importlib._bootstrap>", line 222, … -
"POST /user/create/ HTTP/1.1" 500 82190
I am having a problem setting up authentication in django rest. Everytime I try to create a user using a post request to this url http://127.0.0.1:8000/user/create/ I get this error: AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> [09/Apr/2021 14:41:43] "POST /user/create/ HTTP/1.1" 500 82190. I have tried may solutions here with no success. views.py from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework.views import APIView from rest_framework import status, permissions from rest_framework.response import Response from .serializers import TokenObtainPairSerializer from rest_framework.generics import CreateAPIView from .serializers import CustomUserSerializer, MyTokenObtainPairSerializer class CustomUserCreate(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format = 'json'): serializer = CustomUserSerializer(data= request.data) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from .models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) username = serializers.CharField() password = serializers.CharField(min_length = 8, write_only= True) class Meta: model = CustomUser fields = ('email', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance urls.py from django.urls import path from rest_framework_simplejwt import views as jwt_views from .views … -
Django Rest Framework How to create two model instances in one endpoint?
I have 3 models: class CustomUser(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=255, unique=True, db_index=True) .... class Team(models.Model, HaveGUID): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=128) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') members = models.ManyToManyField(CustomUser, through='Membership') class Membership(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='teams') role = models.CharField(choices=Roles.choices, max_length=128) ... Now I have an endpoint for creating new team, and I ask for name only when user submitting the form. I create new team successfully However I want to also create a new membership instance and make user owner of the team. Views.py class TeamViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Team.objects.all() serializer_class = TeamCreateSerializer @action(methods=['post'], detail=False, url_path='create-team') def create(self, request): user = request.user data = request.data role = 'owner' member = {user,role} serializer = TeamCreateSerializer(data=data) # memberserializer = TeamMemberSerializer(data=member) ?? # if memberserializer.is_valid(): # memberserializer.save() if serializer.is_valid(): serializer.save() return Response({'message': 'successfully created ' + data['name'], 'success': True}) else: errors = serializer.errors return Response({'message': 'error creating Team', 'success': False, 'errors': errors}) How do I create this logic? The best way is using signals? Because it is all relational models, maybe there is an easier way to update membership model as well. Thanks! Serializers.py class TeamMemberSerializer(serializers.ModelSerializer): user = … -
Django filter and saving of the object
Below is the Django Code for filtering the DB and saving the object in Postgres DB for label in Label.objects.select_for_update().filter(uuid=tags_clean): label.remove_assets(soft_uuids) Class Label(): def remove_assets(self,uuids): self.save() a) select_for_update() get locks on the rows only while calling filter() or until save() is called for each label b) also what type of locking is taken is it Table locking or row locking -
Raising Http404 in Django
I have the following path: path("polls/<int:week_id>/vote/", views.vote, name="vote") And in my view, I wrote the following method: def vote(request, week_id): week = Week.objects.get(pk=week_id) try: selected_choice = week.choice_set.get(pk=request.POST["choice"]) except Week.DoesNotExist: raise Http404("Poll for said week does not exists") else: selected_choice.votes += 1 selected_choice.save() return redirect("results", week_id) I'm trying to raise an 404 page if a user navigates to polls/123/vote, where 123 is a non-existing week in the database. For some reason the code above returns a DoesNotExist error instead of the actual 404 page. I'm assuming that line of code were i'm raising the 404 page is not being hit. Is that right? -
Django edit row by row in a table
Im new to django and im trying to make a interactive table and be able to edit each row,one by one,meaning:the person using mysite can see all the table and after each row there is a edit button when he clicks it,it gives him the ability to edit that row only,i hope that makes sense here is my code: views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader from .models import Client from .form import Clientform from django.urls import reverse_lazy def editclient(request): pk = request.POST.get('id') client=Client.objects.get(pk) if request.method == 'POST': print("seen as POST") form = Clientform(request.POST, instance=client) if form.is_valid(): form.save() return render(request,'polls/editclient.html',{"form": form}) else: return render(request,'polls/editclient.html',{"form": form}) form.py from django import forms from .models import Client class Clientform(forms.ModelForm): class Meta: model = Client fields =['nom_client','prenom_client','ville_client','email_client'] base.html "the table part" <div> <table class="table table-striped table-dark" style="max-width: min-content;"> <tr> <th scope="col" style="width:10px">ID</th> <th scope="col"style="width: 20px">Nom</th> <th scope="col"style="width: 20px">Prenom</th> <th scope="col"style="width: 20px"> Ville</th> <th scope="col" style="width: 30px">Email</th> </tr> {% csrf_token %} {% for client in clients %} <tr> <td scope="row"> {{client.id}}</td> <td>{{ client.nom_client }}</td> <td>{{ client.prenom_client }}</td> <td>{{ client.ville_client }}</td> <td>{{ client.email_client }}</td> <td><a href="{% url 'editclient'%}" ><button type="button" name="id" value="{{ client.id }}">edit {{client}}</button></a></td> </tr> {% endfor %} </table> … -
why django-html 'block' autocomplete does not work
i want to use 'block'and 'extends' in django-html to extend template(base.html) 'block' autocompletion is only blockquote not block i checked that my html is Django-html Do I need additional configuration to use block,extends? -
How to put an array in message?
Just a simple question, how can i insert the content of an array to my message? messages.info(request, "text_a" , array , "text_b") This only provides me "text_a" after displaying a message. -
django direction to \ wrong URL href
My url is being directed to wrong location. The href when used in search.html it is directing me to the right location but when the same url I am using in categories.html, it is giving an error page of wrong location. categories.html {{news.title}} I have to get redirected to "http://127.0.0.1:8000/newspaperapp/results/detail/1" but instead of that it is directing me to http://127.0.0.1:8000/newspaperapp/category/results/detail/. This is my urls.py from django.urls import path app_name = 'newspaperapp' from django.conf import settings from . import views from .views import SearchView urlpatterns=[ path('',views.home,name='home'), path('results/', SearchView.as_view(), name='search'), path('results/detail/<int:id>',views.detail,name='detail'), path('category/<int:id>',views.category,name='category'), ] -
How Add Attribute To HTTP request Using middle ware
hi i want add attribute to Django HttpRequest objects by using custom Middleware like request.user how i can do that ? can any one give me some resources how to do that ? -
Downloading an Excel file in Django using AJAX, I get the error "File format or extension is not valid"
I am trying an excel file that is hosted on an Ubuntu server, the file is downloaded, but when I open it, I get the error of "Check that the file has not been damaged and that the extension matches the format", The weird thing is that it only happens with excel files, because when I do it with plain text files, the file doesn't get corrupted when downloaded. -
Django Form does not show up until it's submitted
I made a form in Django, but it's not showing up before it's been submitted. The forms.py looks like this from django.contrib.auth.forms import UserCreationForm from productapp.models import User from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField( max_length=100, help_text='Required. Add a valid email address!!', label='Email') name = forms.CharField(max_length=50, label='Name') password1 = forms.PasswordInput() password2 = forms.PasswordInput() class Meta: model = User fields = ('email', 'name', 'password1', 'password2') # email = forms.EmailField(max_length=100, help_text='required') The views.py file looks like this: from django.contrib.auth import get_user_model from .tokens import account_activation_token from .forms import SignUpForm from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes from django.template.loader import render_to_string from django.http import HttpResponse from django.core.mail import EmailMessage from django.contrib.sites.shortcuts import get_current_site from django.contrib.auth.tokens import default_token_generator from django.contrib.auth.models import User from dotenv import load_dotenv, find_dotenv from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate # Create your views here. from productapp.models import User UserModel = get_user_model() # Create your views here. def signup(request): print(request.POST) if request.method == 'GET': return render(request, 'authentication/register.html') if request.method == 'POST': form = SignUpForm(request.POST) print(form.is_valid()) if form.is_valid(): user = form.save(commit=False) user.normaluser = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string('authentication/email_template.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': … -
How to get the attributes or values in django response, the request sent through the django http requests
Just want to get the id that come in response when request has been placed, the request is working just to fetch the id from the response conn = http.client.HTTPSConnection("api.tap.company") payload = "{\"source\":\"" + tokenId + "\"}" headers = { 'authorization': "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ", 'content-type': "application/json" } conn.request("POST", "/v2/card/" + justCreatedCustomerId + "", payload, headers) res = conn.getresponse() data = res.read() body_unicode = data.decode("utf-8") body_data = json.loads(body_unicode) card_id = body_data['id'] request.session['generatedCardId'] = card_id return sponsorParticularPerson(request, sponsorProjectId) -
Django REST API browser page not showing
I have a Model with some Serializers as well as a ModelViewSet which handle the back-end. Usually when I go to the API endpoint in the browser it will show the Dajgno REST (Red and Gray) browasble API page: e.g. localhost:8000/api/some-api should show the REST framework page but returns the queryset in JSON instead. Right now when I go there I am being returned a JSON queryset, or if an error occurs it shows it in plain text (not even the Django error page). Maybe I deleted something somewhere? class PoliciesViewSet(viewsets.ModelViewSet): """ Policies and Procedures API endpoint. """ serializer_class = PoliciesSerializer authentication_classes = [TokenAuthentication, SessionAuthentication] permission_classes = [permissions.IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def get_queryset(self, *args, **kwargs): qs = PoliciesAndProcedures.objects.all() queryset = qs.filter( receiver=self.request.user.role ) | qs.filter( sender=self.request.user ) return queryset.distinct() router = routers.DefaultRouter() router.register('api/policies', PoliciesViewSet, basename='policies-api') urlpatterns = [ path('', include(router.urls)), ] When I visit http://test2.localhost:8000/api/policies/ it shows: [{"id":5,"category":{"id":3,"parent":{"id":1,"title":"Cat 1","parent":null,"groups":[6]},"title":"Subcat 1 - 1","groups":[1,2,3,4,6,7]},"title":"wefqwefq","contents":.... Thoughts? -
Wagtail Logging to file
I'm using wagtail 2.7, Django 2.2.5 and i'm trying to make logging to file. When DEBUG=True, all work fine and i have my logs. But when DEBUG=False in production my log file is empty. I tried a lot of different logging configs, but they doesn't work in prod, with one config i got DEBUG logs, but i can't get ERROR logs. My current config [appname/settings/base.py]: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(pathname)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'logging.FileHandler', 'filename': os.path.join(ev('APP_LOG_DIR'), "debug.log"), "formatter": "verbose", }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, 'django.request': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, 'django.server': { 'handlers': ['file',], 'level': 'ERROR', 'propagate': True, }, } With this config i got debug logs, but errors didn't work: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(pathname)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'fileError': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': os.path.join(ev('APP_LOG_DIR'), "error.log"), "formatter": "verbose", }, 'fileDebug': … -
How to add several model in one page and handle it?
I have a main model Report: class Report(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True) result_doc = models.FileField(upload_to="lab_result_doc/%Y/%m/%d", null=True, blank=True) date_of_loss = models.DateTimeField(null=True, blank=True) date_of_inspection = models.DateTimeField(null=True, blank=True) report_date = models.DateTimeField(null=True, blank=True) inspector = models.ForeignKey(Inspector, on_delete=models.CASCADE, null=True, blank=True) license = models.CharField(max_length=100, null=True, blank=True) observations = models.CharField(max_length=100, choices=OBSERVATION_CHOICES, blank=True, null=True) report_sample = models.ManyToManyField('Sample', verbose_name='samples') Report sample refers as ManyToManyField to another Model: class Sample(models.Model): serial = models.CharField(max_length=200) location = models.CharField(max_length=200) results = models.CharField(max_length=200, null=True, blank=True) analysis = models.ForeignKey(SampleType, on_delete=models.CASCADE) upload_picture = models.FileField(upload_to="sample/%Y/%m/%d") picture_title = models.CharField(max_length=200) picture_note = models.CharField(max_length=110) I need to make a one page, in which there is a form, in which I can create as many examples as needed. There is a form in blue box. And there is a examples form in red box. I need to add some examples and they are need to show in a table. And When I click "Report Button" all of the examples as well as other form fields needs to be saved into Model. problem image I am trying to implement it already two days. But I am stuck. Please help me.