Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to check ping response of multiple website in django based site?
I have created one website which contains different company application in bootstrap cart format. So this cart is showing the application version and allowing the user to download it by clicking on the button. Requirement: Now I am trying to implement functionally where it will show whether the site is online/reachable or not by a green color dot. I have tried the below code but I found that only for a few 1 sites it is showing green color and for the remaining, it is showing False. Also found that the site is taking time to load the home page I have seen this functionality in another website. Can anyone suggest me how to implement it in the best way? Please find the below code. views.py(showing only logic code) data = {} for singlesite in allsites: site=singlesite.product_by try: subprocess.check_call(['ping', '-c', '1', str(site)]) except subprocess.CalledProcessError: online = False data['online'] = online print('Checking The Ping Response:', online) else: online = True data['online'] = online print('Checking The Ping Response:', online) in the above code, product_by means I am taking it from model str form. HTML code. .logged-in { color: green; font-size: 8px; } .logged-out { color: red; font-size: 8px; } {% if online … -
Django readonly datetime field in inline causing naive datetime RuntimeWarning in tests
I'm getting this annoying error printed to the console when testing the admin add form. The ProductAdmin has an inline with a readonly datetime field which is the culprit of the error: RuntimeWarning: DateTimeField Production.created_at received a naive datetime (2021-04-16 00:00:00) while time zone support is active. class ProductionInline(admin.TabularInline): model = models.Production extra = 1 fields = ('amount', 'details', 'created_by', 'created_at') readonly_fields = ('created_by', 'created_at') @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): inlines = ( ProductImageInline, ProductionInline, ) def test_get_add(self): url = reverse('admin:product_product_add') response = self.client.get(url) self.assertEqual(response.status_code, HTTPStatus.OK) The error is pretty self explanatory, I'm wondering if someone knows an easy way around this without setting a custom formset on the TabularInline that specifies a timezone aware initial value for the created_at field. Interestingly this happens in the browser as well on initial page load after ./manage.py runserver but subsequent page loads don't print the error. -
prefetch_related() error in ,django while inner joining
I am create a code that is inner join of two object Contest and ContestDetails def get_queryset(self): try: key = self.kwargs['pk'] if key is not None: return ModelA.objects.filter(custom_id=key, is_deleted=False).prefetch_related( Prefetch('modelb_set', queryset=ModelB.objects.filter())) \ .order_by('-updated') except Exception: return ModelA.objects.filter(is_deleted=False).prefetch_related( Prefetch('modelb_set', queryset=ModelB.objects.filter())) \ .order_by('-updated') And when I run it then I am getting below error raise AttributeError("Cannot find '%s' on %s object, '%s' is an invalid " AttributeError: Cannot find 'modelb_set' on ModelA object, 'modelb_set' is an invalid parameter to prefetch_related() I checked some example related to this but why I am getting below error in my code? Where I did wrong? How can I fix? -
Django i18n language switcher not working on deploy at subdirectory
I've got a site with two languages (it will get more in time) and a little dropdown menu to switch languages. It works as desired/expected in the development server. Urls look like this when visiting the site: localhost:8000/en/home localhost:8000/pl/home The django project gets deployed on a server (Apache w/ mod-wsgi) at a subdirectory location, lets say: mysite.com/django Everything works as expected, even the admin site, etc, underneath that subdirectory, however, my little menu to change languages doesn't work anymore. When I change the language, the page reloads, but on the same language that it was on when I tried to change it. I can go back and forth between the languages by manually changing the url in the browser and all the pages work as expected with the translations; it's just the dropdown button that doesn't work anymore. mysite.com/django/en/home mysite.com/django/pl/home At first, I thought it was my button (pretty standard off a tutorial): <form action="{% url 'set_language' %}" method="post" class="form-inline">{% csrf_token %} <div class="form-group mx-sm-3 mb-0"> <input type="hidden" name="text" value="{{ redirect_to }}" class="form-control form-control-sm"> <select name="language" id="langselect" onchange="this.form.submit()"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" … -
Django: Model Class Variables Inheritance
I have below classses class power_source_template (models.Model): power_source_current_type_choices = (("AC", "Alternating Current"),("DC", "Direct Current")) class Meta: abstract = True and class power_sources(power_source_template, tracking_template): ... power_source_current_type = models.CharField(max_length = 2, choices = power_source_current_type_choices) ... When running python3 manage.py check, the following error appears: > File "/var/www/celeste/strato/kirchhoff/models.py", line 61, in power_sources > power_source_current_type = models.CharField(max_length = 2, choices = power_source_current_type_choices) NameError: name > 'power_source_current_type_choices' is not defined What am I doing wrong? I reviewed the Django documentation, but there's no mention of variables inheritance. -
Bootstrap alert message giving me unexpected token <
I am working on a django project and in my html file, I have this code snippet. {% block content %} {% ifequal error False %} <script> <div class="alert alert-success"> <strong>Login Successful</strong> </div> window.location.href="{% url 'home' %}"; </script> {% endifequal %} {% ifequal error True %} <script> <div class="alert alert-success"> <strong>Wrong credentials! Try again</strong> </div> window.location.href="{% url 'login' %}"; </script> {% endifequal %} {% endblock content %} In the console, I am getting this message: Uncaught SyntaxError: Unexpected token '<' On line 500, it is saying. Basically, it points at the line where there is a div within the first script tags. The bootstrap alert is not showing and there is no redirection. If I put a simple alert,everything works! Any idea what is wrong? -
Django - Form used in editing data from extended user model doesn't show previous data as placeholder
I use following code: models.py class Profile(models.Model): location = models.CharField(max_length=300, blank=True) user = models.OneToOneField( User, on_delete=models.CASCADE, ) def __str__(self): return self.imie views.py def edit(request): if request.method == 'POST': profile = Profile.objects.get(user = request.user) profile_form = ProfileForm(request.POST, instance = profile) if profile_form.is_valid(): profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('profile') else: messages.error(request, ('Please correct the error below.')) else: profile = Profile.objects.get(user = request.user) profile_form = ProfileForm(request.POST, instance = profile) return render(request, 'edit.html', { 'profile_form': ProfileForm }) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('location') edit.html <div class="col-md-6 offset-md-3"> <form method="post"> {% csrf_token %} {{ profile_form.as_p }} <button type="submit" class="btn btn-secondary">Save changes</button> </form> </div> Following code should allow the user to edit data stored in Profile model and it does exactly that, however form is loaded empty (without placeholder) and I would like it to display previous values. -
How to set a single field of custom form in django in template
I have a custom Django Form # creating a form class PostForm(forms.ModelForm): # create meta class class Meta: # specify model to be used model = Post # specify fields to be used fields = [ "title", "slug", "author", "content", "status", "youtubeVideo", "category", "image", ] I have my view as follows: def create_post(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization user = get_user(request) form = PostForm(request.POST or None, initial={'author': user}) if form.is_valid(): form.fields["author"] = user form.save() return HttpResponseRedirect("/index") context['form']= form return render(request, "blog/create_post.html", context) How to set the django form template with only my current user? My django template is as follows: <div class="card-body"> {% load crispy_forms_tags %} <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form | crispy}} <input type="submit" value="Submit"> </form> </div> -
How to disable dates on calendar if its reservated or book in Django?
I'm making a website with rezervation system in Django. But I want the reserved days not to appear in the calendar (datepickertime). I couldn't do what I tried, does anyone have an idea? How can I query if dates are booked? models.py class Reservation(models.Model): enter_date = models.CharField(max_length=250, db_index=True) out_date = models.CharField(max_length=250, db_index=True) -
SSL certificate for use with Celery/Redis - I don't understand 'keyfile','certfile' and 'ca_certs'
I have my Celery and Redis set up as the following - app.conf.update(BROKER_URL='rediss://:password@host:port', CELERY_RESULT_BACKEND='rediss://:password@host:port', broker_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }, redis_backend_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }) But I want to make the SSL certificate required as per the celery documentation - app.conf.update(BROKER_URL='rediss://:password@host:port', CELERY_RESULT_BACKEND='rediss://:password@host:port', broker_use_ssl = { 'keyfile': '/var/ssl/private/worker-key.pem', 'certfile': '/var/ssl/amqp-server-cert.pem', 'ca_certs': '/var/ssl/myca.pem', 'cert_reqs': ssl.CERT_REQUIRED }, redis_backend_use_ssl = { 'keyfile': '/var/ssl/private/worker-key.pem', 'certfile': '/var/ssl/amqp-server-cert.pem', 'ca_certs': '/var/ssl/myca.pem', 'cert_reqs': ssl.CERT_REQUIRED }) The issue is that I don't understand where I get my 'keyfile','certfile', 'ca_certs' from. Do I have to create these or can I use my SSL certificate from Heroku somehow? -
Django model not updating image field correctly (Raw content)
My model: class MyModel(models.Model): picture = models.ImageField(blank=True, null=True, upload_to='pictures') Update a single object: >>> picture >>> <ContentFile: Raw content> >>> mymodel = MyModel.objects.get(pk=instance.pk) >>> mymodel.picture = picture >>> mymodel.save() >>> mymodel.picture >>> <ImageFieldFile: pictures/fbdfe25b-b246-4f2d-9436-dca49aef88d7.png> Good. Url result /media/pictures/fbdfe25b-b246-4f2d-9436-dca49aef88d7.png. Update a single object with the update() method: >>> picture >>> <ContentFile: Raw content> >>> MyModel.objects.filter(pk=instance.pk).update(picture=picture) >>> mymodel.picture >>> <ImageFieldFile: Raw content> Bad. Url result: /media/Raw%20content. -
School, Students, Room model setup
How can I get all Students in a Room from: rooms = Room.objects.filter(School=school, RoomNumber=teacher.TeacherNumber) #view.py def classRoomPage(request, SchoolCode, TeacherID): teacher = Teacher.objects.get(SchoolCode=SchoolCode, TeacherNumber=TeacherID) school = School.objects.get(SchoolCode=SchoolCode) rooms = Room.objects.filter(School=school, RoomNumber=teacher.TeacherNumber) The data for School, Teacher and Students is coming from an external API I have no control over fields provided. #models.py class School(TimeStampedModel, models.Model): SchoolCode = models.CharField(max_length=254, blank=True, null=True) Name = models.CharField(max_length=100) class Teacher(TimeStampedModel, models.Model): School = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) SchoolCode = models.CharField(max_length=254, blank=True, null=True) TeacherNumber = models.CharField(max_length=254, blank=True, null=True) # Room number assignment FirstName = models.CharField(max_length=254, blank=True, null=True) LastName = models.CharField(max_length=254, blank=True, null=True) Room = models.CharField(max_length=254, blank=True, null=True) # A121, 101 etc.. StaffID1 = models.CharField(max_length=254, blank=True, null=True) # Is Unique class Student(TimeStampedModel, models.Model): ID = models.CharField(max_length=254, blank=True, null=True) SchoolCode = models.CharField(max_length=254, blank=True, null=True) TeacherNumber = models.CharField(max_length=254, blank=True, null=True) LastName = models.CharField(max_length=254, blank=True, null=True) FirstName = models.CharField(max_length=254, blank=True, null=True) Grade = models.CharField(max_length=254, blank=True, null=True) After importing Schools, Teachers and Students I create rooms. Is there a better way to create Rooms? Preferably where there is just one row per RoomNumber instead of a row for each Student. #models.py continued ## How Rooms are Created # for each s in School # for each Teacher in s # for each Student … -
why is "Django HTML" not offered as a choice in "Select Language Mode" in VSCode, Windows 10?
Operating System: Windows 10, 64 bit Editor: VSCode 1.55.2 Python 3.9.0 Django * (for now version 3.2) I'm watching a course (python, codewithmosh). My folders and files are as bellow image. why is "Django HTML" not offered as a choice of language after clicking on the lower-right language indicator? Thanks in advance for your helps. -
How to solve .accepted_renderer not set on Response Error in Django
I'm new at django and I have to use it in my project. So, team mates create micro services using Docker container. I have to call these micro services to execute the text written in text field. To do that I wrote a views.py file but when I try to write a sentence and call these micro services it gave me a AssertionError .accepted_renderer not set on Response error. views.py def link1(request): if request.method == "POST": url = 'http://localhost:5000/sentiment/' payload = {'text':request.POST.get("response")} response = json.dumps(requests.post(url, data = payload).text) return Response (response) return render(request, 'blog/links/Link1.html') Link1.py <form class="text" method="POST"action="{% url 'duyguanalizi' %}"> {% csrf_token %} <label for="textarea"> <i class="fas fa-pencil-alt prefix"></i> Duygu Analizi </label> <h2>Kendi Metniniz ile Test Edin...</h2> <input class="input" id="textarea" type="text" name="text"> </input> <button type="submit" class="btn" name="submit" onclick="submitInfo()" >Dene</button> </form> {% if input_text %} <label >Sonuç </label> <p name ="input_text" id="input_text"><strong>{{ response }}</p> {% endif %} This is my full error: Request Method: POST Request URL: http://127.0.0.1:8000/duyguanalizi/ Django Version: 3.0.5 Exception Type: AssertionError Exception Value: .accepted_renderer not set on Response Exception Location: C:\Users\Asus\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\response.py in rendered_content, line 55 Python Executable: C:\Users\Asus\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 -
sending value from html link to views.py in django
I have a link that lets user download a file. Something like this {% for x in photo %} <a href="{{x.image.url}}" download="none">Get</a> {% endfor %} here photo is a queryset containing all objects in my models.py here is my models.py class Photo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to="home/images") def __str__(self): return str(self.id) now I need a way to get the id of the image into a function in my views.py that user has downloaded using that link. -
Apache, Django and RestFramework: How to block requests on Apache from an unallowed host
I've got an api running with apache, django and djangorestframework on let's say api.example.com. This api is only accessed from www.example.com. In django I get the following logs, which are correct: Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add 'x.x.x.x' to ALLOWED_HOSTS. How can I block requests from another host than www.example.com with Apache? -
Firebase Phone Authentication in Web Django
When i click sending otp to phone, it shows that hostname match not found, Can you tell any suggestion -
Ajax or Django Rest Framework is acting weird with Post Data
I am building a Kanban Board with jQuery / JS Frontend and Django / DRF Backend. I am sending a POST AJAX Request to Server function login(email, password) { var d = { "email": email, "password": password } d = JSON.stringify(d) console.log(d) return $.ajax({ url: "api/accounts/login/", type: "POST", data: d, dataType: "json", }).then((response) => { var data = JSON.parse(response); return data; }).fail((response) => { return false; }) } But when the request is received by the server this {"email":"satyam@gmail.com","password":"satyam@789"} is converted to '{"email": "satyam@gmail.com", "password": "satyam@789"}': ['']}' What is the problem causing this? Is it Javascript or DRF? -
django.db.utils.IntegrityError: NOT NULL constraint failed: app_user.zip
I can't create the superuser when I create this model in my app. WHen I remove AUTH_USER_MODEL = 'app.User' from my settings then showing another error "django.core.exceptions.FieldError: Unknown field(s) (full_name) specified for User" but I can create superuser on that time. Even I tried to fill up every single field with "null=True" and solved the error but can't log in to my admin panel with the created email password. I can't understand exactly where was the problem.. Here is my all code. Models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from creditcards.models import CardNumberField, CardExpiryField, SecurityCodeField class UserManager(BaseUserManager): def create_user(self, email, full_name, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an Email address.") if not password: raise ValueError("Users must have a Password") if not full_name: raise ValueError("Users must have a Full Name") user_obj = self.model( email = self.normalize_email(email), full_name=full_name ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, full_name, password=None): user = self.create_user( email, full_name, password=password, is_staff=True ) return user def create_superuser(self, email, full_name, password=None): user = self.create_user( email, full_name, password=password, is_staff=True, is_admin=False # will be True ) return user class User(AbstractBaseUser): email = … -
How do I install pandas on this one python file?
I just need to install pandas i tried running pip3 install pandas and keep getting this error " import pandas as pd ModuleNotFoundError: No module named 'pandas' " app.py import xml.etree.ElementTree as ET import pandas as pd -
Question coherence choice techno web + Django + BD
I have had a website project for a while. I'm still in the learning phase for probably a few more weeks. I am mastery in HTML, CSS, JavaScript Vanilla, PHP, MySQL, Python. I am currently learning Django, soon the React JS JavaScript framework; AJAX; CSS -> SASS; Nginx; Gunicorn and probably UML + PostgreSQL The site I am going to develop is not yet fixed from a technical point of view. I want it to be in Python / Django, because the site will be very strongly linked to using APIs in Python (including Youtube) and will also be very much linked to a web bot written in Python (bot that provides the data in connection with the API to create the content of the pages). The site will be very automated in the production of its content (by just a web server's view, but also by adding new content). I currently only have a pretty bad estimate of how many pages the site will be able to deliver. I estimate it to be at least 1 million pages. My questions are as follows: I am already familiar with MySQL, but I think I will need several databases, many tables, … -
Can't save admin form with more than 1000 entries selected
I have a group that requires at least 1000 permissions to be chosen. This is the group before: This is what I do: And this is what happens when I save. While I can read, and understand that increasing DATA_UPLOAD_MAX_NUMBER_FIELDS to a larger value or None will resolve the issue, this is a production service, and I am not allowed to increase that value for security reasons. Since only the admin needs to handle POST requests of this size, we can ease that a bit by overriding the admin form. But how should I go about that? This is an example snippet that I have, and I don't know where I can put an override_settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=None. Where can I put that? class GroupAdminForm(forms.ModelForm): class Meta: model = Group fields = '__all__' class GroupAdmin(Admin): form = GroupAdminForm list_display = ('...',) admin.site.register(Group, GroupAdmin) -
trying to show elements of a dictonary that's stored in django model
What i have is a django project that stores a dictionary in a json model. class MyModel(models.Model): jsonM = JSONField() The dictionary is just a bunch of numbers. known as my sortedList I am accessing these numbers in my html by passing then as a context variable in my views.py numbers_in_sortedList = MyModel.objects.all() return render(request, "showdata.html", context={ 'numbers_in_sortedList':numbers_in_sortedList }) I am able to show the dictionary on my html via: <li> {% for number in numbers_in_sortedList %} {{item.jsonM}} {% endfor %} </li> this works find and shows 1 bullet point, with all the values in a dictionary. however how can i access each individual element in the dictionary individually? I have tried nesting a for loop but it doesn't seem to work, stating that "myModel object is not iterable" <li> {% for number in numbers_in_sortedList %} {% for item in number %} {{item.jsonM}} {% endfor %} {% endfor %} </li> Any ideas? -
Django : how to assign permissions automatically after initial migration
I'm using Django for my backend and everything's fine. But I now have to enable permissions and so on. I'm trying to assign all the permissions of an app to a group during the migration process but here is the problem : During the initial migration, the Permissions are not created yet. The reason is that in Django, they are created in a post_migrate signal. The default flow is : call migrate command it does migration things post_migrate signal is sent and Permissions records are created So I could write a post_migrate function too but, how could I be sure that it will be run after the default one that creates Permissions ? Other question : is there a better way to assign permissions automatically when an app is first migrated ? Thanks in advance :) -
python manage.py runserver not working on on localhost:8000
I am new to django and trying to run the django server for the first time. I am trying to run the command for starting a django server in a terminal, i.e. python manage.py runserver. But when I go to http://localhost:8000, it is not giving me the default django output containing a rocket like image. I even tried using http://my_ip:8000 and http://127.0.0.1:8000 but still it doesn't work. I also tried running the command as python manage.py runserver 8000 but it still does not give me anything on localhost:8000. I have checked and no firewall / antivirus is blocking this port for me. Also, I am able to access other applications on other ports. I am not getting any errors on my terminal when I run this command. This is a blocker for me and any help would be really appreciated. Follow the image of my vs code integrated terminal here Find my image of browser navigated to http://localhost:8000 over here. I am using the latest python version 3.9 and my django version is 3.2. Thanks!