Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to retrieve static files into a django project from S3 bucket, but able to upload. Any suggestions?
Following is the settings.py file. I've tried varying combinations of enabling and disabling STATIC_ROOT, status quo remains disabled. Have added CORS and Bucket policy as per templates available on AWS. Alas ! Still no CSS rendered. Django settings for baatcheet project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path import sec # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ with open(os.path.join(BASE_DIR, 'secret_key.txt')) as f: SECRET_KEY=f.read().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['https://test-astratechztestapp.pagekite.me', 'localhost', '127.0.0.1', '*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', 'rest_framework', 'corsheaders', ] AUTH_USER_MODEL = 'base.User' MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'baatcheet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'baatcheet.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { … -
i need to put javascript validation in django
I have a javascript validation but it doesn't work for me, I think it may be sweet alert I think that sweetalert is validating before the validation that I have in javascript javascript validation: const $email_validation = document.getElementById('email_validation'); const $contrasena_validation = document.getElementById('contrasena_validation'); const $formularioempleado = document.getElementById('formularioempleado'); var $expresion_email, $expresion_password; $expresion_email = /^([\da-z_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; $expresion_password = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/; (function() { $formularioempleado.addEventListener('submit', function(e) { let email=String($email_validation.value).trim(); let contrasena=String($contrasena_validation.value).trim(); if(email.length === 0 || contrasena.length === 0){ alert("Todos los campos son obligatorios"); e.preventDefault(); } else if(email.length>100){ alert("El correo es muy largo"); e.preventDefault(); } else if(!$expresion_email.test(email)){ alert("El correo no es valido"); e.preventDefault(); } else if(contrasena.length>255){ alert("La Contraseña es muy larga"); e.preventDefault(); } else if(!$expresion_password.test(contrasena)){ alert("Contraseña: Debe contener al menos un numero y una letra mayúscula y minúscula, y al menos 8 caracteres o más"); e.preventDefault(); } e.preventDefault(); }); })(); createuser.html: {% extends 'app/base.html' %} {% block contenido %} {% load crispy_forms_tags%} <div class="container"> <div class="row"> <div class="col-md-3"> </div> <div class="col-12 col-md-6 content m-0 mt-2 mb-2 pt-2 pb-2" > <form class="p-0" method="POST" id="formularioempleado"> {% csrf_token %} <h2 class="text-center">Crear Empleado</h2> <hr> {{empleado | crispy}} <input class="btn btn-primary mb-2" type="submit" value="Crear Usuario"> <hr> </form> </div> <div class=" col-md-3"> </div> </div> </div> views.py(here i have the message of the sweetalert) def … -
Why does django admin inline save fails when inline contains readonly primary key?
Why isn't it possible to have a readonly inline related object in the django admin? In the example below, as soon as I add id in the readonly_fields, it breaks when trying to save the OtherFoo model. I found this ticket in the django project that was closed years ago and the alternate ticket does not help. class FooInline(admin.TabularInline): model = Foo fields = ( "id", "link", "content", ) readonly_fields = ( "id", # <=============== "link", "content", ) class OtherFooAdmin(admin.ModelAdmin): inlines = [ FooInline, ] -
Adding a Direct Messaging page to react native social media app with Django backend
I am trying to develop a react native social media app with Django backend. I need my app to have a Direct Messaging page. I already have made the Django backend and the React Native frontend without the messaging functions. How can I add the Direct Messaging to my existing backend and frontend? -
Why do i need to use a virtual envirotment with django?
I'm new to django and i want to know why i need to use a virtual enviroment for django. (you have not to read the next it's for stack overflow) i just get started with web developpement blablablablabalabalablablabalablablabalaablablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalan -
How to filter by all in queryset
I've got a queryset within a function. In some cases, I want to filter by a specific model. cars = Car.objects.filter(model='Toyota') In other cases, I don't want to filter by this field at all. Eg. (Syntax is wrong, but it demonstrates what I'm after) cars = Car.objects.filter(model=all) How do I include a field within a queryset as shown above, but prevent it from limiting the results? Thanks! -
How to serve a css file in production using django 4.1?
I have been stuck on this for two days now, I've searched high and low but can't find the solution. I'm trying to use a base.css file in production to render my CSS but it's not working. When I run python manage.py runserver I get this error "GET /static/css/base.css HTTP/1.1" 404 1896 When I run python manage.py findstatic base.css It can find the base.css file file Found 'base.css' here: C:\Users\static\base.css. I think my setup is correct but I must be missing something If someone could help me I would really appreciate it. I'm using Django 4.1 in VS code. settings.py import os BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'home', ] STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('home.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) base.html CSS link {% load static %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"> home app index.html {% extends "base.html" %} {% load static %} -
AttributeError at /appointment/create-appointment/ '__proxy__' object has no attribute 'get'
I had created a appointment creation form and appointment book form whenever I login as doctor or user and try to create or book appointment respectively it is showing me error after I click copy/paste view to find out error I am not getting can you please help me out. below is error and code. Request Method: GET Request URL: http://127.0.0.1:8000/appointment/create-appointment/ Django Version: 3.2.7 Python Version: 3.9.6 Installed Applications: ['m1.apps.M1Config', 'authenticate_me.apps.LoginModuleConfig', 'appointment.apps.AppointmentConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Ashraf\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Ashraf\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\deprecation.py", line 119, in __call__ response = self.process_response(request, response) File "C:\Users\Ashraf\AppData\Local\Programs\Python\Python39\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /appointment/create-appointment/ Exception Value: '__proxy__' object has no attribute 'get' code: class AppointmentCreateView(CreateView): template_name = 'appointment/create-appointment.html' form_class = CreateAppointmentForm extra_context = { 'title': 'Post New Appointment' } success_url = reverse_lazy('appointment:home1') @method_decorator(login_required(login_url=reverse_lazy('authenticate_me:login'))) def dispatch(self, request, *args, **kwargs): if not self.request.user.is_authenticated: return reverse_lazy('authenticate_me:login') if self.request.user.is_authenticated and self.request.user.is_doctor: return reverse_lazy('authenticate_me:login') return super().dispatch(self.request, *args, **kwargs) def form_valid(self, form): form.instance.user = self.request.user return super(AppointmentCreateView, self).form_valid(form) def post(self, request, *args, **kwargs): self.object = None form = self.get_form() if form.is_valid(): return self.form_valid(form) … -
How to pass keys and values in ModelForm ModelChoiceField in django
I have three tables user, doctor, and patient. User table contains Username , password, status , etc. User table is auth table of Django. doctor table contains id, user_id(foreign key),and other information. patient table contain doctor_assignid(foreign key), name ,etc. so, trying to get the username from user table and id form doctor table. And pass those data in ModelForm ModelChoiceField. class PatientForm(forms.ModelForm): assigned_doctor=forms.ModelChoiceField(queryset=None,empty_label="Name of the Doctors",to_field_name='username') class Meta: model= patient fields=['patient_first_name','patient_last_name','address','mobile','age','symptoms'] def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(PatientForm, self).__init__(*args, **kwargs) if self.request: users = self.request.user.id adminId = hospitalAdmin.objects.all().filter(user_id=users).values('pk') doctors=doctor.objects.filter(assigned_hospitalAdmin=adminId[0]['pk']) userTableDoctor = User.objects.filter(id__in=[i.user_id for i in doctors],status=True) userTableDoctor = userTableDoctor.values('username','doctor__id') assignedDoctorId = self.fields['assigned_doctor'] assignedDoctorId.queryset = userTableDoctor but, I'm getting dictionary like querset like this which is not an acceptable parament to pass. So, I want to display the username and If the user selects the username the backend receives the doctor id. So, is there any way to pass as an object or any other way to solve it -
In javascript when adding an image, the src can't find the image because it redirects firstly to the html file and then searches for the image
How do i add an image without it going thrue the html file first? test is the html file. It shows "not found" cause it goes thrue the html file first which is test GET http://127.0.0.1:8000/test/images/a11.png 404 (Not Found) Javascript file var imgQuestion1 = document.createElement("img"); imgQuestion1.src = "images/a11.png"; var block = document.getElementById("question"); block.appendChild(imgQuestion1); -
django/drf: many-to-many, serializer, duplicates
I have M2M relationship between models Combo and ComboLinks. User should be able to provide ComboLinks that are gathered by the backend into a one Combo. This is done with through DRF serializer and it works but with an issue: if a user provides a list of ComboLinks that has one or more ComboLinks already present in the database - duplicate is created. How can I avoid creating those duplicates and use already present ComboLinks to point to new Combo object? django model structure: class Combo(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='searches') updated = models.DateTimeField(auto_now = True) class ComboLink(models.Model): combo = models.ManyToManyField('Combo', blank=True, related_name='links') title = models.CharField(max_length = 64, null=True, blank=True) django view: @api_view(['GET', 'POST', 'PUT', 'DELETE']) def getCombo(request, pk=None): user = request.user # for all paths besides create new search if (pk != 'new') and (pk != None): combo = Combo.objects.get(id=int(pk)) if user != combo.user: return Response('Not valid user for a search', status=status.HTTP_401_UNAUTHORIZED) # handle different request methods if request.method == 'GET': serializer = ComboSerializer(combo, many=False) return Response(serializer.data, status=status.HTTP_200_OK) if request.method == 'POST': data = request.data data['user'] = user.id combo = Combo.objects.create(user= User.objects.get(id=user.id)) serializer = ComboSerializer(instance = combo, data = data) if serializer.is_valid(): print('updateSearch: combo serializer IS valid') serializer.save() combo.save() … -
Django forbidden 403 Origin checking failed csrf failed
I'm running django on a docker machine. Everything works just fine, but when I want to login into the admin site I get 403 forbidden Origin checking failed - https://example.com does not match any trusted origins. I've tried to add some other settings like: ALLOWED_HOSTS = [ "example.com", "127.0.0.1", "localhost", ] CSRF_TRUSTED_ORIGIN = ["https://example.com"] if PRODUCTION: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True as it is mentioned here and here but it doesn't work either. This is my nginx setup: server { server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/example/data/static/; } location /media/ { alias /home/example/data/media/; } location / { proxy_pass http://127.0.0.1:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } how do I fix this error? -
How to configure Django Dynamic Menu with the URLs.py
My app is generating a list that would be the side menu, like this: Views.py: def generate_menu(request): array = [] deviceList = [] f1 = open('dictionary.txt', 'r') array = f1.read() array = literal_eval(array) for i in sorted(array): deviceList.append(i) f1.close() context.update({'deviceList': deviceList}) return render(request, "device_list.html", context) Now in my Template, I am doing this to create the menu based on dic file: device_list.html: <nav id="sidebar"> <ul class="list-unstyled components"> <li class="active"> <a href="device_list">Device List</a> </li> {% block devices %} {% for each in deviceList %} <li> <form action="/{{each}}" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" value={{each}} name='DEVICES'>{{each}}</button> </form> </li> {% endfor %} {% endblock %} </ul> </nav> URLs.py: url(r'^$', app.views.index), url(r'^(?P<string>.+)$', app.views.generate_menu, name='DEVICES'), and it doesn't work here. So how can I change the URL in a way to accept all kind of request like http://127.0.0.1/Device* because all device list names, are different and they need their own url. So I need to have a url path that is dynamic. -
CKEditor breaks when debug = False
I'm nearing the end of my project, a blog. I have set DEBUG = False for security. This breaks my CKEDITOR, making it just not appear at all when the page is loaded. When DEBUG = True it works fine. template: <form class="text-center m-3" action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button class="btn btn-signup right" id="button">Post &raquo;</button> forms.py: class PostForm (forms.ModelForm): class Meta: model = Post fields = ('title', 'excerpt', 'featured_image', 'content', 'author') widgets = { 'title': forms.TextInput(attrs={'placeholder': 'Give it a catchy title'}), 'excerpt': forms.TextInput(attrs={'placeholder': 'E.g. My first ever post'}), 'content': forms.Textarea( attrs={'placeholder': '<p>Wrap your content in these P tags to create a paragraph</p> \ \n\n<b>Wrap your words in these B tags \ to make them bold</b>'}), 'author': forms.TextInput( attrs={'class': 'form-control', 'value': '', 'id': 'user', 'type': 'hidden'}), } -
How to post data in nested serializer using id field
I'm trying to post data in nested serializer using only id field, but it does not work. This project is for making orders in restaurants What i want to see Here is how i push data: { "is_done": false, "dishes": [ {"dish":1} ] } The GET request looks like this: { "id": 14, "is_done": false, "dishes": [ { "dish": 1, "quantity": 1 } ] } But I want to see it like this { "id": 14, "is_done": false, "dishes": [ { "dish": { "id": 1, "name": "Simple dish 1", "price": "200.00" }, "quantity": 1 } ] } Here is my python code OrderItemSerializer OrderSerializer class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ( 'dish', 'quantity', ) class OrderSerializer(serializers.ModelSerializer): dishes = OrderItemSerializer(many=True, read_only=False) class Meta: model = Order fields = ( 'id', 'is_done', 'dishes', # 'created_at', # 'updated_at', ) def create(self, validated_data): order_items = validated_data.pop('dishes') order = Order.objects.create(**validated_data) for dish in order_items: OrderItem.objects.create(order=order, **dish) return order def update(self, instance, validated_data): order_items = validated_data.pop('dishes') instance.is_done = validated_data.get('is_done', instance.is_done) instance.save() for dish in order_items: order_item = OrderItem.objects.get(order=instance) order_item.dish = dish['dish'] order_item.quantity = dish['quantity'] order_item.save() return instance Models class Order(models.Model): is_done = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = … -
Django MultiPartParserError
I am trying to send image to the django server. Here is my code: @csrf_exempt def classify_image(request): if request.method == 'POST' and request.FILES: try: image = request.FILES['file'] if image: img_b64 = b64encode(image.read()) res = main.classify_image(img_b64) return JsonResponse({ "status": "ok", "result": { "class": res[0], "confidence": res[1], } }) except Exception as e: return JsonResponse({ "status": "error", "error": str(e) }) return JsonResponse({ "status": "error", "error": "Image file is required" }) But I keep on getting I am sending requesting using postman, here's the sample The weird thing is the code was working perfectly fine some hours ago. Later I didn't change a single thing but it was throwing error. -
Integrity error while adding foreignkey in a migrated table
I tried to add a foreign that is already migrated but it seems error like django.db.utils.IntegrityError: insert or update on table "adminpanel_product" violates foreign key constraint "adminpanel_product_categories_id_id_cd41514d_fk_adminpane" DETAIL: Key (categories_id_id)=(1) is not present in table "adminpanel_categories". -
How to create or update a model with Django REST Framework?
I would like to create or update a model Account by specifying the fields id and params with the REST Framework. To begin with, I try to create the model but I'm constantly getting 400 or 500 error code. What am'I missing? client data = dict(id=18, params=dict(foo='bar')) res = requests.post('http://container-django-1:8002/api/account/', data=data, headers={'Authorization': 'Bearer {0}'.format(instance.bookkeeper.jwt_token)} ) server models.py class Account(TimestampedModel): active = models.BooleanField(null=True, blank=True, default=False) params = models.JSONField(default=dict, blank=True) views.py class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer queryset = Account.objects.all() http_method_names = ['post'] serializer.py class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('id', 'params',) def create(self, validated_data): return Account.objects.create(id=validated_data['id'], params=validated_data['params']) urls.py router = routers.DefaultRouter() router.register("account", AccountViewSet, basename="accounts-list") urlpatterns = [ path('', include(router.urls)), ] Output container-django-1 | 2022-09-03T18:14:22.785593661Z Starting development server at http://0.0.0.0:8002/ container-django-1 | 2022-09-03T18:14:22.785604944Z Quit the server with CONTROL-C. container-django-1 | 2022-09-03T18:17:09.252092179Z Bad Request: /api/account/ container-django-1 | 2022-09-03T18:17:09.253001155Z Bad Request: /api/account/ container-django-1 | 2022-09-03T18:17:09.261351802Z [03/Sep/2022 18:17:09] "POST /api/account/ HTTP/1.1" 400 40 -
Download and Install Software Application to client machine from hosted web application Django
I was working on scripts, I have added exe file to azure storage I have provided URL link on website, once local user click on that link, he should able to download and install application on his local machine. its was working fine when it was on development step because I was testing this on local webserver, once I hosted it was not working, It was downloading exe files on hosted virtual machine. if you guys have any idea or suggestions it would helps me alot, @login_required(login_url='/') def runcmd(request): import os import subprocess import getpass if request.method == 'POST': if 'app_url' in request.POST: app_dw_link = request.POST.get('app_url') app_obj = get_object_or_404(AppStore, id=int(app_dw_link)) url = app_obj.app_file.url usrname = getpass.getuser() messages.success(request, usrname) folder = 'Temp' dir_path = os.path.dirname(os.path.realpath(__file__)) messages.success(request, dir_path) destination = f"C:\\Users\\{usrname}\\AppData\\Local\\{folder}" if not os.path.exists(destination): os.makedirs(destination) destination = f'C:\\Users\\{usrname}\\AppData\\Local\\{folder}\\{app_obj.app_name}.exe' #add switches download = urlretrieve(url, destination) messages.success(request, download) subprocess.Popen([destination, '/Silent'], shell=True, stdout=subprocess.PIPE) else: destination = f'C:\\Users\\{usrname}\\AppData\\Local\\{folder}\\{app_obj.app_name}.exe' #add switches download = urlretrieve(url, destination) messages.success(request, download) subprocess.Popen([destination, '/Silent'], shell=True, stdout=subprocess.PIPE) messages.success(request, 'Download completed') return redirect("selfservice:it_store") -
How to solve .accepted_renderer not set on Response Error on POST Request, Django
got a problem when trying to call request using Postman, on POST request always get AssertionError at /v1/facility/33/court/ .accepted_renderer not set on Response Request Method: POST Request URL: On Get request other endpoints works fine. Django version - 3.2.15 Class that responsible for this endpoint already have APIView class class ItemAPIView( CSRFEnabledApiViewMixin, CreateAPIView, RetrieveUpdateDestroyAPIView): Even If I put APIView class as last nested class it not working. Who can help with this? what is wrong? Note: if I will doing curl request to such endpoint POST - error is the same -
OrderedDict in Django tests
I have such Django tests queryset = SomeModel.objects.all() response = self.client.get("some_url") serializer = SomeSerializer( instance=list(queryset[:10]), many=True ) self.assertEqual( serializer.data, response.json()["results"], ) And got such error E AssertionError: [OrderedDict([('uuid', 'e58fecc0-d559-41af[23258 chars]))])] != [{'uuid': 'e58fecc0-d559-41af-993b-9519309[17732 chars]0.0}] How can be OrderedDict be removed or transformed? -
Django convert CBV to json
I have this CBV class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' Im using _set to display all users data to staff. But I need to use the data for calculations, how can I convert this to json -
Is their any way to practice back-end? [closed]
How can I practice back-end? Is there any website where I can find front-end and attach back-end by my-self? -
DJANGO {{form.errors.title.as_text}} not working
a I have been watching a video which uses the following code to show errors. {% if form.errors %} <div class="alert alert-danger"> {{form.errors.title.as_text}} </div> {% endif %} But when I use it no errors show If I use: {% if form.errors %} <div class="alert alert-danger"> {% for error in form.errors %} <p>{{ error }}</p> {% endfor %} </div> {% endif %} I get a single word eg. 'email' but the whole error text does not display. It works fine on the video, Could anyone tell me what i am doing wrong? -
Django OperationalError when creating django_content_type table
With local MySQL was fine, but with the production is the error. After this error I see only the following tables in the database: auth_group, auth_group_permissions, auth_permission, django_content_type and django_migrations Operations to perform: Synchronize unmigrated apps: djoser, messages, rest_framework, staticfiles Apply all migrations: account, admin, auth, authtoken, blog, commands, contenttypes, faq, servers, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial...Traceback (most recent call last): File "C:\Program Files\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Program Files\Python310\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute return self.cursor.execute(query, args) File "C:\Program Files\Python310\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Program Files\Python310\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Program Files\Python310\lib\site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.OperationalError: (1142, "REFERENCES command denied to user 'test_user'@'22.161.40.219' for table 'django_content_type'")