Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert string to list in python. Like "['a']" to ['a']
I get list form database as a string. But how to convert string to list. For example I get '["a","b"]' but it is string format how to convert it ["b","b"]. i was also trying list() method. userf = user.pending print(userf) #userf is "['animation']" userf.append(tosend).save() -
I am unable to connect one of the .html files from the quiz application to the django application. (Page not found (404))
I have a quiz app (QuizApp) inside my django app. (basic_app) Everything is working fine up to the moment, where the game ends and the quiz_end.html page is not displaying. Here is a link to quiz_game.js inside the quiz_game.html file - (quiz_js is in this case a folder situated inside the django´s static folder) <script src="{% static "quiz_js/quiz_game.js" %}"> Here is some kind of link to the end.html file inside the quiz_game.js file - (the game is finished, when there are no questions left) if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) { localStorage.setItem("mostRecentScore", score); //go to the end page return window.location.assign("/end.html"); }; (You can see the full code of this file here - https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript/blob/master/Quiz%20App%20Master/game.js - it´s just called game.js instead of quiz_game.js + You can see all of the files from the Quiz App here - https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript/tree/master/Quiz%20App%20Master) But since I am using Django, I was trying to incorporate template tag into the quiz_game.js file like this - (I am not sure, if I am doing it right) getNewQuestion = () => { if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) { localStorage.setItem("mostRecentScore", score); //go to the end page return window.location.assign("{% url 'quiz_end' %}"); }; The thing is, that this … -
Django + Nginx + Uwsgi see Nginx default page then run on 80 port
I have Django app that runs on VPS using Nginx + Uwsgi. The Symlink nginx config # the upstream component nginx needs to connect to upstream django { server unix:///root/ubergf/client/uwsgi_nginx.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name my-site.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /root/ubergf/client/media; # your Django project's media files - amend as required } location /static { alias /root/ubergf/client/staticfiles; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /root/ubergf/client/deployment/uwsgi_params; # the uwsgi_params file you installed } } uwsgi_params uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME … -
Splitting a monolith file Django
First to set the scene a little. I am working on piece of software that has been worked on by a number of developers over the years, each making improvements, and compromises along the way. We have about 30 apps in the project, but about 60% of all of the code is in one models file. In recent years we have been moving away from this monolithic architecture, but we have not had the time/willingness to actually spilt this file up. It is causing issues just loading and searching the file at the moment. I am looking for any advice or strategies that could help with this. I have been looking into three methods/paths, but I am not sure if they are a good idea, or if there is a better one. Moving Models out 1-by-1. Hard code in the database name, and then overwrite the migration so no data is deleted, and move out each model one by one to their new home. Make the file into a directory. Instead of being one file, split this up into a number of files. This will alleviate the current issues we are having with the file size. And will also spilt … -
`basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute
I'm new in Django stuff and would like to build an API Server. However, when I register the ModelViewSet I get the error shown in the title. Model: from django.db import models from django.core.exceptions import ValidationError class User(models.Model): telegram_id = models.CharField(max_length=50) mail = models.CharField(max_length=100, default="None") password = models.CharField(max_length=100, default="None") is_group = models.BooleanField(default=False) priority = models.IntegerField(default=10) max_watches = models.IntegerField(default=5) current_watches = models.IntegerField(default=0) notification_rate = models.IntegerField(default=3600) watches = models.ManyToManyField('Url', through="Watch") def save(self, *args, **kwargs): if self.current_watches > self.max_watches: raise ValidationError("Límite de enlaces alcanzado") super().save(*args, **kwargs) def __str__(self): return self.telegram_id Serializer: from rest_framework import serializers from hermes.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' ViewSet: from rest_framework import viewsets import hermes.models as models import hermes.serializers.UserSerializer as UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = UserSerializer router: from hermes.ViewSets import UserViewSet from rest_framework import routers router = routers.DefaultRouter() router.register(r'users/', UserViewSet) router in app: from django.contrib import admin from django.urls import path, include from hermes.urls import router urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) ] I have also added the basename param at the end of the router as it suggested me but is fails again saying that it has no attribute get_extra_actions. And when I define that method it … -
Reduce the range of minutes displayed in the user form. Django
I have a problem with the correct display of data picker for the user, exactly I mean if I am able to reduce the range of displayed time to choose this is my forms.py file class EventForm(ModelForm): class Meta: model = Event widgets = { 'start_time': DataInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DataInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M',), } exclude = ['user'] # def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',) In the template, the user has a choice of dates and times from this range Is it possible to add some restrictions when selecting dates, e.g. selecting only days of a given month or only days of a given week? The same question about time selection e.g. am I able to limit the range only to 9:00-9:30 with a half-hour interval and not with a minute interval -
django formset not valid in edit mode
i can save a formset in post method, but when i try to edit it in my "put" method, my formset.is_valid returns false ... i excluded some logic in this code samples and replaced it with .... so it is easier to read... hope this is enough information to get an idea of my problem my view.py class AngebotView(View): def get(self, request, id=None): if id: ................. raum_formset = RaumFormSet(queryset=objekt.t_raum_set.all()) raum_formset.extra = 0 template = 'angebot/edit_angebot.html' else: ..................... # Create an instance of the formset raum_formset = RaumFormSet(queryset=T_Raum.objects.none()) template = 'angebot/new_angebot.html' context = {'kunde_form': kunde_form ,'angebot_form': angebot_form, 'objekt_form': objekt_form, 'raum_formset': raum_formset} return render(request, template, context) def post(self, request, id=None): # Post = Speichern/Ändern context = {} if id: return self.put(request, id) #Forms aus Request holen kunde_form = KundeForm(request.POST, instance=T_Kunde()) angebot_form = AngebotForm(request.POST, instance=T_Angebot()) objekt_form = ObjektForm(request.POST, instance=T_Objekt()) formset_raum = RaumFormSet(data=self.request.POST) #wenn die Eingabe der Formen passt if kunde_form.is_valid() and angebot_form.is_valid() \ and objekt_form.is_valid() \ and formset_raum.is_valid(): .................. #Alle Instanzen des Formsets in raum_instances #Mit den Instanzen kann man dann weiterarbeiten, Foreign Key setzen etc... raum_instances = formset_raum.save(commit=False) for new_raum in raum_instances: new_raum.objektid = new_objekt new_raum.save() messages.success(request, 'Angebot wurde gespeichert!') return HttpResponseRedirect(reverse('angebot:angebot_details', kwargs={'id': new_angebot.id})) else: #TODO: Errorhandling raise Http404 context = {'angebot_form': … -
How do I make this appear in Djanog-Python?
I'm currently in the process of building a hospital management app with using Django and Python In the index page, I want to show the total patient numbers, yet the code I've inputted does not make that happen. Also, I've cut most of the HTML code for this since the full code went over the word count limit. The following are the code: index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Lifesaver</title> <!-- Custom fonts for this template--> <!-- <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> --> <link href="{% static 'startbootstrap-sb-admin-2-gh-pages/vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <!-- <link href="css/sb-admin-2.min.css" rel="stylesheet"> --> <link href="{% static 'startbootstrap-sb-admin-2-gh-pages/css/sb-admin-2.css' %}" rel="stylesheet"> </head> <body> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <!-- {% include 'lifesaver/sidebar.html' %} --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-laugh-wink"></i> </div> <div class="sidebar-brand-text mx-3">LifeSaver </ul><div> </a> <!-- Divider --> <hr class="sidebar-divider my-0"> <!-- Nav Item - Dashboard --> {% include 'lifesaver/navbar_user.html' %} </ul> <!-- End of Sidebar --> <!-- Content … -
Users are not highlighted when they presses the like button and also doesn't show the count of likes ..in django. Can You suggest me any solution
registration and login page is working properly but mine like button is not working it doesn't highlight users who presses like button and also doesn't show the count of like .. I don't know why... Can somebody help me to solve this issue … it will be great help please help Thank you! Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required # Create your views here. @login_required def likes(request, pk): post = get_object_or_404(Post, id=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity', args=str(pk))) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} def __init__(self, *args, **kwargs): stuff = get_object_or_404(Post, id = self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() context={"post":post} return render(request, "datasecurity/blogHome.html", context) 2.urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"), ] Models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes = models.ManyToManyField(User, related_name='likes') @property def total_likes(self): return self.likes.count() def __str__(self): return self.title + … -
How to arrange multiple files size into single HTML card?
I want to arrange multiple items (photo/videos) size in single HTML card like facebook or instagram: . Here is the layout: when i upload items in Django. i want to know is there any kinds of library or javaScript code do what i have to do? i want the items auto arrange according to the size contain without extending the card size? here is the source code of my layout.. <div class="panel-image"> {% for i in object.filemodel_set.all %} <img src="{{i.file.url}}" alt="article" class="img-responsive card-img-top"> {% endfor %} </div> -
How to send email by godaddy email account in django?
I want to send mails by my godaddy email account. The function which i have created in veiws.py , That is working perfectly with gmail account but not sending emails from my godaddys' email. Please tell me whats the possible mistake im making here. views.py(functions to send verifcation code) class SignUp(CreateView): form_class = UserCreateForm template_name = 'accounts/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Dotescrow Account' html_message = loader.render_to_string('accounts/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject,'message' ,fail_silently=True,html_message=html_message) messages.success(request, 'Please verify you email to activate you account.') return redirect('accounts:signup') return render(request, self.template_name, {'form': form}) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.bussicess.net' EMAIL_HOST_USER = 'no-reply@bussicess.net' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_USE_TLS = False If more code is require then tell me in comment sessions. Thank you. -
Django - can I have 2 many to many fields to another model?
I'm developing an application that has the following three models: Student, Subject and Skills. A Student can have many skills, and a Skill can have many student. A Subject can offer 0 or many skills after a Student complete it, however, a Student has to have 0 or many skills required to complete a Subject. I tried doing the following: Subject class Subject(models.Model): name = models.CharField(max_length=50, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='subjects', default=0) code = models.CharField(primary_key=True,verbose_name='Code', max_length=50) description = models.CharField(max_length=100, blank=True) offered_skills = models.ManyToManyField(Skill, related_name='subjects_o', blank=True) required_skills = models.ManyToManyField(Skill, related_name='subjects_r', blank=True) Skill class Skill(models.Model): code = models.CharField(primary_key=True,verbose_name='Code', max_length=50) name = models.CharField(max_length=50, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='skills', default=0) description = models.CharField(max_length=100, blank=True) students = models.ManyToManyField(Student, related_name='skills', blank=True) Student class Student(models.Model): code = models.CharField(primary_key=True, verbose_name='Codigo', max_length=50) name = models.CharField(max_length=50, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='students', default=0) description = models.CharField(max_length=100, blank=True) When I try makemigrations it leads me to the following error: Traceback (most recent call last): File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1149, in __init__ to._meta AttributeError: module 'dashboard.models.Skill' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line … -
Get QuerySet from ForeignKey in Django
I have two models in Django: class Category(models.Model) .... class Article(models.Model) category=models.ForeignKey(Category,on_delete=models.CASCADE,blank=True,null=True) I would like to get some categories with some filter, and all the articles of this Category in the same Query. I try with annotate, but I do not know how is the correct syntax. categories = Category.objets.filter(whatever='whatever').annotate('article') -
DRF Permission class IsAuthenticated isn't working with React js JWT authentication
I've created an authentication app using React and Django REST. It works fine when create account and login. But it doesn't work when I want to view something after login with IsAuthenticated permission class. It shows the error as the image. . It works fine without permission. REST permission and JWT settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } # jwt permission SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=14), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADERS_TYPES': ('JWT',), 'USER_ID_FIELDS': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', } And React code: Home view import React, { Component } from "react" import axiosInstance from "../AxiosApi" export default class Home extends Component { constructor() { super() this.state = { aboutData: [] } } getData = async () => { try { const response = await axiosInstance.get("/v1/about/") this.setState({ aboutData: response.data }) return response.data } catch (error) { console.log("Error: ", JSON.stringify(error, null, 4)) throw error } } componentDidMount() { const data = this.getData() console.log(data) } render() { return ( <div> {this.state.aboutData.map((item) => ( <div key={item.id}> <h2>Name: {item.name}</h2> <p>Address: {item.address}</p> <p>Phone Number: {item.phone_no}</p> <br></br> </div> ))} </div> ) } } AxiosInstance import axios from "axios" const baseURL = … -
Overriding a view.py file in an external Django package
I am working on a Django project and had to install a package with pip: 'authemail'. I want to override the view.py file and the serializers.py in this package. So I can customize the code without touching the package. What is the best way to do this? -
Django Design Pattern To Get Specific Objects Of Models
I am wondering if there is a design pattern or best practice to allow a Django-programmer to easily and safely get specific objects of a model. Let me explain the question by an example: I have a model with classes Pattern and Sequence. class Pattern(models.Model): name_id = models.CharField(max_length=50, unique=True) sequence = models.CharField(max_length=50) class Sequence(models.Model): sequence = models.CharField(max_length=1000) The database is initialized with several Patterns which will be used in methods that check for specific patterns within the objects of class Sequence. Let's say we build them like so: Pattern.objects.create(name_id="the_a_pattern", sequence="DEF") Pattern.objects.create(name_id="the_b_pattern", sequence="GF") Now I want a safe way to get these Patterns when writing new code, without having to remember the exact id of the pattern. Instead of Pattern.objects.get(name_id='the_a_pattern') I want to get help by Code Completion and use something like Pattern.get_the_a_pattern. My first approach was to include get-methods in the model, but this will blow up the model very quickly and is not very well maintainable: class Pattern(models.Model): name_id = models.CharField(max_length=50, unique=True) sequence = models.CharField(max_length=50) @staticmethod def get_the_a_pattern(): return Pattern.objects.get(name_id='the_a_pattern') Since I couldn't find a good solution in the www, although I'm sure that this is a very common problem, I would appreciate any suggestions for a better design. -
Why I am getting net::ERR_ABORTED 404 (Not Found) in my django project?
I have downloaded a template from online which has these files- index.html gallery.html generic.html I tried to connect these files into my django project.my django settings.py is: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6+!*vrjoh*c56kf4u#1+7q=!t&yr6jbakf*8!d^)g-rgvj3w-_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', '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 = 'projectapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'projectapp.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True … -
NoReverseMatch at / 'QuizApp' is not a registered namespace inside 'basic_app'
I want to connect my basic_app with an index.html (index.html of my quiz app) file, which is inside the basic_app folder, but it is situated like this basic_app/QuizApp/index.html and this problem is probably about the principle of having another folders in my basic_app folder and calling the .html files from there, which is something I am struggling with. This is my view - def quizindex(request): return render(request,'basic_app/QuizApp/index.html') This is the corresponding urlpattern - url(r'^quizindex/$', views.quizindex, name='quizindex'), And this is the anchor tag situated on my homepage, (main index.html situated like this - basic_app/index.html) which points to the actual index.html of the Quiz - (I am honestly not sure, if the following code is written in a right manner) <a href="{% url 'basic_app:QuizApp:register' %}">QUIZ</a> The error I am having is described in the title. I know, that this is kind of beginner problem, but I would really appreciate some genuine help. Could anybody please give me some hint on how to fix this? Thank You very much in advance. -
Modify form field depending on other field in Django
I have a form including several fields. Let's say one of them is "subjects", a multiple choice selection field, and the other one is "main_subject", a single choice selection field. How should I code the views.py file in order to automatically select a subject in the "subjects" one, if the corresponding "main_subject" is selected? (I do not want to save a main subject for a student if it isn't included as one of his subjects). models.py class Subject(models.Model): subject=models.CharField(primary_key=True, max_length=100) class Student(models.Model): name=models.CharField(primary_key=True, max_length=100) main_subject=models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True) class StudentSubject(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Discipline, on_delete=models.CASCADE) class Meta: constraints = [models.UniqueConstraint(fields=['name ', 'subject '], name='uniqueStudentSubject')] forms.py class NewStudentForm(forms.ModelForm): class Meta: model=Student fields=['name', 'main_subject'] widgets={'name': forms.TextInput(), 'main_subject': forms.Select()} subjects = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Subject.objects.all(), required=False ) views.py def new_student(request): if request.method == 'POST': form = NewStudentForm(request.POST) if form.is_valid(): form.save(commit=True) for stu in form.cleaned_data['subjects']: StudentSubject.objects.create( name=Project.objects.get(pk=request.POST['name']), subject=Subject.objects.get(pk=stu) ) # SOMETHING ELSE......... # -
Deploy django + react on cpanel
I follow this tutorial on how to implement react on my django project https://www.valentinog.com/blog/drf/#Django_REST_with_React_Django_and_React_together Right now, I am trying to deploy it on cpanel. And I dont have any idea how to it. Please let me know if theres any tutorial I can use. Thanks -
Hightlight buttons on click with CSS
I have a multiple selection and would like to be able to click on it to manage the answers on a /getmatch page. At the moment I have no visual cue that I have selected things: []]1 So how to make the selection of multiple items responsive? Here is the code from the page that gives these buttons: {% extends "todo/base.html" %} {% block content %} <style> .elements { display: block; } ul.items { display: flex; margin: 0; padding: 0; list-style: none; } li.item { flex: 1 0 20%; padding: 8px; margin: 2px; border-radius: 8px; border: 1px solid rgba(61, 86, 233, 0.3); text-align: center; } .col { display: flex; flex-direction: column; align-items: center; } </style> <!-- Header --> <header class="intro-header"> <div class="container"> <div class="col-lg-5 mr-auto order-lg-2"> <h3><br>Tell me something about you... </h3> </div> </div> </header> <!-- Page Content --> <section class="content-section-a"> <div class="container"> <dt> <span>Pick the keywords you want to express when wearing perfume</span> </dt> <form action = "/getmatch" method="POST"> {% for keyword in keywords %} <div class="elements"> <ul class="items "> <li class="item col-xs-6 col-sm-3 col-md-3 col-lg-3"> <div class="box"> <div data-toogle="buttons" class="col"> <span>{{ keyword.title }}</span> </div> </div> </li> </ul> </div> {% endfor %} {% csrf_token %} <button type="submit">Envoyer</button> </form> </div> … -
Google SMTP service daily limit
I am using Google's SMTP service (smtp.gmail.com) in my Django project for sending account activation emails for new users. I have went through this page but not quite sure what exactly is Google's SMTP outgoing quota per day with regard my gmail account's setup. I am using only a regular Gmail account (it's not subscribed to any of Google's premium services). -
NOT NULL constraint failed error when using createview in django
I am trying to create a new entry in my model using createview. the model Venue is in a onetone relation with Adress model and I cannot get it to upate that model. I have tried to use a custom form but I always get the following error: IntegrityError at /evcreate/ NOT NULL constraint failed: kammem_person.padress_id form.py: class AdressForm(ModelForm): street=CharField(max_length=100) snumb=CharField(max_length=15) town=CharField(max_length=100) postn=CharField(max_length=5,validators=[postnvali]) class Meta: model=Person exclude=['padress'] view: class EvCreate(CreateView): form_class=AdressForm template_name='kammem/create.html' success_url=reverse_lazy('event') def form_valid(self,form): street=form.cleaned_data['street'] snumb=form.cleaned_data['snumb'] town=form.cleaned_data['street'] postn=form.cleaned_data['postn'] form.vadress=Adress.objects.create(street=street,snumb=snumb,town=town,postn=postn) return super().form_valid(form) models.py class Person(Model): fname=CharField(default="missing",max_length=100) lname=CharField(default="missing",max_length=100) mobil=PhoneField(default='9999999999') mail=EmailField(default='contact@gmail.com') padress=OneToOneField(Adress,on_delete=CASCADE,primary_key=True) def __str__(self): return self.fname class Meta: ordering=('fname','lname') class Venue(Model): vname=CharField(default="",max_length=100) vamil=EmailField(default='contact@gmail.com') vpage=CharField(default='homepage',max_length=100) vadress=OneToOneField(Adress,on_delete=CASCADE,,primary_key=True) def __str__(self): return 'Venue: ' + self.vname url.py path('evcreate/',EvCreate.as_view(),name='evcreate'), I have really searched for an answer but with no succes. Any clues? -
why is day out of range?
i am trying to add a date to an application that I am writing. the apllication is actualy a list of activities. when i tried to add a datefield to the ui and save it into my database. i got this error ValueError: day is out of range for month this is my model class Vergadering(models.Model): kriskras = models.ForeignKey(Kriskras, on_delete=models.CASCADE) date = models.DateField(("Date"), default=datetime.date.today) extra = models.CharField(max_length=5) activiteit = models.CharField(max_length=500) def __str__(self): return self.activiteit this is my html page {% for vergadering in ls.vergadering_set.all %} <div class="input-group mb-3"> <input type="date", value="{{vergadering.date}}" class="form-control col-2" name="d{{vergadering.id}}"> <input type="text", value="{{vergadering}}" class="form-control" name="c{{vergadering.id}}"> </div> {% endfor %} and this is my view def index(response, id): ls = Kriskras.objects.get(id=id) if response.method == "POST": print(response.POST) if response.POST.get("wijzig"): print("wijzig") for vergadering in ls.vergadering_set.all(): pass elif response.POST.get("newVergadering"): txt = response.POST.get("new") date = response.POST.get("newdate") if len(txt) > 2: ls.vergadering_set.create(activiteit=txt, date=date) else: print("invalid") return render(response, "main/kriskras.html", {"ls":ls}) i cant figure out why this is raising, i think it has something to do with the date format? -
How to change rtl direction to ltr in codesample plugin of tinymce
My Django-TinyMCE direction has turned rtl due to my language and everything looks fine except the codesample plugin which has gotten rtl and scrambles the code. I would appreciate anyone help me figure this out. I want code sample to be ltr while everything else is rtl. Thanks in advance images ... rtl text editor I want rtl to ltr