Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"No errors found by the IDE" in problems tab
My PyCharm always shows: "No errors found by the IDE" I don't open power save mode. I don't know why. I even reinstalled PyCharm and shut down all plugins, however, my idea doesn't work well. I have search this problem on the internet but without finding any solution. -
I'm unable to run my django application, but nothing happens
I have a django project and I'm trying to run it with '''python manage.py runserver ''' but nothing really happens. I was working on it just 5 mins before this happens. Now, I'm unable to run anything, my project doesn't even show on the github desktop version... anyone has any ideas ? I've tried to check django, python, Running Processes, everything is okey. I'm not able to Run Django Shell neither.enter image description here -
how to show user in TokenSerializer dj-rest-auth
I'm trying to return UserSerializer after successful login through dj-rest-auth. I followed the steps that were told in After login the `rest-auth`, how to return more information? which has a similar issue, but it still doesn't show information about User after logging in. what i'm getting after successful login REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': 'blink.user.serializers.TokenSerializer', 'USER_DETAILS_SERIALIZER': 'blink.user.serializers.UserSerializer' } #settings.py class UserSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): exclude_fields = kwargs.pop('exclude_fields', None) super(UserSerializer, self).__init__(*args, **kwargs) if self.context and 'view' in self.context and self.context['view'].__class__.__name__ == 'UsersView': exclude_fields = ['subscription', 'avatar', 'file'] if exclude_fields: for field_name in exclude_fields: self.fields.pop(field_name) class Meta: fields = ('id', 'username', 'email', 'last_login', 'first_name', 'last_name') model = User class TokenSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TokenModel fields = '__all__' #User.serializers.py -
Post.objects.all() not working as i wished
Hey I am currently going through the Django tutorials and I am trying to display all of my Post objects in the python shell using from blog.models import Post Post.objects.all() my model is from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) contents = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title It should display ` [<Post: Blog 1>, <Post: Blog 2>] instead of [<Post: Post object (1)>, <Post: Post object (2)>] It just says "Post object" instead of the title. What is the reason why? I have been following the tutorial exactly and can't understand why it displays it like that. It's hard to organize all of the posts when it says "Post object" for all of them. I am using the latest version of python and django. -
ReactJS useParams for Django equivalent?
Django Example # urls.py url = [ path('password_reset/<uidb64>/<token>/', views.password_reset_confirm, name='password_reset_confirm'), ] # views.py def password_reset_confirm(request, id, token): print(id) print(token) pass How would I create an equivalent for ReactJS?? // App.js <Route path='password_reset/:uid/:token' element={<PasswordResetPage/>} /> // PasswordResetPage.js ???? -
Custom Django Transform with case statement for casting a string to either int or null
I'm trying to create a custom django lookup as_int so that you can easily compare and order the contents of text fields when they contain only a number, and treat them as NULL when they have the wrong format. For example: Comment.objects.filter(body__as_int__gt=5) # Should treat a comment with body="37" as 37 # Should treat a comment with body="abc" as NULL This is what I have so far: class AsIntTransform(Transform): lookup_name = "as_int" output_field = models.IntegerField() def as_sql(self, compiler, connection): case_expr = Case( When( Regex(self.lhs, r"^\d+$"), then=Cast(self.lhs, models.IntegerField()), ), default=Value(None), ) return case_expr.as_sql(compiler, connection) models.CharField.register_lookup(AsIntTransform) models.TextField.register_lookup(AsIntTransform) Trying to filter with the above code is throwing: field_list = name.split(LOOKUP_SEP) ^^^^^^^^^^ AttributeError: 'Col' object has no attribute 'split' It looks like the 'Col' its referring to here is self.lhs in the transform, but I'm not sure what I'm supposed to change to make this work? -
Django errorlist in form Select Valid Choice
The situation is as follows: I am building a form where I fetch data for some fields from an API. I have tried debugging in every possible way, but I cannot understand why the data is not being persisted in the database. Whenever I click submit, I get the following error: <ul class="errorlist"><li>municipio<ul class="errorlist"><li>Select a valid choice. Afuá is not one of the available choices.</li></ul></li></ul> If anyone can help me understand why this error is occurring, I would appreciate it. To provide context, I am sharing the three main files. My models.py: # apps/parametrizacao/models.py from django.db import models class RegraFiscal(models.Model): REGIME_TRIBUTARIO_CHOICES = [ ('Simples Nacional', 'Simples Nacional'), ('Lucro Presumido', 'Lucro Presumido'), ('Lucro Real', 'Lucro Real'), ('Misto', 'Misto') ] PORTE_CHOICES = [ ('ME', 'Microempresa (ME)'), ('EPP', 'Empresa de Pequeno Porte (EPP)'), ('Demais', 'Demais') ] nome = models.CharField(max_length=255, default='Padrão') regime_tributario = models.CharField(max_length=20, choices=REGIME_TRIBUTARIO_CHOICES) porte = models.CharField(max_length=10, choices=PORTE_CHOICES, default='ME') aliquota_csll = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_irpj = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_pis = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_cofins = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_icms = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_ipi = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_iss = models.DecimalField(max_digits=5, decimal_places=2, default=0) aliquota_inss = models.DecimalField(max_digits=5, decimal_places=2, default=0) def __str__(self): return f"{self.nome} - {self.porte}" class Empresa(models.Model): nome = models.CharField(max_length=255) cnpj = models.CharField(max_length=18) … -
How to debug HTTP 400 Bad Request errors in django?
I have an app with React frontend and Django backend. I'm trying to make a POST request from my react client but I get "Bad Request" error. I checked my request url and it matches with my api url. Therefore I believe the error has to do with the data I pass. How can I debug this error to learn more about it? Here are the necessary code parts: models.py class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="products") def __str__(self): return self.name class BatchChain(models.Model): created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) is_active = models.BooleanField() class Batch(models.Model): # This is the model I'm trying to POST product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="batches_from_products") chain = models.ForeignKey(BatchChain, on_delete=models.CASCADE) serializers.py class BatchPostSerializer(serializers.ModelSerializer): class Meta: model = Batch fields = ["id", "product", "chain"] views.py class BatchListCreate(generics.ListCreateAPIView): serializer_class = BatchPostSerializer permission_classes = [IsAuthenticated] def get_queryset(self): user = self.request.user batches = Batch.objects.filter(product__owner=user) return Batch.objects.filter(chain__in=batches.values_list("chain")) def perform_create(self, serializer): if serializer.is_valid() is False: return Response({'Message': 'Serializer is not valid'}, status=status.HTTP_400_BAD_REQUEST) if Batch.objects.filter(chain=self.request.data["chain"]).exists(): return Response({'Message': 'You can not create a second batch with same chain'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) serializer.save() api/urls.py ... path("batches/", views.BatchListCreate.as_view(), name="batch-list-create"), # all calls to /api/ are directed to this folder ... … -
Validation in DR(Django)
I'm trying create customs validations to my serialiazer but Django just ignore them and return me DRF default errors. {'message': 'Erro ao criar camião', 'data': {'plate': [ErrorDetail(string='This field may not be null.', code='null')]}} That's the answer i get view.py View that allow companies to add their trucks class TruckView(generics.GenericAPIView): permission_classes = [IsAuthenticated, IsCompanyAuthenticated] queryset = Trucks.objects.all() serializer_class = TruckSerializer def post(self, request): company = get_object_or_404(Company, user=request.user) request.data['company'] = company.id request.data['on_service'] = False serializer = TruckSerializer(data=request.data) if serializer.is_valid(raise_exception=False): serializer.save() return Response( { 'message': "Camião criado com sucesso", 'data': serializer.data }, status=status.HTTP_201_CREATED ) else: print(serializer.data) return Response( { 'message': "Erro ao criar camião", 'data': serializer.errors }, status=status.HTTP_400_BAD_REQUEST ) Serializer.py class TruckSerializer(serializers.ModelSerializer): company = serializers.PrimaryKeyRelatedField(queryset=Company.objects.all()) types = TypesSerializer(many=True, read_only=True) class Meta: model = Trucks fields = '__all__' def validate(self, attrs): return super().validate(attrs) def validate_required_field(self, value, error_message): if not value or value in [None, "", " ", []]: raise ValidationError(error_message) return value def validate_plate(self, value): return self.validate_required_field(value, "Matricula inválida") def validate_types(self, value): for type_id in value: try: # Get the Types instance by ID Types.objects.get(id=type_id['id']) except Types.DoesNotExist: # Handle the case where the type ID is not valid raise serializers.ValidationError("Tipo de veículo inválido") return self.validate_required_field(value, "Introduza tipo válidos para este camião") def validate_policy_nr(self, value): … -
Django app deployed to under the url subdirectoly
In my server,django and nginx is deployed on ECS fargate and connected to loadbalancer, but URL is transferd by Akamai https://www.example.com/company/playground/* -> https://amazonloadbalancer/* However, there comes a few problem,such as Problem 1 static Access https://www.exmplae.com/company/playground/top will be jumped to https://amazonloadbalancer/top correctly, but static file url will be https://www.exmplae.com/static/main.js while the real file is located https://www.example.com/company/playground/static/main.js /company/playground is omitted so, can not be reached. Problem 2 admin transfered accesing https://www.example.com/company/playground/admin the url is transferred by django to https://www.example.com/admin/login/?next=/admin/ /company/playground is omitted again, so can not be reached. Is there any good setting for this purpose?? -
Django Inline Formset data not saving
I have created an inline formset which works exactly as I planned on the frontend side- However I can't seem to access any of the data- it seems like the form isn't saving the data? Here in the views.py you can see where it should be saving: def formset_variantingredients_valid(self, formset): variantingredients = formset.save(commit=False) for variantingredient in variantingredients: variantingredient.recipe = self.object variantingredient.save() def formset_images_valid(self, formset): images = formset.save(commit=False) for image in images: image.recipe = self.object image.save() In the admin, in my saved form I can only see the standard fields that have saved and not either of these two inline formsets- Is my issue in the saving of the form itself or am I just not accessing the data correctly? Many Thanks for the help! -
Is the batch processing speed of Python slower than that of Java?
I am working on migrating a function implemented in Java Spring Boot to Python Django. I encountered an issue while migrating a function that retrieves a list of keywords through a select query and updates these keywords using an update query. Specifically, updating 450 rows takes around 0.1 seconds in Java, but it takes 2 seconds in Python. Below are the methods I used to measure the time and the Java and Python code. Measurement method // java long startTime = System.nanoTime(); // Execute the update long endTime = System.nanoTime(); double duration = (endTime - startTime) / 1_000_000_000.0;; String formattedDuration = String.format("%.2f seconds", duration); log.info("processing_time: {}", formattedDuration); // python start_time = time.perf_counter() // Execute the update end_time = time.perf_counter() processing_time = end_time - start_time processing_time_formatted = f"{processing_time:.2f}" logger.info(f"processing_time: {processing_time_formatted} seconds") Logic Java // application.yml spring: datasource: driver-class-name: org.mariadb.jdbc.Driver url: jdbc:mariadb:... username: ... password: ... jpa: hibernate: ddl-auto: none properties: hibernate: show_sql: true use_sql_comments: true format_sql: true dialect : org.hibernate.dialect.MariaDBDialect open-in-view: false sql: init: mode: never // service public void updateUserIntrKwd(String indvNum) { // 2s List<IntrKwdDto> kwdList = intrKwdMapper.selectIntrKwdList(indvNum); // 0.001s DatesAndMaxFrequency datesAndMaxFrequency = getDatesAndMaxFrequency(kwdList); // 0.1s intrKwdMapper.updateUserIntrKwd(kwdList, datesAndMaxFrequency); } // Mapper <update id="updateUserIntrKwd" parameterType="map"> <foreach collection="kwdList" item="item" separator=";"> ... Python … -
AJAX Filtering with jQuery and Django Not Updating Product List
I am working on a project where I need to filter products based on selected categories and vendors using AJAX with jQuery and Django. However, despite no errors in the console, the product list is not updating as expected. Here are the relevant parts of my code: JavaScript: $(document).ready(function(){ $(".filter-checkbox").on("click",function(){ console.log("A checkbox have benn clicked"); let filter_object = {} $(".filter-checkbox").each(function(){ let filter_value = $(this).val() let filter_key = $(this).data("filter") // console.log("Filter value is:", filter_value); // console.log("Filter key is:", filter_key); filter_object[filter_key] = Array.from(document.querySelectorAll('input[data-filter = '+ filter_key +']:checked')).map(function(element){ return element.value }) }) console.log("Filter object is:", filter_object) $.ajax({ url: '/filter-product', data: filter_object, dataType: 'json', beforeSend: function(){ console.log("Trying to filter Product...") }, success: function(response){ console.log(response); console.log("Data filtered successfully..."); $("#filtered-product").html(response.data) } }) }) }) Django Views: def filter_product(request): categories = request.GET.getlist("category[]") vendors = request.GET.getlist("vendor[]") products = Product.objects.filter(product_status="published").order_by("-id").distinct() if len(categories) > 0: products = products.filter(cagtegory__id__in = categories).distinct() if len(vendors) > 0: products = products.filter(vendor__id__in = vendors).distinct() context = { "products":products } data = render_to_string("core/async/product-list.html",context) return JsonResponse({"data":data}) Template: <div class="showcase" id="filtered-product"> {% for p in products %} <div class="showcase-banner"> <img src="{{p.image.url}}" width="300" class="product-img default"> <img src="{{p.image.url}}" width="300" class="product-img hover"> <p class="showcase-badge">15%</p> <div class="showcase-actions"> <button class="btn-action"> <ion-icon name="heart-outline"></ion-icon> </button> <button class="btn-action"> <ion-icon name="eye-outline"></ion-icon> </button> <button class="btn-action"> <ion-icon name="repeat-outline"></ion-icon> </button> … -
Payment Gateway Integration with Django
I'm integrating payment gateway APIs in my application (Django). I have written a class PaymentGateway that provides all the methods for all payment related utility. The __init__ initialises the payment gateway client as self.client so that it's available across all methods. But, I need help in making a decision on how to use it. Is it OK if I instantiate and use the payment gateway object across the program, whenever I need it? OR Should I maintain a single instance of it across the whole application? Need help in understanding what could be pros and cons or any other suggestion so that I can make this decision. My current code looks something like below right now: class PaymentGateway: def __init__(self): self.client = PG(api_key="api_key") def create_intent(self, user): return self.client.intents.create(customer_id=user.email) def get_user_id(email): return self.client.users.retrieve(customer_id=email) class MyView(GenericAPIView): def get(self, request): pg_instance = PaymentGateway() intent = pg_instance.create(request.user) return Response({"user_id": get_user_id(request.user), "intent": intent}) # Somewhere in utils.py def get_user_id(user): pg = PaymentGateway() return pg.get_user_id(user.email) -
runser can't serve media if MEDIA_URL is within STATIC_URL, even different settting
In my server,django and nginx is deployed on ECS fargate and connected to loadbalancer, but URL is transferd by Akamai https://www.exmplae.com/company/playground/* -> https://amazonloadbalancer/* So,https://www.exmplae.com/company/playground/ is the url in browser. I have this error django on server (DEBUG=TRUE) runser can't serve media if MEDIA_URL is within STATIC_URL However in this case I have only static setting, no media settings. STATIC_URL = "static/" STATIC_ROOT = "static/" So I just added the media setting in settings.py = STATIC_URL = "static/" STATIC_ROOT = "static/" MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' However , strangely the same error runser can't serve media if MEDIA_URL is within STATIC_URL occurs. How can I fix this? -
Handle Http 302 response on Django view and Javascript async function
For strict security, how can I implement redirect on Django view in response to a JS async call that only updates a div InnerHTML? That is the first preference. I tried JS client-side redirect in multiple ways. It didn't work either. JS keeps rendering home page as InnerHTML in the div. When user's session is ended, server returns 302 Location: /. To take the user to the home page. View @csrf_protect def edit_form(request): if not request.user.is_authenticated: return redirect('/') form = userForm() return render(request, 'edit_form.html', {'form': form}) JS async function fetch_form() { try { const response = await fetch('http://192.168.1.10:8000/edit_form',{ method: 'GET', }); if (!response.ok) { //redirect didn't work const redirectUrl = response.headers.get('Location'); console.log(redirectUrl); window.location.href = redirectUrl; //throw new Error('Network response was not ok ' + response.statusText); } else if (response.status === 302) { //redirect didn't work const redirectUrl = response.headers.get('Location'); console.log(redirectUrl); window.location.href = redirectUrl; } document.getElementById('firstModal').innerHTML = data; } catch (error) { console. Error('There has been a problem with your fetch operation:', error); } }; async function fetch_form() { try { const response = await fetch('http://192.168.1.10:8000/edit_form',{ method: 'GET', }); if (!response.ok){ throw new Error('Network response was not ok ' + response.statusText); } document.getElementById('firstModal').innerHTML = data; } catch (error) { if (error.response.status … -
Django Auto Assigning Author to the user creating the post
I am having an issue with my Author being auto-assigned, it was previously working but has stopped working since I added some inline formsets- Here is my model: class Recipe(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) serving = models.PositiveIntegerField(default=1) temperature = models.PositiveIntegerField(default=1) prep_time = models.PositiveIntegerField(default=1) cook_time = models.PositiveIntegerField(default=1) ##tags = models.ManyToManyField('Tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return self.title Unsure if maybe some of my other code could be overriding this? This is my form: class RecipeForm(forms.ModelForm): class Meta: model = Recipe exclude = ['author', 'created_at', 'updated_at'] def __init__(self, *args, **kwargs): super(RecipeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('title'), Field('description'), Field('temperature'), Field('serving'), Field('prep_time'), Field('cook_time'), ) ) If I set blank=True, null=True in the model, it allows the form to go through but with no author associated- Even any indication to what could be causing my issue would be hugely helpful! Many Thanks -
binascii.Error: Invalid base64-encoded string: number of data characters (41) cannot be 1 more than a multiple of 4
I'm trying to use py-vapid, pywebpush, and django-push-notifications to send notifications via Webpush. When I try to send a test notification from the django admin website, I get this traceback log in the console: | Internal Server Error: /djangoadmin/push_notifications/webpushdevice/ | Traceback (most recent call last): | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 518, in thread_handler | raise exc_info[1] | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 38, in inner | response = await get_response(request) | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 233, in _get_response_async | response = await wrapped_callback(request, *callback_args, **callback_kwargs) | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 468, in __call__ | ret = await asyncio.shield(exec_coro) | File "/usr/local/lib/python3.8/site-packages/asgiref/current_thread_executor.py", line 40, in run | result = self.fn(*self.args, **self.kwargs) | File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 522, in thread_handler | return func(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper | return self.admin_site.admin_view(view)(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 232, in inner | return view(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper | return bound_method(*args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view | response = view_func(request, *args, **kwargs) | File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1723, in changelist_view | response = self.response_action(request, … -
COUNT(DISTINCT <col>) without GROUP BY
In Django, Count("col", distinct=True) can be used to perform COUNT(DISTINCT col) but it automatically adds a GROUP BY so is there a way to prevent that from happening so the distinct count of all rows that match the WHERE can be received? -
Why we should install postgresql in the Django container?
Why is necessary install postgresql as dependency in a Django backend container? the Django app is intended to connect to a PostgreSQL DB running in a separate container. I have the next Dockerfile: # pull official base image FROM python:3.12.4-slim-bookworm # set working directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # new # install system dependencies RUN apt-get update \ && apt-get -y install gcc postgresql \ && apt-get clean # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add app COPY . . And I have the next docker-compose.yml file: services: movies: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8009:8000 env_file: - ./app/.env.dev depends_on: - movies-db movies-db: image: postgres:16 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=movies - POSTGRES_PASSWORD=movies - POSTGRES_DB=movies_dev volumes: postgres_data: This is the case in the course "Test-Driven Development with Django, Django REST Framework, and Docker" by testdriven.io Thanks in advance. -
Better directory structure for Django projects with git perspective
I'm new to Django and trying to decide between two different directory structures. I want to understand the implications of each structure from git perspective and also which one is more favorable in the industry or common practice. Method 1 . ├── .git ├── mysite │ ├── manage.py │ └── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── README.md Method 2 . ├── .git ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── README.md created a few projects with both the structures and want to stick to one or atleast have a favourite. -
Incorrect Redirection to Login Page from Profile and Logout Links After User Login
Context: I’m working on a Django project where I have implemented user authentication with profile and logout functionality. The issue I'm encountering is that when I try to access the profile or logout links from the navbar, it redirects me to the login page instead of navigating to the user's profile or performing logout. Profile Link: Should navigate to the user's profile page if the user is logged in. Logout Link: Should log out the user and redirect to the homepage. Current Setup: Templates (base.html): {% if logged_in %} <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ customer_name }} </a> <ul class="dropdown-menu" aria-labelledby="userDropdown"> <li><a class="dropdown-item" href="{% url 'profile' %}?email={{ customer_email }}">Profile</a></li> <li><a class="dropdown-item" href="{% url 'logout' %}">Logout</a></li> </ul> {% else %} <a class="nav-link" href="{% url 'login' %}">Login</a> {% endif %} Views: from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import costumer @login_required def profile_view(request): email = request.GET.get('email') if email: try: user = costumer.objects.get(email=email) if user.id == request.session.get('customer_id'): return render(request, 'profile.html', {'user': user}) else: return redirect('index') except costumer.DoesNotExist: return redirect('index') else: return redirect('index') def logout_view(request): request.session.flush() auth_logout(request) return redirect('index') def login_view(request): if request.method … -
How to create a node in neo4j using Django
I am working on a web app. For the backend I chose Django and as a database I would like to use a graph database so I chose neo4j. There is a python library neomodel to work with neo4j and a specific library django_neomodel to incorporate neomodel with Django. I am able to use Django to with neo4j to retrieve data from a node in the database, however I cannot get it to create a node in the database. Here is my a part of my settings.py file: INSTALLED_APPS = [ ... 'django_neomodel', 'neomodel', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'create', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } NEOMODEL_NEO4J_BOLT_URL = 'bolt://neo4j:password@localhost:7687' and here the views.py from create class RegisterView(View): """ This view handles POST requests to create a new user in the database. """ def post(self, request): new_node = myNode(XXX=request.POST['XXX'], YYY=request.POST['YYY'], ZZZ=request.POST['ZZZ']) new_nodesave() Here the myNode class: from neomodel import (StructuredNode, StringProperty, UniqueIdProperty) from .event import Event class myNode(StructuredNode): # Properties uid = UniqueIdProperty() XXX = StringProperty(required=True, unique_index=True) YYY = StringProperty(required=True) ZZZ = StringProperty(required=True) The error I get is: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I asked chatGPT and … -
Concurrency Control Mechanism For Dataframe Processing In Django WebApp
I have django webapp where processing data directly on pandas dataframe without using django model. now, i want to make this operations concurrency control for multiple processing requests simultaneously. suggest me best approach for it. i am aware about atomic transactions in django but it is not useful for the pandas processing. -
Invalid block tag on line 1: 'include'. Did you forget to register or load this tag?
During a Django tutorial I've got an issue with the index.html file. I can't handle this exception: Invalid block tag on line 14: 'else'. Did you forget to register or load this tag? I really don't understand why it doesn't recognize "include". My index.html is like this: <h1>{{ title }}</h1> {% include 'alphas/includes/nav.html' %} <ul> {% for item in posts %} {% if item.is_published %} <li> <h2>{{ item.title }}</h2> <p>{{ item.content }}</p> <p><a href="{% url 'post' item.id %}">Читать пост</a></p> {% if not forloop.last%} <hr> {% endif %} </li> {% endif %} {% endfor %} </ul>