Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Radio button in django
Tried looking for solutions but I have a different problem and couldn't find anything related to it I've created a django form with fields from models.py forms.py from .models import ProValue from django import forms class SchoolInput(forms.ModelForm): school_name = forms.CharField( max_length=255, required=True, widget=forms.TextInput( attrs={ 'class': 'input' } )) level_of_grades = forms.IntegerField(min_value=1, required=True) num_of_days = forms.IntegerField(min_value=1, max_value=7, required=True) division_check = forms.ChoiceField( label='Do you have multiple divisions for your grades?', widget=forms.RadioSelect) class Meta: model = ProValue answer = ( ('no', 'no'), ('yes', 'yes') ) fields = [ 'school_name', 'level_of_grades', 'num_of_days', 'division_check', ] With this I can't see radio buttons on the page I've tried doing division_check = forms.ChoiceField( label='Do you have multiple divisions for your grades?', widget=forms.RadioSelect()) and division_check = forms.ChoiceField( label='Do you have multiple divisions for your grades?', widget=forms.RadioSelect(choice=answer)) This tells me answer is not defined This is my models.py from django.db import models from django import forms class ProValue(models.Model): school_name = models.CharField(max_length=50) level_of_grades = models.IntegerField() num_of_days = models.IntegerField() answer = ( ('Yes', 'Yes'), ('No', 'No'), ) division_check = models.CharField( max_length=5, choices=answer) Plus do I need to define answer in class Meta again? I didn't do it at first, I tried to solve above problems but still couldn't with it. -
ModuleNotFoundError: No module named 'cal'
I am a relatively new programmer and decided to start picking up python. I specifically was looking into the web development side of things. I was installed Django but I did so without being in a virtual env. I was still able to connect to the page. After following along with some tutorials I created a virtual env and then the server would no run and I would get a long error. It is posted in the pastebin link. It says missing module named 'cal' but I installed it with "pip install cal" but I still get this error. Any suggestions? Also, this is my first time using this website for help so I am also getting used to it. https://pastebin.com/Gve79dLA from django.urls import path from. import views urlpatterns=[ path('', views.home, name='home') ] from django.shortcuts import render from django.http import HttpResponse Create your views here. def home(request): return HttpResponse("Hello World") this is my urls.py and views.py -
Whle converting dict to serializer, serializer.is_valid always False in Django
My cmd: python manage.py shell from user.models import UserInfo from user.serializers import UserInfoSerializer import io from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser u=UserInfo.objects.all()[0] s=UserInfoSerializer(u) j=JSONRenderer().render(s.data) o=io.BytesIO(j) d=JSONParser().parse(o) s1=UserInfoSerializer(data=d) s1.is_valid() But the issue here is that s1.is_valid() always comes out to be False and I can't save s1 as a serializer. I'm getting this error: >>> d {'username': 'user001', 'password': 'pass001', 'email': 'user001@example.com', 'contact': 9876543210} >>> s001=UserInfoSerializer(data=d) >>> s001.is_valid() False >>> s001.validated_data() Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'dict' object is not callable >>> s001.validated_data {} >>> s001.data {'username': 'user001', 'password': 'pass001', 'email': 'user001@example.com', 'contact': 9876543210} >>> s001.save() Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/imharjyotbagga/PycharmProjects/DRF/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 182, in save 'You cannot call `.save()` on a serializer with invalid data.' AssertionError: You cannot call `.save()` on a serializer with invalid data. >>> So how can I go about this!? -
Django best practice combain REST API with Web application or sperate the both?
I am currently working on a Project with Django backend and Flutter frontend. Know we have to do a Web application for the admin for adding data to the Rest framework/Database (excluding the admin panel). My question is, should I add the web application to the existing API project or should I start a completely new Project. -
Django 400: Bad Request This field is required
I'm developing a REST API with Django and the restframework-json-api package. I make the following request curl --location --request POST 'http://localhost:8000/api/students/' \ --header 'Content-Type: application/json' \ --data-raw '{ "data": { "type": "students", "attributes": { "first_name": "First Name", "last_name": "Last Name" } } }' And I get this response { "errors": [ { "detail": "This field is required.", "status": "400", "source": { "pointer": "/data/attributes/first_name" }, "code": "required" } ] } This is my code: models.py class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('first_name',) views.py class StudentsViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() parser_classes = (JSONParser, FormParser, MultiPartParser) serializer_class = StudentSerializer urls.py router = routers.DefaultRouter() router.register(r'students', views.StudentsViewSet, 'student') urlpatterns = [ path('', views.index, name='index'), path('api/', include(router.urls)) ] settings.py REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework_json_api.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ) } If I instead dont use the JSONParser and use the normal django request format instead of Json API it works fine. What am I missing? -
how to copy the value of a 'textarea' and insert it to other html template? django
I'm trying to copy the value of a 'textarea' input (where the user provides a text) and use it as it is in a "draft page" before posting it. I won't paste here all my code but the relevant things. First of all I'm using Django Framework, and I added to the base.html template the Jquery script. In other html template called 'userblog' I added a mini text editor where 1 of his elements is 'textarea' input. <div id="textBox" contenteditable="true" name="post_content"><p>Lorem ipsum</p></div> And in the draft.html I wrote: {% extends "TheApp/base.html" %} {% load static %} {% block body_block %} <div class="container"> <h1>This is a preview of you're post: <script type="text/javascript" src="userblog.html"> document.write(textAreaContent) </script> </h1> {% endblock %} The problem is that it does not display my text area content.. whats wrong in my code? I'm new to this, I learn a bit python and the Django framework.. towards the process i touched a bit of HTML & CSS but I know almost nothing about JS.. -
Page Customizer such as wordpress
I'm making a site with django.I want to edit the articles on the page. How do you do wordpress-like editing. wordpress I can save data with a form, but how to select the data. I want to have the edit icon on the data vue.js or js or react ? -
Django log_update() got multiple values for argument 'user'
I'm getting TypeError log_update() got multiple values for argument 'user' when trying to create an instance in the database. Constructor class ChangeLogManager(models.Manager): use_in_migration = True def log_update(user, content_type, object_id, content_object, changes, date_of_change): return self.model.objects.create( user = user, content_type = content_type, object_id = object_id, content_object = content_object, changes = changes, date_of_change = date_of_change, ) views def editUser(request, pk): # Query appropriate user based on pk returned in url user = User.objects.get(pk = pk) # Get the EditUserForm and add the user as instance edit_user_form = EditUserForm(instance = user) if request.method == 'POST': # Bind data to the form class, and add the user as instance edit_user_form = EditUserForm(request.POST, error_class=DivErrorList, instance = user) old_user_instance = User.objects.get(pk = pk) # Validate form inputs if edit_user_form.is_valid(): # Save edits edit_user_form.save() # Log change ChangeLog.change_message(request.user.id, User, old_user_instance) else: # error context = { 'user': user, 'edit_user_form': edit_user_form, } # Render request, template and context return render(request, 'users/backend/user/user_edit.html', context) method def change_message(request, obj, old_instance): new_instance = obj.objects.get(pk = old_instance.pk) ct = ContentType.objects.get_for_model(new_instance) for field in obj._meta.get_fields(): if isinstance(field, models.ManyToOneRel): continue old_value = getattr(old_instance, field.name) new_value = getattr(new_instance, field.name) if old_value != new_value: change_message = json.dumps({"field": field.name, "old_value": old_value, "new_value": new_value}) ChangeLog.objects.log_update( user = request, content_type = … -
How to display model's primary key in django during update
In some of my models I have used the primary key defined by the system (Django) whereas in some others I have defined my own primary keys. In the second instance (i.e. for models with custom primary keys), while updating / changing a record, I am able to show the primary key (as a readonly field) in the page being presented to the user (through a template). This is what I am unable to replicate for models with system defined primary key. In the image below, the supplier ID field is a custom id field and can be displayed in the page. In the second instance shown below, I have not defined custom id and the update page looks like this: Is there at all some way to display the primary key field value to the user while updating a record, albeit as a readonly field? -
What is correct/Pythonic way to change a setting in an imported package?
What is correct/Pythonic way to change a setting in an imported package? For example, I want to change the DEFAULT_PROTOCOL value to 0 (zero) in the constants.py file in django-picklefield for use in conjunction with django-constance. But more than just this example, I have several cases in Mezzanine and Cartridge among other imported packages where I want to change a value in their settings.py or another file. Do I need to fork the package repository, make my changes and import the local modified package in my project? Thanks. -
Configuring nginx with Superviser
When I host my django application in AWS EC2 instance it was able to run on gunicorn but on configuring nginx with supervisor I had created django.conf file which is as below django.conf server{ listen 80; server_name ec2-16-216-111-33.us-west-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Duklr-web/app.sock; } } But I am getting the error: nginx: [emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 64. So how should I modify my django.conf file to resolve the issue. -
Don't understand Django's ORM - Models
As I'm having some spare time these days I decided that it would be nice to learn a new language. So I picked python because of its popularity and because I got interested in Django. Some hours later, despite all syntax related difficulties derived from a new language, I manage to make a simple backend logic design (what my "app" should do). The next step now was to introduce my code to Django to finally make that logic "real" in a way and to also learn some HTML, CSS in the process. After following Django's official tutorial I felt I learned enough to get my project started. Before I start talking about Django's ORM I want to say that, from what I've seen and learned in the tutorials, I totally enjoyed all Django's web-related utilities (views, paths, templates). They seem, at least for now, really easy to learn and simple to use. Now about the ORM. First of all, I feel that it is necessary to clarify that it's the second ORM I use in my life; the first one I used was Java's JPA in one of my courses to learn about them. From what I've learned using JPA, … -
Django: ImportError: cannot import name 'Celery' from 'celery'
So I've installed celery and got the file celery_tasks_settings.py in my project directory next to settings.py. This I got was a way to avoid conflicts with the package itself. I also did find -name '*celery*.pyc' as a way to find any celery.pyc files that may have been generated before.The result: /__pycache__/celery_tasks.cpython-38.pyc /__pycache__/celery_tasks_settings.cpython-38.pyc Unfortunately, I still get the same error: from celery import Celery ImportError: cannot import name 'Celery' from 'celery' Am I doing something wrong? PS: I also went ahead and tried adding: from __future__ import absolute_import, unicode_literals to my celery_tasks_settings.py My error still won't budge. -
Django update table data using ajax
I'm trying to filter table data and then update the table using ajax. I have: filter form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input type="text" class="form-control" id="tokenfield1" name="txtSearch"> <button type="submit" class="btn btn-default js-filter">Submit</button> </form> views.py def article_filter(request): data = dict() if request.method == 'POST': search = request.POST.get('txtSearch') articles = Article.objects.filter(title = search) context = { 'articles': articles } data['html_table'] = render_to_string('blog/article_table.html', context, request = request ) return JsonResponse(data) ajax handler: <script> var filter = function() { $.ajax({ type: "POST", url: "blog/article-filter", dataType: 'json', success: function(response) { $('#article-table').html(response.html_table); } }); }; $("#search").on("submit", ".js-filter", filter); </script> But when I submit the form, it only prints out raw html text (the table), how do I actually replace the table within the page and render it? -
Dynamic wagtail streamblock additions to structblock
Let's say I have: class PageLink: page = ... add_child_pages = Boolean Now, if add_child_pages is True: I want to inject a child block (as a StreamBlock named items) so that I can use a reusable template as such: .. render normally {% if add_child_pages %} {% include 'my reusable template' %} To render the child items {% endif %} Which contains {% for item in self.items %} {% include_block item %} {% endfor %} Is this even possible? Essentially you'd have to do: if page: public_children = page.get_children().live().public() Which is fine... It's converting this to a Wagtail structure that gets rendered I'm stumped on. These need to go to PageLink objects themselves. But, doing class PageStructValue: @property def items(self): yield a bunch of `PageLink` objects with the PageLink().meta.default = {values} doesn't work. everything just shows as a string. -
npm: command not found - Gitlab CI specific runner
I am running gitlab-runner on my server, I am not using docker for deployment. I am trying to achieve the deployment on a remote server by doing ssh to the server. This is my .gitlab-ci.yml file - stages: - deploy pre-staging: stage: deploy environment: name: Gitlab CI/CD for pre-staging deployment url: "$REMOTE_SERVER" before_script: - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )' - mkdir -p ~/.ssh - eval $(ssh-agent -s) - 'echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config' script: - ssh-add <(echo "$REMOTE_PVT_KEY") - ssh ubuntu@"$REMOTE_SERVER" "cd deployment_container; npm --version ;rm -rf static; source deploy.sh" - echo "Deployment completed" only: - megre_requests - pre-staging tags: - auto-deploy My pipeline is failing with error npm: command not found. I have proper environment for npm on my ssh-ed server. I am trying to deploy the Django-react application. I have already tried using image: node:latest. npm is installed using nvm Can somebody help me resolve this? -
Djano/MySQL Unique Constraint how to treat NULLs as equal
I have a Django model which has a recursive field. A simplified version is below. The idea is roughly to have a tree data structure in sql. The problem which I have is that, apparently, Django does not treat NULLs as equal. The problem now is that, since every tree's root has a 'null pointer' by necessity, I can have two identical trees but Django will treat them as different because of the NULL value. How can I implement the UniqueConstraint below so that two 'Link' objects with NULL link values and equal node values will be treated as identical, and fail the UniqueConstraint test? Thank you. class Link(models.Model): node = models.ForeignKey(Node, on_delete=models.CASCADE) link = models.ForeignKey('self', on_delete = models.CASCADE, null=True) class Meta: constraints = [ models.UniqueConstraint(['node', 'link'], name='pipe_unique') ] -
What's the best way to post multiple forms of same model in this situation?
I'm trying to post multiple forms of the same model in one submission. So, I have a model "Task" which has a name, a category and a property field. I have also a model named "Task Check" which has a task and a status. The purpose of task check is to save the status of one task, like "done" or "checked" as can be seen below: models.py class Task(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Categories) property = models.ManyToManyField(Property) class TaskCheck(models.Model): status = models.CharField(choices=STATUS_CHOICES, default='nd', max_length=50) image = models.ImageField(upload_to='task_check', blank=True, null=True) notes = models.TextField(max_length=500, blank=True) task = models.ForeignKey(Task) property_check = models.ForeignKey(Propertycheck) class Propertycheck(models.Model): property = models.ForeignKey(Property, models.DO_NOTHING) name = models.CharField(max_length=150) date = models.DateField(default=timezone.now) next_visit = models.DateField() staff = models.ForeignKey(User, max_length=25) notes = models.TextField(max_length=500, blank=True) As can be seen in the models above, a TaskCheck is related to One PropertyCheck, the purpose of the "PropertyCheck" is to save a set of taskchecks. Functional Example: Someone goes to a property to check if everything is ok, he adds a PropertyCheck and then the list of TaskCheck's of every Task related to that property. My template looks like this: {% for obj in task %} {% if obj.category == cat %} <div class="form-group"> <div … -
easy-thumbnails saving to S3 Bucket
I'm trying to use easy-thumbnails in a Django app using an S3 bucket. I'm trying to display thee images in a carousel as following: {% for image in organisation.photos %} <div class="carousel-item{% if forloop.first %} active{% endif %}"> <img class="d-block w-100" src="{% thumbnail image.file 'carousel_image' subject_location=image.file.subject_location %}" alt="{{ image.name }}"> </div> {% endfor %} If the image exists it is downloaded fine, but if it doesn't exists I'm getting a 404 Not Found message for the images whereas I'm expecting them to be generated. Is there something I'm missing here or something with S3 Bucket permissions I need to add to allow easy-thumbnails to create the images? -
How to chain queries in django view
Hello there is a specific problem that i am trying to solve. Im making a tasking system that is built on 3 models , the taskings model , the extended user model(profile) , and the django default User model. Here are my models class Sales_taskings(models.Model): sales_status= ( ('p1','Phase 1'), ('p2','Phase 2'), ('p3','Phase 3'), ('p4','Phase 4'), ) task_id = models.AutoField(primary_key=True) sales_extras= models.ManyToManyField('sales.Sales_extras') sales_project= models.ForeignKey('sales.Sales_project',on_delete=models.CASCADE) description = models.TextField(max_length=200 , default='your notes' ) date_time = models.DateTimeField(auto_now=True) status = models.TextField(max_length=10, choices= sales_status ,default='p1') class Sales_extras(models.Model): role= ( ('sm','sales_manager'), ('s','sales'), ) user = models.OneToOneField(User,on_delete=models.CASCADE) user_type = models.TextField(max_length=500, choices= role) here is my view with context @login_required def sales_taskboard(request): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] sales_extras_id = Sales_taskings.objects.values('sales_extras').get('username') print(Sales_taskings.objects.values('sales_extras')) usernames = User.objects.values('username').filter(id__in = sales_extras_id) print(usernames) context = { 'sales_task' : Sales_taskings.objects.all(), 'sales_extras' : Sales_taskings.objects.values('sales_extras'), 'usernames' : usernames } return render(request, 'sales/taskboard.html',context) Sorry i am new to django , above is me trying ways to get the username out. I feel like there should be a built in query method that enables me to link my sales_takings model and my sales_extras model and finally to my User model . Your help will be greatly appreciated! -
How to get correct JSON responce from my app on Heroku?
I have a test django application on Heroku what returns this by /api/test/?format=json request And I try to get it in frontend part whith this code let url = "https://morning-thicket-20719.herokuapp.com"; async function getData() { let response = await fetch(url + '/api/test/?format=json'); let data = await response; return data; } getData().then(data => console.log(data)); and get in console this message: Access to fetch at 'https://morning-thicket-20719.herokuapp.com/api/test/?format=json' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. How to solve this problem? Is problem in my django app? -
Django Live Video Chat
Is it possible to make a Live Streaming system like Video Call and Audio Call ? If it is, Please give some Tips or any resources to get started on it. -
Why can't I acces the django admin site?
I'm new to Django and trying to learn it. So I have created a superuser with python manage.py createsuperuser in the terminal and created username and password. When i try to login with i fail. I manage to get to the django http://127.0.0.1:8000/ site and the login django site, but I can't login even though the the username and password is correct. I have searched on google and checked that my Django server is running. It is on. Here is my setting.py file: """ Django settings for learning_log project. Generated by 'django-admin startproject' using Django 3.0.1. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'mdsezf)hzjg&(l=c06u5t99-!d!%-k@576yd2ct@lgl@@%eg2m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'learning_logs', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = … -
DJANGO How to filter queryset with ListView?
I'm currently building a website with Django and my problem is the following : I have a page, home, whose goal is to display all Plat objects in the database (Plat is a model from the database). What I want is having kind of a filtering table next to the list, which enables to filter the objects on various attributes. For example, we could filter the objects with a price greater than 10 euros, or the objects with a certain attribute lower than 5, or both at the same time. I'm a little bit lost on how to proceed to do that. First of all, here are the relevant parts of my files : views.py class home(ListView): model = Plat context_object_name = "plats" template_name = "actualites/home.html" paginate_by = 9 urls.py urlpatterns = [ path('home', views.home.as_view(), name = 'home'), ] The home.html file is made with bootstrap and is really big so I will not display it since I don't think it's much useful. A solution to my problem may be to put parameters in the url path('home/<int:price>', views.home.as_view(), name = 'home'), and overwrite get_queryset in the home view def get_queryset(self): return Plat.objects.filter(prix=self.kwargs['price']) The problem is that the filtering can be … -
Django package for CSV auto detection?
I'm making a website in Django where users can upload CSV-files of their bank transactions. Due to different using banks users will upload different CSV-formats. Eg: - "Date";"Text";"Amount" - "Date";"Text";"";"";"";"Amount";"Category";"Subcategory" - "Date";"";"";"";"Text";"Amount";"Category";"Subcategory" And so on. All CSV-formats will contain at least: - Date (Could be any date format though) - Text - Amount Some also includ - Category - Subcategory Is there a python/Django package which will help automatize the recognition of each field - and maybe even supply users with a tool for changing the detected fields? Eg: Switch the Text, Category and Subcategory fields as they might get mapped incorrectly.