Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Cookiecutter-django - DB doesn't seem to have project's tables
I initialized a project with cookiecutter-django according to the instructions in the docs, including setting up a PostgreSQL DB under the same name as the project slug. I can't seem to find any project-related tables in the DB. It contains 3 schemas: information_schema - no project-related tables there, obviously. pg_catalog (it's my first time working with Postgre, but I'm assuming no project-related tables would be there. Currently, nothing is.) public - it's empty. Some DB actions I can still make from the Django admin page, but I'd rather have direct access to the DB tables (mostly for self-verification). Thanks for any help. -
How to add a button near to each object in django 3.0 admin
I am developing a project which includes feature like sending mail. There will be different providers eg : amazone ses, sengrid etc. I have to test a provider by sending a test mail. SO how can i add a button to each provider object in model list page. There will be a button (send test mail) for each object in the model list also After sending a mail it should give success response in the page like we get after saving a model. Thanks in advance. -
Is it possible to add fields to the table "account_emailaddress"?
I want to add a new field to an existing table account_emailaddress (preserving this table), from allauth. But I can't figure out how to do it. Is it possible to customize the model? Thank you very much! -
Why am I getting this error when installing daphne?
First time attempting to run py -m pip install daphne from my django project directory: WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system can not find the file specified: 'C:\\Python39\\Scripts\\automat-visualize.exe' -> ' C:\\Python39\\Scripts\\automat-visualize.exe.deleteme' Second attempt: WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system can not find the file specified: 'C:\\Python39\\Scripts\\cftp.exe' -> 'C:\\Python39\ \Scripts\\cftp.exe.deleteme' Where am I supposed to get these files from? -
Django djsonfield Decimal stored as string in expressions
I have a JSONField with some financial data. I cannot store it as a float, because I need precision, so I store it as a string. My model looks like this class Finance(models.Model) bill_data = JSONField( verbose_name=_("Bill data"), default=dict, blank=True, ) then I save bill_data = dict(paid=str(some_decimal_amount)) Finance.objects.create(bill_data=bill_data) I try to use Cast to convert it back to Decimal, because I need to use expressions, Finance.objects.all().annotate(paid=Cast('bill_data__paid', DecimalField())) I get an error return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "none" LINE 1: ...der"."bill_data", ("myapp_finance"."bill_data")::numeric(No... Does anyone know how to use str from JSONField in expressions or how to handle Decimal in JSONField correctly? -
How to retrieve these lines from postgres JSON-field based on key value pair with Django filter
In Django I have a model: class NewModelItem(models.Model): model = models.ForeignKey(to=NewModel, on_delete=models.CASCADE, related_name='new_model_item') field_data = models.JSONField() link_data = models.JSONField(null=True) and like to retrieve: 3 {"name": "105000-001-001", "customer_name": "belangrijk sample"} 4 {"index": 4, "project": [1]} 6 {"name": "105000-001-002", "customer_name": "nog een belangrijk sample"} 4 {"index": 4, "project": [1]} based on the last field (that's the link_data field) and specifically when project contains 1. I tried it as an integer instead of an array, but the filter below does not retrieve them either way. I would kindly ask for any help or suggestions. lookup = 'link_data__project' related_model = 4 # this is the field before link_data id = 1 data = NewModelItem.objects.filter(**{lookup: id, 'model': related_model}) -
Update data mismatching in Modal(pop-up) - Djanago Rest Framework
I'm practicing Django Rest Framework. I'm using data from API URL in the front end using JavaScript created by serializing the models. Furthermore, I have two models To-do and Task. Where Task is the subcategory of Todo. Task comes under Todo. The problem I'm facing was I was able to create a Task item under a particular Todo. But I was unable to update Todo, , update Task, delete Task and mark Task as completed. I was able to update first Todo item that displayed at the top of the list. If I want to update second item I couldn't do it. Task item was created under a Todo. Let's take a scenario, If I have two Todo items and two Task items under each Todo. If I delete 1st Task item from 1st Todo, but the 1st task element from both the Todo gets deleted. But I want to delete the 1st task from 1st todo item only. I know it's quite confusing for you to understand. Let me share the code and some images for the better understanding of the problem I'm facing. models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, … -
Creating Signature and Greeting SMTP email setting Django
Anyone can help me, I want to add signature and greeting on email. I am using Django SMTP service to send the email but the default signature do not added while sending email. def form_valid(self,form): subject="Thank you" message = 'I hope.' from_email = settings.EMAIL_HOST_USER to_list = [form.cleaned_data.get('email')] send_mail(subject,message,from_email,to_list,fail_silently=True) return super(SignupPageView, self).form_valid(form) Here I want to add signature also because default signature does not work. Can anyone help me to add signature or there is any other way to add default signature so I can include it. I sending email via Gmail SMTP service -
Is it safe to dump django data and remake migrations?
I'm not entirely sure if this question belongs on SO or on some discussion board (I would appreciate any pointers) but I'm gonna put it here first. If it turns out to be out of place I'll delete it. I have a Django app in production with a few users and maybe about 20k records. The models have undergone so many changes over 3+ years and I want to tidy it up. I know about squashing migrations but that is not exactly what I'd like to achieve (though it could be a good compromise). My plan now is this dump the data delete all migration files and run manage.py makemigrations to generate new and fewer migration files create a new db and use manage.py loaddata to load the data back. I do this fairly regularly when I want to work with production db on my local and so far I haven't encountered any issues. Usually takes about 15 minutes to complete data dump and re-upload. I want to get more opinions on whether its safe to go this route. If there's anything I need to watch out for. For contentTypes, I do delete unused contenttypes using django admin interface. My …