Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I connect my React frontend with my Django backend?
I've been trying to connect my React frontend with Django backend server to complete development of a sign up page. I'm trying to test a simple GET HTTP request to my server which I know is functioning correctly. However every time the code compiles I get these errors in the console instead of a response. For reference here are some photos. My Signup page JSX Errors in the console I looked into the errors and found they were Axios Errors. Axios is the HTTP calls library I am using but I am unsure why these errors are being thrown. I have attempted to configure CORS headers in multiple ways as well but with no success. I think I am either declaring it incorrectly. Ways I've tried to Configure my CORS headers: Using the axios properties e.g. Method 1 I found this next fix on this site Here is how I implemented it in my index.js file Method 2 -
Edit multiple tables in database in django
I have a page with the user can edit the information in database, and this page have more than one table (InformacaoFamilia, Imagens). The images i can delete and insert. But when click in confirm the fields with a legend dont save in database. In this page have a form with all fields in InformacaoFamilia models, have a image and a textarea with respectivily legend, have all images and the user can select what goes to delete, and for a add news images. but the legend dont saving in database. update_facthseets.html <article> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <p class="form-group"> {% if field.errors %} <div class="">{{ field.errors.as_text }}</div> {% endif %} <label class="" for="{{ field.id_for_label }}"> {{ field.label }}: </label> {{ field }} </p> {% endfor %} <hr> Editar Legenda {% for image in images %} <div class="imagem"> <p> <label for="edit-legend-{{ image.id }}"> <img src="{{ image.imagens.url }}" alt="{{ image.legenda }}"> Legenda: <textarea type="text" name="imagens-{{ image.id }}-legenda" id="edit-legend-{{ image.id }}" value="{{ image.legenda }}">{{ image.legenda }}</textarea> </label> </p> </div> {% endfor %} Excluir Imagens {% for image in images %} <div class="imagem"> <!-- <p class="paragrafo-{{ image.id }}"> --> <input type="checkbox" name="delete_image" value="{{ image.id }}" id="delete-image-{{ image.id … -
How to reference/mess with a model in a JS file (Django)
So I have a model Profile with a field level (IntegerField) upon completion I would like to add a number to that field but I'm not sure how to reference it in the JS file. Can I edit a models field in a JS file? I'm new to Django and couldn't find anything in the ''documentation''. class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) rpg_class = models.CharField(max_length=100, default='Warrior') level = models.IntegerField(default=1) def __str__(self): return str(self.user) Views.py: profile = self.get_object() context['level'] = profile.level return context for now I just want to know if I can do something like this in hte JS file model_name += 1; but I cant figure out how to reference it -
Custom permission class not returning custom permission denied message - DRF
I have a custom permission class where I want a custom permission message to be returned. But it is returning the default permission denied message. Below is the custom permission class that I have written: class IsAuthenticatedAndIsLr(BasePermission): def has_permission(self, request, view): message = "user is not LR" return request.user.is_authenticated and request.user.regd_as == "LR" and here is how I am using it on the api: @api_view(['POST']) @permission_classes([IsAuthenticatedAndIsLr]) def create_profile(request): ''' this api creates profile for users based on their choosen category. ''' data = request.data model_dict = { 'IND' } try: ... return Response({'message': f'{request.user} isLR'}, status= status.HTTP_201_CREATED) except Exception as e: return Response({"message": str(e)}, status= status.HTTP_500_INTERNAL_SERVER_ERROR) I have followed the docs method to raise a custom message but for some reason it is not working. Please suggest to me what is the cause of this problem. -
Gitlab CI/CD and Azure deploying Django
Am trying to deploy Django code to Webapp using gitlab CI, here's the .gitlab-ci.yml ; image: name: docker/compose:1.25.4 entrypoint: [""] services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 stages: - deploy deploy-azure-stag: stage: deploy image: mcr.microsoft.com/azure-cli script: - echo "Logging into Azure" - az login --service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET --tenant $AZURE_TENANT_ID - echo "Deploying to Azure App Service" - az webapp up --name $AZURE_APP_NAME However am getting this error, how best can I continuously deploy my Django code . Error am getting. Deploying to Azure App Service $ az webapp up --name $AZURE_APP_NAME WARNING: Webapp 'app_name' already exists. The command will deploy contents to the existing app. ERROR: Unable to retrieve details of the existing app 'app_name'. Please check that the app is a part of the current subscription if updating an existing app. If creating a new app, app names must be globally unique. Please try a more unique name or leave unspecified to receive a randomly generated name. Cleaning up project directory and file based variables 00:01 ERROR: Job failed: exit code 1 -
How can i shuffle my questions in Django views?
I have got a project with quiz and it needed to make random questions. I try like this: @login_required def test(request, test_id): test_set = get_object_or_404(TestSet, id=test_id) questions = test_set.question_set.all().order_by('?') But when i take an a next question it may be repeated. How can i fix it? Also i have a button like "repeat" -
Save() method does not save my form to database
Coding a simple form to add articles to website. Failed to add any information from form to database. My models.py from django.db import models class Articles(models.Model): title = models.CharField('Name', max_length=50) anons = models.CharField('announcement', max_length=250) full_text = models.TextField('Article') def __str__(self): return self.title class Meta(): verbose_name = 'news' my forms.py from .models import Articles from django.forms import ModelForm, TextInput, Textarea class ArticlesForm(ModelForm): class Meta: model = Articles fields = ['title', 'anons', 'full_text'] widgets = { 'title': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Header' }), 'anons': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Announcement' }), 'full_text': Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Text' }), } my views.py from django.shortcuts import render, redirect from .models import Articles from .forms import ArticlesForm def news(request): news = Articles.objects.all() #[:2] - срез записей return render(request, 'news_templates/news.html', {'news': news}) def create(request): error = '' if request.method == 'POST': form = ArticlesForm(request.POST) if form.is_valid(): form.save return redirect('./') else: error = "Wrong format" form = ArticlesForm() data = { 'form': form, 'error': error } return render(request, 'news_templates/create.html', data) template for page {% extends 'main/layout.html' %} {% block title %}Create article {% endblock %} {% block content %} <main class="features"> <h1>Add an article</h1> <form method='post'> {% csrf_token %} {{ form.title }}<br> {{ form.anons }}<br> {{ form.full_text }}<br> <button … -
No build() and create() vs build() vs create() in Factory Boy
I created UserFactory class in factories.py as shown below. I use pytest-django and pytest-factoryboy in Django: # "factories.py" import factory from django.contrib.auth.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = "John" Then, I registered UserFactory class in conftest.py as shown below: # "conftest.py" import pytest from pytest_factoryboy import register from tests.factories import UserFactory register(UserFactory) Then, I created test_user() which prints username with user_factory and user_factory.build() and user_factory.create() in test_ex1.py as shown below: # "test_ex1.py" import pytest from django.contrib.auth.models import User def test_user(db, user_factory): print(user_factory.username) # Here print(user_factory.build().username) # Here print(user_factory.create().username) # Here assert True Then, I got 3 John's as shown below: $ pytest -q -rP . [100%] =============== PASSES ================ ____________ test_new_user ____________ -------- Captured stdout call --------- John John John 1 passed in 0.55s My questions: What is the difference between user_factory, user_factory.build() and user_factory.create() in Factory Boy? When should I use user_factory, user_factory.build() and user_factory.create() in Factory Boy? -
Creating internet function in django webapp
I have been tinkering around with Django for about a year now and I have created a little webapp that I can put in a VPC or remote server, currently the vpn uses a full tunnel, not split. So the users have to use the internet and dns provided through the VPC. Currently the webapp has login, auth, sessions via django-redis, file transfer, chat and dm (functions like iMessage), and in admin all of the permissions for these are setup and handled. The one function I'm having a hard time with is: User requires permissions for external internet access (http/https) If user has permissions, internet access doesn't enable until user also clicks the 'Internet' button to activate it. I had come up with this for the django bit: @login_required @permission_required('accounts.proxy_access', raise_exception=True) def proxy(request): try: # Get the remote IP address of the incoming request remote_ip = request.META['REMOTE_ADDR'] # Add iptables rule to allow traffic from the remote IP subprocess.run(['iptables', '-A', 'OUTPUT', '-d', remote_ip, '-j', 'ACCEPT']) messages.success(request, 'Proxy connected. You may now open a new tab and browse the web normally.') except: messages.error(request, 'Proxy failed. Please contact your administrator.') return redirect('home') can get the incoming IP from the request metadata. Then … -
Open Graph meta tags not fully recognized
I have a Django application hosted on Heroku, which provides event details pages. Each of these pages has Open Graph meta tags set up to enable rich previews when the URLs are shared on platforms like Facebook and iMessage. However, while Facebook is able to recognize and display all the information correctly (title, description, and image), iMessage is showing only the title. Interestingly, the description and the image are completely ignored by iMessage. Here's the template with the relevant Open Graph meta tags: <head> <meta property="og:title" content="{{ name }}"> <meta property="og:description" content="{{ date }}"> <meta property="og:image" content="{{ posterURL }}"> <meta property="og:url" content="{{ request.build_absolute_uri }}"> <meta property="og:type" content="website"> Additional details: The URL for the image is from Firebase Storage, and is URL-encoded. However, it works fine on Facebook and directly in browsers. When testing the link on Chrome, the debugger shows the og:description correctly, but iMessage ignores it. The URL was provided in the format: https://firebasestorage.googleapis.com:443/v0/b/moonlight-f2113.appspot.com/o/... and works when opened directly. I've tried decoding the URL using JS unquote but it results in a non-working link. Any ideas on why iMessage would ignore both the og:description and og:image while Facebook doesn't, and potential fixes? Also note, I also tried doing "og:image:secure_url" … -
Django DateTimeField only recording Date
I have a model with two DateTimeFields. For some reason, only the dates are being entered into the database - not the times as well. So far I haven't been able to figure out the problem. The model: from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils import timezone from accounts.models import CustomUser class WorkTime(models.Model): worker = models.ForeignKey(CustomUser, null=True, on_delete=models.CASCADE) clock_in = models.DateTimeField(null=True) clock_out = models.DateTimeField(null=True) def save(self, *args, **kwargs): if self.id: # Object is being updated self.clock_out = timezone.now() super(WorkTime, self).save(*args, **kwargs) @receiver(pre_save, sender=WorkTime) def set_clock_in(sender, instance, **kwargs): if not instance.id: # Object is being created instance.clock_in = timezone.now() The view: from django.shortcuts import render from django.views.generic import DetailView, CreateView, UpdateView from django.utils import timezone from django.urls import reverse_lazy from .models import WorkTime from django.contrib.auth.mixins import LoginRequiredMixin class WorkTimeCreateView(LoginRequiredMixin, CreateView): model = WorkTime fields = [] # Remove 'worker' from fields as it will be auto-detected template_name = 'timeclock/worktime_form.html' def form_valid(self, form): # Automatically set the worker to the currently logged-in user form.instance.worker = self.request.user # Set the clock_in time form.instance.clock_in = timezone.now() return super().form_valid(form) class WorkTimeUpdateView(LoginRequiredMixin, UpdateView): model = WorkTime fields = ['worker'] template_name = 'worktime_update' # Use a custom template for update … -
Django serializer - Aggregate a function
Goal: Get the total of number of days for a trip Each trip can have multiple legs of varying duration. I have calculated the duration of each leg using a function. I now need to calculate the total sum of all these legs for any given trip. Models class Trip(models.Model): name = models.CharField(max_length=140) class Leg(models.Model): trip_name = models.ForeignKey(Trip, on_delete=models.PROTECT) depature_date = models.DateField() arrival_date = models.DateField() def total_days(self): return ((self.arrival_date - self.depature_date).days) + 1 Serializers class Trip_Serializer(serializers.ModelSerializer): total_no_of_days = serializers.SerializerMethodField() class Meta: model = Trip fields = ['id', 'name', 'total_no_of_days'] def get_total_no_of_days(self, instance): return Leg.objects.filter(trip_name=instance.id).aggregate(Sum('total_days')) class Leg_Full_Serializer(serializers.ModelSerializer): class Meta: model = Leg fields = [ 'id', 'trip_name', 'depature_date', 'arrival_date' , 'total_days' ] The issue I am having is I don't know how to use the total_days function in the Trip Serializer. -
DRF - Can't login in APIView
I have this serializer for login: class UserLoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() And an APIView: from django.contrib.auth import authenticate, login class UserLoginAPIView(APIView): def post(self, request): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): username = serializer.data.get("username", None) password = serializer.data.get("password", None) user = authenticate(request, email=username, password=password) if user: login(request, user) return Response(serializer.data) return Response(serializer.error_messages) It authenticates users with the given email and password correctly but it the login(request, user) doesn't seem to work since afterwards, I check and I'm still not logged in. -
Is there a way in Django to specify a starting/first test?
My tests take a long time to run, and many times fixing one test often fixes multiple tests, so I often use --failfast to fix tests one by one in the order in which they error out. I fix a test, then rerun to find the next failure that wasn't due to the same root cause as the one I just fixed. The problem is that the tests take a long time to run and I have to wait through all the tests that I already know will pass. *I'm aware that code changes to fix one test could break a previously run/successful test, but I'd prefer to handle that in a second run. What I would like to do is specify a "starting test" so that I only run the tests from the previous failure forward. I don't see a way to do that using python manage.py test. Is there a trick to get it to not test previously run tests and just pick up where it left off? -
Django dev server does not start if noreload is not set
I'm encountering an issue when attempting to start the Django development server with runserver_plus from django-extensions When I initiate it with the following command: python backoffice/manage.py runserver_plus 0.0.0.0:8000 --noreload It starts successfully without any problems. However, if I use the following command instead python backoffice/manage.py runserver_plus 0.0.0.0:8000 Notice that if I not pass the --noreload flag, it returns the following error: backoffice/manage.py: [Errno 2] No such file or directory The command is being executed in the same place so it does not make sense why is not finding the manage file. Why does it only work when I include --noreload? Is there a way to make it work? I would like to use the reload capability to save time in development process. Thank you! -
Why am I getting Post method error while submitting form in Django?
This is the error which i m getting when trying to click on the submit button: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/contact/ Using the URLconf defined in career.urls, Django tried these URL patterns, in this order: admin/ myapp/ signup /contact ^media/(?P\<path\>.\*)$ The current path, contact/, didn’t match any of these. I am attaching my file code below: Contact.html: <div class="container my-3"> <h1>Contact Admin</h1> <form method="post" action="/contact"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" aria-describedby="name"> </div> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" name="email" id="email" aria- describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="phone">Phone Number</label> <input type="phone" class="form-control" name="phone" id="phone"> </div> <div class="form-group"> <label for="content">How may we help you?</label> <textarea class="form-control" name="content" id="content" cols="30" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> views.py: def contact(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] content = request.POST['content'] print(name, email, phone, content) contact.save() return render(request, "myapp/contact.html") models.py: class Contact(models.Model): sno = models.AutoField(primary_key=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=10) email = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.name admin.py: from django.contrib import admin from .models import\* admin.site.register(Careers) … -
Problem Configuring Static in OpenLiteSpeed with Django Project (www.menuweb.cl)
The problem. traditional-italian-food-world-tourism-day.jpg:1 - Failed to load resource: the server responded with a status of 404 /#:1 - Refused to apply style from 'https://menuweb.cl/python/static/main/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I'm trying to set up a Django project on OpenLiteSpeed and am facing some challenges in properly configuring the static files.Based on the user manual's recommendations, I've set STATIC_URL and STATIC_ROOT in my settings.py as follows: STATIC_URL = '/python/static/' STATIC_ROOT = '/usr/local/lsws/Example/html/growpyme/static' Here's my directory structure: /usr/local/lsws/Example/html/ growpyme/ staticfiles/ main/ static/ carta/ static/ growpyme/ static/ If anyone has previously configured Django static files in OpenLiteSpeed and can offer guidance, it would be greatly appreciated. Thank you in advance! <!DOCTYPE html> <html lang="es"> <head> {% load static %} <meta charset="UTF-8"> <title>App Menu Web</title> <!-- Incluir Bootstrap CSS y JS usando un CDN para mejor compatibilidad --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Vincula tus hojas de estilo CSS --> <link rel="stylesheet" type="text/css" href="{% static 'main/home.css' %}"> <!-- Vincula tus librerías o frameworks JS --> <script src="{% static 'jquery.js' %}"></script> <link href="https://fonts.googleapis.com/css2?f...0&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet"> </head> -
I can't install ebcli with Python 3.11.4 | AttributeError: cython_sources | Getting requirements to build wheel did not run successfully
When I try to install ebcli using Python 3.11.4 (inside a venv, as per the official instructions)I get an error and I just can't get around it. If I try to install ebcli using Python 3.8.10(again inside a venv, but this time the 3.8.10 version), it does work. The error looks like this: File "/tmp/pip-build-env-yn_umd7x/overlay/lib/python3.11/site-packages/setuptools/_distutils/command/sdist.py", line 336, in _add_defaults_ext self.filelist.extend(build_ext.get_source_files()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<string>", line 201, in get_source_files File "/tmp/pip-build-env-yn_umd7x/overlay/lib/python3.11/site-packages/setuptools/_distutils/cmd.py", line 107, in __getattr__ raise AttributeError(attr) AttributeError: cython_sources [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. I already followed the troubleshooting recommendations, which consists on installing dependencies, and it didn't have any effect. I already googled for this specific issue and I can't find a solution. I did find this issue containing AttributeError: cython_sources which might be related, but I don't know what action to take from there. -
Add prefix to router while still showing it in API root view
To simplify my question, I have a Django project with two apps: devices and pins with the following urls.py: # devices/urls.py router = routers.DefaultRouter() router.register(r'relays', api_views.RelayViewSet) router.register(r'ultrasonic_sensors', api_views.UltrasonicSensorViewSet) router.register(r'contact_sensors', api_views.ContactSensorViewSet) ... urlpatterns = [ path('', include(router.urls)), ] # pins/urls.py router = routers.DefaultRouter() router.register(r'pins', api_views.PinViewSet) urlpatterns = [ path('', include(router.urls)), ] and the main project's urls.py looks like this: from devices.urls import router as devices_router from pins.urls import router as pins_router urlpatterns = [ path('', include(pins_router.urls)), path('devices/', include(devices_router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Question: I want to "group" or prefix all device_router urls with /devices/ while still showing it on the root API view. Currently, I can view /devices/relays/<pk>, however it is not shown in the root API view of DRF. Current result: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "pins": "http://pinode:8000/pins/" } Required result: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "pins": "http://pinode:8000/pins/", "devices": "http://pinode:8000/devices/" } Where http://pinode:8000/devices/ shows the following: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "relays": "http://pinode:8000/devices/relays/", "ultrasonic_sensors": "http://pinode:8000/devices/ultrasonic_sensors/", "contact_sensors": "http://pinode:8000/devices/contact_sensors/", } -
Update / edit post with multiple images in django
I am working to create a social network with django and I want to update a post that contains multiple images. So far, I can create a post with images by using 2 model Post and Images. This is my update function for now, I copy it form my create_post function: def update_post(request, pk): if request.method == 'GET': post = Post.objects.get(pk=pk) post_form = PostModelForm(post.content) if request.method == 'POST': print('dude u call me') postForm = PostModelForm(request.POST) profile = Profile.objects.get(user=request.user) images = request.FILES.getlist('images') if postForm.is_valid(): post_form = postForm.save(commit=False) post_form.author = profile post_form.save() for image in images: photo = Images(post=post_form, image=image) photo.save() messages.success(request, "Yeeew, check it out on the home page!") return HttpResponseRedirect("/") else: print(postForm.errors) return HttpResponseRedirect("/") Update template <div class='ui segment'> <h3>Update post</h3> <form action="" method="POST" class="ui form" enctype="multipart/form-data"> {% csrf_token %} {{form}} <button type='submit' class="ui button primary mt-5">Update</button> </form> </div> Post model form class PostModelForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'rows': 2})) class Meta: model = Post fields = ('content', ) Images model class Images(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='posts', verbose_name='Image', validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])], blank=True) Post model class Post(models.Model): content = models.TextField() liked = models.ManyToManyField(Profile, blank=True, related_name='likes') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='posts') My create template … -
How to get cognito user pool's custom attributes from access token? it shows only user attrs why?
def lambda_handler(event, context): if event["httpMethod"] == "GET": print('Event_Auth:', event) headers = event['headers'] access_token = headers.get('Authorization') if access_token: pieces = access_token.split() if len(pieces) == 2 and pieces[0].lower() == 'bearer': access_token = pieces[1] print('Without Bearer:', access_token) is_valid = validate_token(access_token) def validate_token(access_token): try response = cognito.get_user(AccessToken=access_token) if response['Username']: print('Response:', response) print('Cognito Username:', response['Username']) return True except: return False This is my lambda handler, what we are using? we have an authroizer in api-gateway which triggers a lambda function and obtain an Access Token... i have an intermediate knowlodge about aws. Problem: We haved added custom attrs in coginto user pool, and we need these attrs to build SaaS which is very much important for us. So, what is happening now, we are unable to retrieve custom attrs of user pool in the event because custom attrs doesn't exist in event, but user attrs are in the event, then why custom doesn't exists in the event? What will be the solution for that, kindly let me know we stuck there from last couple of days? ` Response: {'Username': 'XXXXXXX', 'UserAttributes': [{'Name': 'sub', 'Value': 'ca2ae0ae-XXXXX-XXXXX'}, {'Name': 'email_verified', 'Value': 'true'}, {'Name': 'email', 'Value': 'example@email.com'}], 'ResponseMetadata': {'RequestId': '87314820-7141-4089-a92c-XXXXXXXXXXXX', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Wed, 09 Aug 2023 12:04:57 … -
Django data table load thousands of rows using server side AJAX
I have already created a data table that is working just fine. The only problem is that because there are thousands of rows it takes quite a while to load. Below is my code view def live_equity_balance_original(request): if request.method == 'POST': mt4_checked = 'mt4' in request.POST.getlist('platform') mt5_checked = 'mt5' in request.POST.getlist('platform') ctrader_checked = 'ctrader' in request.POST.getlist('platform') platforms = [var_name for var_name, var_value in [('mt4', mt4_checked), ('mt5', mt5_checked), ('ctr', ctrader_checked)] if var_value] variable_names = { 'mt4': 'balance_equity_mt4_query', 'mt5': 'balance_equity_mt5_query', 'ctr': 'balance_equity_ctr_query' } for platform in platforms: if platform in variable_names: module_name = 'queries.queries' variable_name = variable_names[platform] module = importlib.import_module(module_name) balance_equity_query = getattr(module, variable_name) if platform == 'mt4': df = my_library.get_mt4_data(balance_equity_query) df = df.loc[df.login.astype(str).str.len() > 5] exclude_strings = ['MANAGER','tEsT','COVER'] df = df[~df['group'].str.contains('|'.join(exclude_strings),case=False)] df = df.loc[(df['balance']!=0)|(df['equity']!=0)] df = df.head(100) headers = df.columns json_records = df.reset_index(drop=True).to_json(orient ='records') data = json.loads(json_records) context = {'headers': headers,'data': data} return render(request, 'live_equity_balance.html', context) table.html template {% load custom_filters %} <div class="container"> <br><br><br> <table class="table row-border cell-border display compact" id="example" style="text-align: center;"> <thead class="table-success"> <tr> {% for header in headers %} <th>{{ header }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in data %} <tr> {% for header in headers %} <td>{{ item|get_value:header }}</td> {% endfor %} … -
Function does not return http 400 request
queryset = WaitingForParticipationInEvent.objects.all() serializer_class = WaitingForParticipationInEventSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): instance = serializer.save() if `ParticipationInEvents`.objects.filter(user=instance.user, event=instance.event).exists(): print(5551) print(ParticipationInEvents.objects.filter(user=instance.user, event=instance.event).exists()) return Response({"message": "User already in event"}, status=status.HTTP_400_BAD_REQUEST) else: waiting_serializer = WaitingForParticipationInEventSerializer(data={'url': instance.url, 'id': instance.id, 'username': instance.username,'first_name': instance.first_name, 'read': instance.read, 'user': instance.user, 'event': instance.event}) if waiting_serializer.is_valid(): waiting_serializer.save() print(555) return Response({"detail": "Допущено: Объект успешно создан в ModelA."}, status=status.HTTP_201_CREATED) return Response(waiting_serializer.errors, status=status.HTTP_400_BAD_REQUEST) There is my model viewset, when I am creating WaitingForParticipationInEvent object I need to check an existence of ParticipationInEvents object with the same user and event, if exists I return bad request, if does not I create the object. Butyour text it does not return bad requеst though print(5551) works. Help pls -
Django different 404 Errors on Production
I have product pages and tag pages on my website. For the product query, I use the code: product = get_object_or_404(Product, slug=slug), and for the Tag query, I use: tag = get_object_or_404(Tag, slug=slug). When running my code on my local machine with DEBUG set to True, I encounter a Django error page with a 404 status code. However, in my production environment, I experience different behaviors for the two types of pages. For tag pages, like https://my.domain/tag/abrakadabra/, I correctly receive a 404 error page. However, for product pages, like https://my.domain/product/abrakadabra/, I encounter an internal server error instead of the expected 404 error page. Interestingly, when I set DEBUG to True on my production server, I do receive the correct 404 Django error page for both tag and product pages. -
Migrating from SQLITE to postgreSQL in django raises " can't adapt type 'CharField'"
I'm using Django 4.1.10 and i'm trying to migrate from sqlite to postgresql but when I try to execute de migration files or dump data from manage.py i get this error django.db.utils.ProgrammingError: can't adapt type 'CharField' It happens both whe using python.exe manage.py migrate and python.exe manage.py dumpdata > datadump.json Is there any restriction related to datatypes?