Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement preview page with files Django?
I have my News model: class News(models.Model): subject = models.CharField(max_length=30) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I also have File model to store files and NewsFile model to connect models to each other: class File(models.Model): file = models.FileField( 'файл' ) class NewsFile(models.Model): file = models.ForeignKey( File, on_delete=models.CASCADE, verbose_name='файл', related_name='news_files' ) news = models.ForeignKey( News, on_delete=models.CASCADE, verbose_name='новость', related_name='files' ) Here is my news form: class MultipleFileInput(forms.ClearableFileInput): allow_multiple_selected = True class MultipleFileField(forms.FileField): def __init__(self, *args, **kwargs): kwargs.setdefault("widget", MultipleFileInput()) super().__init__(*args, **kwargs) def clean(self, data, initial=None): single_file_clean = super().clean if isinstance(data, (list, tuple)): result = [single_file_clean(d, initial) for d in data] else: result = single_file_clean(data, initial) return result class NewsForm(forms.ModelForm): files = MultipleFileField(required=False) class Meta: model = News fields = ('subject', 'text') I want to make a page with a preview of the news and buttons to publish or edit the news. I have started implementing publish button, I can't pass files with form. My view: def form_valid(self, form): files = form.cleaned_data.get('files') if self.request.GET.get('save') == 'true': res = super().form_valid(form) for file in files: file_obj = File.objects.create(file=file) NewsFile.objects.create(news=self.object, file=file_obj) return res img_files = [] non_img_files = [] for file in files: if file.name.split('.')[-1] in settings.IMAGE_FORMATS: img_files.append(file) else: non_img_files.append(file) images = [] for file in img_files: … -
Google Authentication Not Appearing in Django Project
Body: I am trying to set up Google authentication in my Django project using django-allauth, but the Google login option is not appearing on my login page. I suspect I might be missing a configuration step or setting. I have confirmed the site ID is correct by checking the link: http://127.0.0.1:8000/admin/sites/site/3/change/ Could someone help me identify what I might be missing or doing wrong? Here are the relevant parts of my settings.py: SOCIALACCOUNT_PROVIDERS = { "google": { "app": [ { "client_id": "myid", "secret": "mysecret", }, ], "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "online", }, } } SITE_ID = 3 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', 'allauth.account.middleware.AccountMiddleware', 'livereload.middleware.LiveReloadScript', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'core.views.site_settings', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LOGIN_REDIRECT_URL = 'login' # Redirect after login LOGOUT_REDIRECT_URL = 'home' # Redirect after logout -
Speeding up Django's total record count calculation for a site with 20 million records MySQL
I've encountered a problem with my Django website. Given that my database contains more than 20 million records, the operation of counting the total number of data (count) becomes extremely slow. I am using the following queries: company_count_query = f"SELECT COUNT(DISTINCT cs.OGRN) AS total_companies {company_from_clause} WHERE {company_match_condition} {email_condition} {capital_condition} {date_condition} {company_okved_condition}" ip_count_query = f"SELECT COUNT(DISTINCT ip.OGRNIP) AS total_ips {ip_from_clause} WHERE {ip_match_condition} {imail_condition} {ip_okved_condition}" How can I optimize these queries or use other methods to speed up the calculation of the total number of records? Thank you for your help! I tried to optimize the query structure by adding indexes to the columns on which filtering is performed, hoping to improve the performance of the counting operation. I expected that this would reduce the query execution time and speed up the data processing. However, in practice, the query execution time remained high and the counting operation still takes too long. -
How do I retrieve more than 10k document in elasticsearch?
I'm completely new to ELK and trying to retrieve 40k documents. the search_after depends on the previous batch of results and wasn't useful for me. GET twitter/_search { "query": { "match": { "title": "elasticsearch" } }, "search_after": [1463538857, "654323"], "sort": [ {"date": "asc"}, {"tie_breaker_id": "asc"} ] } how to retrieve more than 10k documents? -
Django reverse ForeignKey returns None
I have Student and Mark models in different apps of one project. # project/study # models.py class Mark(models.Model): ... student = models.ForeignKey( "students.Student", on_delete=models.PROTECT, related_name="marks", related_query_name="mark", ) # project/students # models.py class Student(models.Model): ... # views.py class StudentDetailView(DetailView): queryset = Student.objects.prefetch_related("marks") template_name = "students/one_student.html" context_object_name = "student" # one_student.html ... <p>{{ student.marks }}</p> ... Output of html is "study.Mark.None" That is my problem. I tried making ManyToOneRel field on student, select_related, making custom view func, but that does not help. Reverse ForeignKey brings None. I watched related questions - can't understand answers, because they are unrelated directly to my situation. I'm expecting to get all Student's marks. What am I doing wrong? -
Django admin inlines that has multilanguage field , TabbedTranslationAdmin does not work correctly
i have a django project, i use django-modeltranslation for translation fields. it have two model with one-to-many relation and i use django admin with inline for @admin.register(News) class NewsAdmin(nested_admin.NestedModelAdmin, TabbedTranslationAdmin): inlines = (NewsImageInline,) and image inline is: class NewsImageInline(nested_admin.NestedTabularInline,TranslationTabularInline ): model = NewsImage extra = 1 but in admin, tabularinline not work and show all of fields in one row -
Nginx is active but I don't see static files
I have a django project. Settings.py: STATIC_URL = 'static/' STATIC_ROOT = 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' I've made collectstatic and everything worked fine. Now static folder on my server with all the files. Nginx: enter image description here I had porblems with nginx, cause I changes name in sites_available and it started to give errors, so I reinstalled it and now everything is fine: nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset:> Active: active (running) since Wed 2024-05-01 14:47:13 UTC; 11min ago Docs: man:nginx(8) Process: 6843 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_proce> Process: 6844 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (c> Main PID: 6845 (nginx) Tasks: 2 (limit: 1026) Memory: 3.1M CPU: 60ms CGroup: /system.slice/nginx.service ├─6845 "nginx: master process /usr/sbin/nginx -g daemon on; master> └─6846 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" ""> May 01 14:47:13 23210 systemd[1]: nginx.service: Deactivated successfully. May 01 14:47:13 23210 systemd[1]: Stopped A high performance web server and a r> May 01 14:47:13 23210 systemd[1]: Starting A high performance web server and a > May 01 14:47:13 23210 systemd[1]: Started A high performance … -
403 Error when renewing Let's Encrypt Certbot using Django and Apache. I have 6 days to renew
When running the certbot renew command I first change my firewall permissions to allow connections on port 80, I put Cloudflare into Development Mode, then I run the renewal command. However this time I received a 403 Forbidden error trying to access the url example.com/.well-known/acme-challenge/funnylettersandstuff. I don't remember certbot needing this url but I only do this once a year for just one of my websites because for whatever reason I never got this configuration to auto renew. So here I am now trying to figure out what is causing this error. I have reviewed my virtual host configuration file and I cannot see any reasons this could be occuring. I also have modsecurity enabled but I doubt that's the issue since I cannot find any related errors in the modsecurity logs. Do I need to do something to Django to make this work? Certbot failed to authenticate some domains (authenticator: apache). The Certificate Authority reported these problems: Domain: example.com Type: unauthorized Detail: During secondary validation: 2a06:98c1:3120::1: Invalid response from http:// example.com/.well-known/acme-challenge/funkylettersandnumbers: 403 sudo iptables -P INPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo iptables -P OUTPUT ACCEPT sudo iptables -t nat -F sudo iptables -t mangle -F sudo iptables … -
Python Celery route task using hostname
I'm currently utilizing Celery for task management within my application, and I'm facing a challenge regarding task distribution to specific workers based on their unique hostnames. In my use case, I'm deploying multiple worker containers for a particular application. These containers are required to connect to various VPNs for specific requests or processing tasks. The challenge arises from the dynamic nature of container deployment, where each container's hostname is unique and dynamically assigned and it is stored on database with metadata information to be used by the application to select which worker should run a particular task. Given this scenario, I'm seeking a solution to send tasks directly to a specific worker based on it's hostname. This would ensure efficient task distribution, even in dynamic deployment environments where workers may connect to different VPNs dynamically and have different hostname each time. The logic to select the worker is already in place. The logic to create container/worker is already in place. The logic to requeue a task that is sorted to an invalid queue is already in place. Scenario Workers Worker01 (hostname=a333) connected to VPN 1 Worker02 (hostname=b999) connected to VPN 2 Worker03 (hostname=c777) connected to VPN 3 Worker04 (hostname=c444) connected … -
Why my Elasticsearch request doesn't show any hits?
I have dockerized Django project. I want to use Elasticsearch, so I choosed django-elasticsearch-dsl. My steps were: In my Django project's settings file (settings.py), I configured the Elasticsearch connection settings. ELASTICSEARCH_DSL = { 'default': { 'hosts': ["http://localhost:9200"], }, } Created a file named documents.py my Django app. In this file, I defined Elasticsearch documents that correspond to my Django models. from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Filmwork @registry.register_document class FilmWorkDocument(Document): class Index: name = 'film' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Filmwork fields = ['title', 'description'] So then I indexed data from my Django model into Elasticsearch by using command python3 manage.py search_index --rebuild. I used this command outside docker, it showed: File "/Users/ArtemBoss/Desktop/artem_yandex_repo/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "database" to address: nodename nor servname provided, or not known At the same time, when I'm trying to index data inside django container it shows: File "/usr/local/lib/python3.10/site-packages/elastic_transport/_node/_http_urllib3.py", line 202, in perform_request raise err from None elastic_transport.ConnectionError: Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f9150762b60>: Failed to establish a new connection: [Errno 111] Connection refused)) Anyway Index was successfully … -
CSRF verification failed. Request aborted. Origin checking failed
Here is my setup: localhost (Windows 11) - Nginx listening on port 80 and 443, 80 is NOT automatically redirected to 443 each proxy_passed to http://wsgi-server where wsgi-server=127.0.0.1:8080 - waitress_wsgi running as a service on port 8080 Here is Django config: <!-- email_test.html --> <!-- ... --> <form action="{% url 'identity:email_test' %}" method="post"> {% csrf_token %} {{ email_form }} {% translate 'Send email' as submit_translated %} <!-- I use django_bootstrap5 --> {% bootstrap_button button_type="submit" content=submit_translated extra_classes='w-100'%} </form> # settings.py ---------- MIDDLEWARE = { # ... 'django.middleware.csrf.CsrfViewMiddleware', # ... } # forms.py ------------- class EmailTestForm(forms.Form): email = forms.EmailField( # help_text=password_validation.password_validators_help_text_html(), label=_('Email'), max_length=128, ) # views.py ------------- def email_test(request): context = {} context.update(template_globals()) if request.method == "POST": email_form = EmailTestForm(request.POST) if email_form.is_valid(): email_obj = EmailMessage(subject='Hello', body='Email body', from_email='noreply@nutrihub.hnet', to=[email_form.cleaned_data.get('email')]) email_obj.send(fail_silently=False) else: email_form = EmailTestForm() context['email_form'] = email_form return render(request, "identity/email_test.html", context) Here are my test resuts when I visit the URL on browser: py manage.py runserver (default port 8000), browser http://127.0.0.1:8000, empty settings.CSRF_TRUSTED_ORIGINS: Works fine. Browser http://localhost or http://127.0.0.1 or https://localhost or https://127.0.0.1 with individual entry not in settings.CSRF_TRUSTED_ORIGINS: CSRF error. Browser http://localhost or http://127.0.0.1 or https://localhost or https://127.0.0.1 with individual entry not settings.CSRF_TRUSTED_ORIGINS: Works fine. Browser https://mymachine.net with this entry in … -
Import Error while using python manage.py migrate command
Recently, i forked some source code from github to use as a basis for a project that i'm using to learn Django. As per the deployment instructions, i tried to use this command for the database in my terminal: python manage.py migrate Yet i keep getting this error: ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\afric.virtualenvs\Online-Examination-System-aZtpAN9a\lib\site-packages\django\utils\encoding.py) the error stems from the terminal trying to proccess this command: from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError can anyone please help me solve this? -
What's the best approach to keeping data consistent in a django-based app used in parallel by three or four users?
I'm making a Django app using a postgresql database for a family who need to coordinate their grocery purchases. Say one person has on their mobile device a full list of the groceries and is in the supermarket, buying and ticking each item off the list. His partner decides to stop at another shop and begins buying the items on the same list. How would you approach ensuring that they don't buy double or, more importantly, that they don't end up messing up the data entirely? A simple first-come, first-served lock, giving the second user only read-only rights? Or is there a more flexible way? And if the best way is a lock, how much does postgresql do for you? -
Django: Pass model ID to url using bootstrap modal
I'm trying to create a delete confirmation dialog using bootstrap 5 modals in my Django project. {% extends 'base.html' %} {% block content %} <div class="col-md-6 offset-md-3"> {% if messages %} {% for message in messages %} <div class="alert alert-success alert-dismissible fade show" role="alert"> {{ message }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} </div> <h1>Service Overview</h1> <br/> <div class="d-grid gap-2 justify-content-md-end"> <a class="btn btn-primary" href="{% url 'add_service' %}">Add service</a> <br/> </div> <table class="table table-hover table-bordered"> <thead class="table-secondary"> <tr> <th class="text-center" scope="col">#</th> <th scope="col">Name</th> <th scope="col">Description</th> <th class="text-center" scope="col">Cost</th> <th class="text-center" scope="col">Created at</th> <th class="text-center" scope="col">Updated at</th> <th class="text-center" scope="col">Status</th> <th class="text-center" scope="col">Actions</th> </tr> </thead> <tbody> {% for service in services %} <tr> <td class="text-center">{{ service.id }}</td> <td>{{ service.name }}</td> <td>{{ service.description}}</td> <td class="text-center">{{ service.cost }} AED</td> <td class="text-center">{{ service.created_date }}</td> <td class="text-center">{{ service.updated_date }}</td> {% if service.status == "ACTIVE" %} <td class="text-center"> <span class="badge text-bg-success" style="font-size:0.7em;">{{ service.status }}</span> </td> {% elif service.status == "INACTIVE"%} <td class="text-center"> <span class="badge text-bg-danger" style="font-size:0.7em;">{{ service.status }}</span> </td> {% endif %} <td class="text-center"> <!--Update--> <a href="{% url 'service_record' service.id %}" class="text-decoration-none"> <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="tooltip" title="Update service"> <i class="bi bi-pencil-fill"></i> </button> </a> <!--Delete modal--> <!-- Button trigger … -
Django URL 404 - 1 week spent debugging with GPT4, Claude luck. One specific function is just NOT resolving
Issue Summary: I'm facing an issue where the /LS/mark-text-responses/ URL in my Django application is not being found when an AJAX request is sent to the mark_text_responses view. This issue is occurring in the user-facing part of my application, specifically in the JavaScript code that sends the AJAX request. I'm receiving a 404 Not Found error, indicating that the URL is not being resolved correctly. Relevant JavaScript Code: **javascript ** function submitWorksheet(event, activityIndex) { event.preventDefault(); const worksheetForm = event.target; const worksheetQuestionsData = worksheetForm.querySelector('.worksheet-questions').textContent; let worksheetData = {}; try { worksheetData = JSON.parse(worksheetQuestionsData); } catch (error) { console.error('Error parsing worksheet data:', error); return; } // ... (code omitted for brevity) ... if (question.type === 'text_response') { const textResponse = worksheetForm.querySelector(`textarea[name="response_${index + 1}"]`).value; const feedbackElement = document.getElementById(`text-response-feedback-${index + 1}`); // Make an AJAX request to the server to get feedback on the text response fetch('/lessons/mark-text-responses/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.querySelector('input[name="csrfmiddlewaretoken"]').value }, body: JSON.stringify({ activity_id: '{{ activity.id }}', question_index: index, text_response: textResponse }) }) .then(response => response.json()) .then(data => { if (data.feedback) { feedbackElement.textContent = data.feedback; } else { console.error('Error:', data.error); feedbackElement.textContent = 'Error processing text responses.'; } }) .catch(error => { console.error('Error:', error); feedbackElement.textContent = 'Error processing text … -
A "django.core.exceptions.SuspiciousFileOperation" error is occurring despite setting everything up correctly
Currently attempting to serve all of my static files via whitenoise. Funnily enough, the function itself works a treat. It seeks out all the directories labelled static in all of my Django apps. However, why is Django consistently returning the django.core.exceptions.SuspiciousFileOperation exception in my traceback, and why is this returning this just one css file. Logic would dictate that seeing as this css file is among other .css files in the same directory, Django seems to have some sort of personal vendetta against this one file. On the face it it, what Django is doing is completely illogical. My settings are as follows: pip install whitenoise settings.py INSTALLED_APPS = [ .... 'django.contrib.staticfiles', .... ] BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [ BASE_DIR / "static/libraries/assets/brand-assets", BASE_DIR / "static/libraries/assets/images", BASE_DIR / "static/libraries/assets/vectors", BASE_DIR / "static/libraries/assets/videos", BASE_DIR / "static/libraries/css", BASE_DIR / "static/libraries/js", BASE_DIR / "static/main", BASE_DIR / "legal/static", BASE_DIR / "blog/static", BASE_DIR / "events/static", BASE_DIR / "careers/static", BASE_DIR / "media/static", BASE_DIR / "static", ] My file directory is as follows: PROJECT NAME-| Root-| settings.py careers-| static-| careers.css media-| static-| media.css blog-| static-| blog.css legal-| static-| legal.css static-| main-| xxx.css xxx.css libraries-| css # <- location of … -
401 unauthorized Django Rest API Login
Im having problems with my login API Endpoint, it was working the last time I checked, now after working blindly for a few hours it doesnt work anymore and i don´t know what i´ve done :) Register is working smoothly, the user also gets created in the db and is visible in the admin panel. The same credentials are not working for the login. I´ve posted the code below, thanks for the help in advance views.py #register new users @api_view(['POST']) def register_user(request): if request.method == 'POST': serializer = UserSerializer(data= request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.data,status=status.HTTP_400_BAD_REQUEST) #userlogin with authentication tokens @api_view(['POST']) def user_login(request): if request.method == 'POST': email = request.data.get('email') password = request.data.get('password') user = None if not user: user = authenticate(email = email, password=password) if user: #token creation for the logged in user token, _ = Token.objects.get_or_create(user=user) return Response(user.getDetails(), status=status.HTTP_200_OK) # type: ignore return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) models.py class CustomUser(AbstractUser): # username = models.CharField(max_length = 25 ,default = 'No name',unique = True) username = None email = models.EmailField(default ="no email",unique = True) first_name = models.CharField(max_length = 25 ,default = 'No name') last_name = models.CharField(max_length = 25, default = 'No surname') password = models.CharField(max_length = 25,default = "no … -
Deployment not found error on deploying django project on cpanel
I have an issue in deploying my django project to cpanel after creating the python setup on cpanel pointing my subdomain to the setup project .I get 404(deployment not found) error once i click the url how can i fix that i expect the project should show the passenger_wsgi.py IT Works Screen on click of the url -
make authenticated and login work for multiple table other then auth User table django?
I have created hostTable model in hostlogin app and I want to use this table for login purpose for that i have created custom authenticate function because default authenticate() was working for auth user table only. Also login() is not attaching current session to the users from hostTable. Although it working fine if I set AUTH_USER_MODEL ='hostlogin.HostTable' but then admin page is not working also this is not acceptable solution because hostTable I will use for teaches login (127.0.0.1:8081/tlogin/) and studentlogin table I will use for student login (127.0.0.1:8081/slogin/) that time how will I use two different table for different login() and authenticate (), for non of these two users I don't want to provide admin access (127.0.0.1:8081/admin/) that's why I am not using auth user table. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser,AbstractBaseUser,PermissionsMixin from django.contrib.auth.hashers import make_password, check_password class HostTable(AbstractBaseUser): pid=models.AutoField(primary_key=True,auto_created=True) username=models.CharField(max_length=50,unique=True) password=models.CharField(max_length=128) createdtime =models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(default=timezone.now) is_authenticated=models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS=['hostname','ownername','password'] def save(self, *args, **kwargs): self.password = make_password(self.password) super(HostTable, self).save(*args, **kwargs) def __str__(self): return self.hostname view.py def hostlogin(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') print('view',username,password) user = hostTableAuth.authenticate(request,username,password) … -
When we upload a selfie we get a 500 error [closed]
def upload_selfie_document(self,cleardil_id,document_id,selfie_image): url = f"{self.url}customers/{cleardil_id}/identifications" print(url, "url") selfie_image.seek(0) selfie_image = selfie_image.read() selfie_image_base64 = base64.b64encode(selfie_image).decode('utf-8') payload = json.dumps({ 'document_id': document_id, 'selfie_image': selfie_image_base64, }) # print(payload, "payload") headers = { **self.headers , 'Content-Type': 'application/json'} print(headers, "headers") try: response = requests.post(url, headers=headers, data=payload) print(response, "response") if response.status_code in range(400, 505): {response.text}") return None return response.json() except Exception as e: logger.error(f"Request exception: {str(e)}") return None I am trying to upload a selfie but I get response <Response [500]> response -
No output in serializermethodfield()
I defined a serializermethodfield. My problem in displaying the output. When this method exists, the image field is empty for me. But if I delete this serializermethodfield, my image output will be correct. serilizer: class ArticleSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) image=serializers.SerializerMethodField() class Meta: model=Article fields="__all__" validators=[Checktitle()] def get_image (self , obj ): request=self.context.get("request") if obj.image: image_url=obj.image.url return request.build_absolute_uri(image_url) return None view: class ArticleListview(APIView): def get(self,request): query_set=Article.objects.all() ser = ArticleSerializer(instance=query_set,many=True,context={'request':request}) print(request) return Response(data=ser.data) I wanted to change the url image. But by defining this method, the image is not saved at all. -
Unable to start Django app, error related to what seems like a circular import?
I'm currently attempting to build my first django app, a resume website. I get this error when trying to start the app. <class 'mainapp.admin.CertificateAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'is_active', which is not a callable, an attribute of 'CertificateAdmin', or an attribute or method on 'mainapp.Certificate'. This is what I have in my models.py file related to "certificate" (comments included): `class Certificate(models.Model): class Meta: verbose_name_plural = 'Certificates' verbose_name = 'Certificate' date = models.DateTimeField(blank=True, null=True) # When the certificate was earned name = models.CharField(max_length=50, blank=True, null=True) # Name of the certificate title = models.CharField(max_length=200, blank=True, null=True) # Title or description of the certificate description = models.CharField(max_length=500, blank=True, null=True) # Additional details about the certificate is_active = models.BooleanField(default=True)` And this is what I have in my admin.py file: @admin.register(Certificate) class CertificateAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'title', 'is_active') # Display 'id', 'name', and 'is_active' fields ChatGPT has been no help so far, only circular answers to make sure 'is_active' is properly called, I'm not sure it is, it seems like it (I'm sort of a beginner). I'm following instructions from a youtube video (yes, I have been learning python and django since last year, did not follow THAT blindly!), the "is_active" … -
Memcached-MemcacheIllegalInputError - Data values must be binary-safe: 'ascii' codec can't encode characters in position 2-5: ordinal not in range(128
I'm doing some tests with memcached on my django project to understand if I can get benefit of it. But I stuck at unicode character caching. I read many article about it but still could not understand how can I make it work. Here is my code block: def cache(request): client = Client("127.0.0.1:11211") cache_key = '123' # needs to be unique cache_time = 86400 # time in seconds for cache to be valid data = client.get(cache_key) # returns None if no key-value pair if not data: print("setting cache") #data contains unicode characters - Throws an error datafromdb = Subject.objects.all() #unicode characters - Throws an error unicodestr="abçüıö" #encoded unicode characters - Working fine encodedunicodestr=str.encode("abçüıö") client.set(cache_key,unicodestr , cache_time) else: print("getting from cache") return HttpResponse(data) So If I use str.encode on text values It works fine and data can be cached. But If I retrieve data from database(postgres) and this data contains unicode memcached throws an error. I'm wondering if is there a way to use str.unicode on my queryset/list etc that returned from database or something else may be. -
Unit Test pipeline - Django Unit tests
I am working on a django project and it has 20+ apps in it which means i have to run tests of 20+ apps which includes 3000+ tests. So I decided to make subjobs in my pipeline and now running 20 jobs for the unit tests on commit. But the issue is that when more than 1 developer commits and tests runs for both, pipeline get stucks. Pipeline runners are registered on a VM of 32 CPU cores and 24 GB of RAM. CPU utilization becomes 100% and jobs stuck(deadlock). How can I optimize my pipeline subjobs so that if multiple devs work it didnt stuck. unit_test: stage: test rules: - changes: - backend/ tags: - workstream-unit-test when: manual allow_failure: false parallel: matrix: - APP_NAME: - apps.app1 - apps.app2 - . - apps.app20 before_script: - apt-get update - apt-get install -y unixodbc unixodbc-dev - pip install virtualenv - virtualenv venv - source venv/bin/activate - pip install -r requirements.txt script: - COVERAGE_FILENAME=$(echo "$APP_NAME" | tr '.' '_')_coverage.xml - coverage run --source=$APP_NAME ./manage.py test $APP_NAME --settings=hrdb.test_settings --keepdb --noinput - coverage xml -i -o $COVERAGE_FILENAME - coverage report -m --fail-under=90 --skip-covered coverage: '/(?i)TOTAL.*? (100(?:\.0+)?%|[1-9]?\d(?:\.\d+)?%)$/' artifacts: expire_in: 2 hour paths: - $CI_PROJECT_DIR/$APP_NAME_coverage.xml I am … -
Find Template in django
My code is like below. {% if request.path != '/login/' %} {% include "/hospital/templates/header.html" %} {% endif %} I am getting error TemplateDoesNotExist at /dashboard/ /hospital/templates/header.html How to include a template ?