Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access to attrbuite of another model or table using ManyToMany in django
Please, I need your help. How can I access to attribut of another model or table using ManyToMany I need to get data through this method but it's not retrieved ---=> this is Models.py class Mission(models.Model): nom=models.CharField(max_length=50,null=False,blank=False) description=models.CharField(max_length=150,null=False,blank=False) date_publier=models.DateTimeField() class Participer(models.Model): id_benevole = models.ManyToManyField(User) id_mission = models.ManyToManyField(Mission) est_participer = models.BooleanField(default=False) class User(AbstractUser): est_association = models.BooleanField(default=False) est_benevolat = models.BooleanField(default=False) username = models.CharField(max_length=30,unique=True) email = models.EmailField() password1 = models.CharField(max_length=20,null=True) password2 = models.CharField(max_length=20,null=True) class ProfileBenevole(models.Model): user = models.OneToOneField(User,related_name="benevole", on_delete = models.CASCADE, primary_key = True) photo_profile = models.ImageField( upload_to='uploads/images',null=True,blank=True) nomComplet = models.CharField(max_length=50,null=True) --=> this is Views.py def demande_participer(request): participers=Participer.objects.all() return render(request,'Association/success.html', {'participers':participers},print(participers)) ----=> success.html {% extends 'home/base.html'%} {% block content %}{% load static %} <div class=" mt-4 pb-5"> <h1 style="text-align:center;">Confirmation de Participation </h1> <div class="container"> <div class="card mt-5 pb-5"> {% for parti in participers %} {{parti.mission_id.nom}} <br> {{parti.id_benevole.username}} <br> {{parti.est_participer}} {% endfor%} </div> <a class="btn btn-secondary mt-2 " href="{% url 'benevole' %}">Retour </a> </div> </div> {% endblock content %} -
Django template double the data [closed]
I would need to display the information but it displays twice. Does anyone know how to put (list and disci) together as I know the error is in my code with the for i, for j and {% endfor %} in double. Employe and Disciplinaire are 2 different table with is own data. page.html <tr> <th scope="col">Matricule</th> <th scope="col">Prenom</th> <th scope="col">Nom</th> <th scope="col">Avis Verbal</th> <th scope="col">1er Avis Écrit</th> <th scope="col">2er Avis Écrit</th> <th scope="col">Suspension</th> <th scope="col">Fin d'emploi</th> <th scope="col">Actions</th> </tr> {% for i in liste %} {% for j in disci %} <tr> <td>{{i.Matricule}}</td> <td>{{i.Prenom}}</td> <td>{{i.Nom}}</td> <td>{{j.Avis_verbal}}</td> <td>{{j.Avis_ecrit}}</td> <td>{{j.Avis_ecrit2}}</td> <td>{{j.Suspension}}</td> <td>{{j.Fin_emploie}}</td> <td><a href="">Editer </a>/<a href=""> Supprimer</a></td> </tr> {% endfor %} {% endfor %} views.py def disciplinaire(request): disci = Disciplinaire.objects.all() liste = Employe.objects.all() return render(request, 'accounts/page.html', {'disci':disci, 'liste':liste}) Screenshot of page.html -
How to properly use multiprocessing module with Django?
I'm having a python 3.8+ program using Django and Postgresql which requires multiple threads or processes. I cannot use threads since the GLI will restrict them to a single process which results in an awful performance (especially since most of the threads are CPU bound). So the obvious solution was to use the multiprocessing module. But I've encountered several problems: When using spawn to generate new processes, I get the "Apps aren't loaded yet" error when the new process imports the Django models. This is because the new process doesn't have the database connection given to the main process by python manage.py runserver. I circumvented it by using fork instead of spawn (like advised here) so the connections are copied to the other processes but I feel like this is not the best solution and there should be a clean way to start new processes with the necessary connections. When several of the processes simultaneously access the database, sometimes false results are given back (partly even from wrong models / relations) which crashes the program. This can happen in the initial startup when fetching data but also when the program is running. I tried to use ISOLATION LEVEL SERIALIZABLE (like … -
Django does not throw ValidationError when required fields are not present
I am currently testing my django model using pytest (and pytest-django), but I can not write a failing test case in which a required field is missing. My Person-model requires solely a name and a company. The other fields are nullable and therefore optional. models.py: from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=64) company = models.CharField(max_length=128) position = models.CharField(max_length=64, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) def __str__(self): return (f"{self.name}" + (f", {self.position}" if self.position is not None else "") + f"({self.company})" + (f" born {self.date_of_birth}" if self.date_of_birth is not None else "") ) test.py from .models import Person import pytest from django.core.exceptions import ValidationError pytestmark = pytest.mark.django_db # Create your tests here. def test_minimal_person(): """Test if a minimal person can be created""" valid_person = Person(name="Max Mustermann", company="ACME") valid_person.save() assert len(Person.objects.get_queryset()) == 1 def test_insufficient_params(): with pytest.raises(ValidationError): invalid_person = Person() invalid_person.save() def test_missing_company(): with pytest.raises(ValidationError): invalid_person = Person(name="Max") invalid_person.save() def test_missing_name(): with pytest.raises(ValidationError): invalid_person = Person(company="ACME") invalid_person.save() def test_invalid_date_format(): """Test if an invalid date format throws a ValidationError""" with pytest.raises(ValidationError): invalid_person = Person(name="Max", company="ACME", date_of_birth="not-a-date") invalid_person.save() The test test_invalid_date_format and test_minimal_person succeed, but the other ones do not throw an (expected) error. What am I … -
My django form is showing that data is posted but data isnt being saved to database
So my form was working just fine until i played around with my frontend...changing the look of the system. But i dont think this has an effect on my forms but surprisingly all my forms are no longer saving data to the database!! Some help here guys. Here is my views.py from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from .forms import * # Create your views here. def register(request): form = RegistrationForm() if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'User successfully registered!') return redirect('home') else: form = RegistrationForm() return render(request, 'accounts/register.html', {'form': form} ) def login(request): if request.method == 'POST': username = username.POST['username'] password = request.POST['password'] try: user = Account.objects.get(username=username) except: messages.error(request, 'username does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Invalid username Or Password') return render(request, 'accounts/login.html', {} ) models.py from distutils.command.upload import upload import email from django.db import models from django.conf import settings from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.base_user import BaseUserManager class MyAccountManager(BaseUserManager): def _create_user(self, email, username, profile_pic, address, phone_number, car, details, password): if not email: raise ValueError("User … -
Django is not collecting all my static files
I have 2 folders containing my static files (admin, and assets). However, when I run python manage.py collectstatic, only the static files in the admin folder are collected. Below is a code snippet for static files in settings.py STATIC_URL = 'static/' STATTICFILES_DIRS = [ BASE_DIR/ "asert" ] STATIC_ROOT = (BASE_DIR/"asert/") Below are some urls linking to the static files from an html page <link rel="stylesheet" type="text/css" href="{% static 'assets/css/assets.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendors/calendar/fullcalendar.css' %}"> <!-- TYPOGRAPHY ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/typography.css' %}"> <!-- SHORTCODES ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/shortcodes/shortcodes.css' %}"> <!-- STYLESHEETS ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/dashboard.css' %}"> <link class="skin" rel="stylesheet" type="text/css" href="{% static 'assets/css/color/color-1.css' %}"> -
I'm very new to Django. I am trying to desing my login module and trying to print the values i submit. its not working [closed]
def login(request): form =LoginForm() print(form,'0000000000') if request.method == "POST": form = LoginForm(request.POST) print(form,'1111111111') if form.is_valid(): user = authenticate( username = form.cleaned_data['username'], password = form.cleaned_data['password'], ) if user is not None: login(request, user) else: messages.error(request,"Invalid username or password") else: form =LoginForm() return redirect("post_list", pk=user.pk) return render(request,"blog/login.html", context={"form":form}) -
datalist in HTML new option adding
I have a datalist elements from my view in django model, and i want to have sticky option(option that it's there even if the user enter something not in the list with "add new button" inside or to track it using javascript) to add new record in my model. -
How can I change the "Delete?" label in a Djano Inline
I'd like to replace the default "Delete?" label in TabularInLine to be something like "X". Is there a way to do this in Django directly or do I have to change it after the page loads with JS? example image -
NoReverseMatch at /assetAdmin/ error in Django
I have created a table that contains details about all the Assets. I wish to update the details of the asset. So, from the table, a made asset_id as URL to update page as happens in Django Administration. But after I added the URL pattern to update the asset, I am receiving this error: Reverse for 'asset-update' with keyword arguments '{'id': UUID('cd7edefa-796d-428e-bcec-c90ceecc7fc3')}' not found. 2 pattern(s) tried: ['assets/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/update/\\Z', 'assets/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/\\Z'] Here is my urlpatterns from urls.py: urlpatterns = [ path('home/', home, name='home'), path('assets/', assets, name='assets'), path('assetAdmin/', adminAssetView, name='assetsAdmin'), path('createAsset/', createAssetView, name='createAssets'), path('assets/<uuid:pk>/update/', assetUpdateView.as_view(), name='asset-update'), path('register/', register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='assets/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='assets/logout.html'), name='logout'), path('accounts/profile/', profile, name='profile'), path('admin/', admin.site.urls), ] Here are the views involved: @user_passes_test(lambda u: u.is_superuser) def adminAssetView(request): context = { 'assets': asset.objects.all(), 'users':User.objects.all(), } return render(request, 'assets/assetAdmin.html', context) class assetUpdateView(SuperUserCheck, LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = asset fields = ['currentOwner',] def form_valid(self, form): return super().form_valid(form) def test_func(self): asset = self.get_object() if self.request.user.is_superuser == True: return True return False And here is the part in assetAdmin.html where I am using asset-update urlpattern {% for asset in assets %} <tr> <td><a href="{% url 'asset-update' id=asset.id%}">{{ asset.id }}</a></td> <td>{{ asset.asset_type }}</td> <td>{{ asset.asset_name }}</td> <td>{{ asset.brand }}</td> <td>{{ asset.isActive }}</td> <td>{{ asset.currentOwner }}</td> … -
Issue with django factory for GenericForeignKey
models.py class GoogleCreative(models.Model): name = models.CharField creative_type = models.CharField url = models.URLField table_url = models.URLField status = models.CharField tags = GenericRelation( 'CreativeTag', object_id_field='creative_id', content_type_field='creative_content_type' ) class Tag(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=150, allow_unicode=True) class CreativeTag(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) creative_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) creative_id = models.PositiveIntegerField() creative = GenericForeignKey('creative_content_type', 'creative_id') class Meta: unique_together = ['tag', 'creative_content_type', 'creative_id'] factories.py class GoogleCreativeFactory(factory.django.DjangoModelFactory): class Meta: model = GoogleCreative name = factory.Faker('word') ..... class TagFactory(factory.django.DjangoModelFactory): class Meta: model = Tag django_get_or_create = ('name',) slug = factory.LazyAttribute(lambda o: slugify(o.name, allow_unicode=True)) class CreativeTagFactory(factory.django.DjangoModelFactory): class Meta: model = CreativeTag exclude = ['creative'] class Params: name = factory.Sequence(lambda n: f'tag {n}') tag = factory.SubFactory(TagFactory, name=factory.SelfAttribute('..name')) creative_id = factory.SelfAttribute('creative.id') creative_content_type = factory.SelfAttribute('creative.content_type') test.py @pytest.mark.django_db def test_tags_removed(google_creative_factory, creative_tag_factory, user): creative = google_creative_factory() creative_tag_factory(creative=creative, name='Big Fish') But getting error AttributeError: 'GoogleCreative' object has no attribute 'content_type' I try to solve it adding new field creative to CreativeTagFactory and comment Meta exclude field class CreativeTagFactory(factory.django.DjangoModelFactory): class Meta: model = CreativeTag # exclude = ['creative'] class Params: name = factory.Sequence(lambda n: f'tag {n}') tag = factory.SubFactory(TagFactory, name=factory.SelfAttribute('..name')) creative_id = factory.SelfAttribute('creative.id') creative_content_type = factory.SelfAttribute('creative.content_type') creative = factory.SubFactory(GoogleCreativeFactory) But got the same error -
How to use Django models with enumeration in REST APIs?
I am using User model to store user details: class User(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze') (MEMBERSHIP_SILVER, 'Silver') (MEMBERSHIP_GOLD, 'Gold') ] name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) membership = models.CharField(max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) When customer created using post api then i want to allow only these three values Bronze for MEMBERSHIP_BRONZE, Silver for MEMBERSHIP_SILVER & Gold for MEMBERSHIP_GOLD in membership field. When a user select membership choices lebel from ui then i need to insert the respected value. I don't know how to do this? serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["name", "email", "phone", "membership"] views.py @api_view(["GET", "POST", "PUT"]) def userActions(request): if request.method == "GET": users = User.objects.all() serializer = UserSerializer(users, many=True) res = serializer.data if request.method == "POST": name = request.POST.get("name") email = request.user.email phone = request.POST.get("phone") membership = request.POST.get("membership") user = User.objects.create(name=name, email=email, phone=phone, membership=membership) serializer = UserSerializer(user) res = serializer.data return res -
Django create a custom model field for currencies
Here I my custom model field I created it class CurrencyAmountField(models.DecimalField): INTEGER_PLACES = 5 DECIMAL_PLACES = 5 DECIMAL_PLACES_FOR_USER = 2 MAX_DIGITS = INTEGER_PLACES + DECIMAL_PLACES MAX_VALUE = Decimal('99999.99999') MIN_VALUE = Decimal('-99999.99999') def __init__(self, verbose_name=None, name=None, max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, **kwargs): super().__init__(verbose_name=verbose_name, name=name, max_digits=max_digits, decimal_places=decimal_places, **kwargs) How can I show the numbers in a comma-separated mode in Django admin forms? Should I override some method here on this custom model field or there is another to do that? Should be: -
how can i set up my server with winscp, putty, nginx, ubuntu and gunicorn [closed]
My English is very bad.And I am a beginner in programming I created a backend project with python ,django and rest api.But I don't know how to set up server. Please if someone knows about this , teach me -
django @cache_page decorator not setting a cache
Here's my cache setting: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } And a very basic view with cache_page decorator @api_view(['POST']) @cache_page(60*1) def sawan_ko_jhari(request): data = request.data.get('name') return JsonResponse({"success": True, "data": data}, safe=False) I've been checking cache keys for every request sent.. and I get empty array. Is there something I'm missing here? -
How to incorporate django-tailwind into Dockerized cookiecutter-django project?
Apologies for what is likely a very simple question, I am pretty new to Docker and am struggling to integrate django-tailwind into my docker project, which was created using cookiecutter-django. I have tried altering my Dockerfile and local.yml file to follow the Example dockerfiles on the Example app on the django-tailwind github repo but haven't been able make it work. The instructions beyond the example app are not very detailed. I have quoted my Dockerfile and local.yml file below; would someone be able to advise on what changes I need to make in order to incorporate django-tailwind, or point me in the direction of information that would help me to do it myself? Thanks for any help anyone can offer! Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye # define an alias for the specfic python version used in this file. FROM python:${PYTHON_VERSION} as python # Python build stage FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ # psycopg2 dependencies libpq-dev # Requirements are installed here to ensure they will be cached. COPY ./requirements . # Create Python Dependency and Sub-Dependency Wheels. RUN pip wheel --wheel-dir … -
Number of questions Django/Python
Number of questions: Try to create a new game of 20 questions of medium difficulty (MEDIUM) in the Art category. It was acting weird, right? This is definitely not a desirable situation. It follows that Open Trivia DB does not have enough questions from a given category with a given level of difficulty, so it returns us an error. And we do not handle it wisely: try: question = quiz.get_question() quiz.save(request) return render(request, 'game.html', vars(question)) except IndexError as x: return redirect('/finish') because we assume that the end of the questions = the end of the game. What makes sense if the API has the right number of questions ... The response code from the Open Trivia website in this case is 1. Looking at the documentation (https://opentdb.com/api_category.php), we will find out what each code means: Hint We have to think about how to solve this problem. It would be nice if the answer, apart from the error code, would include all possible tasks for a given category and level of difficulty - but unfortunately it is not. We have to adapt to the existing API, changing anything there is beyond our reach. We have three possible solutions: or we will … -
Django excel export, file is not downloading
I am trying to perform excel export functionality in Django with xls. But When I am trying to perform that file is not downloading and there is no error also. Here is my code. def excelExport(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment;filename="InitalRegistaration.xls"' work_book = xlwt.Workbook(encoding='utf-8') uc = u"".join(chr(0x0410 + i) for i in range(32)) # some Cyrillic characters u8 = uc.encode("UTF-8") work_sheet = work_book.add_sheet('Client Registration') work_sheet.write(0,0,"Clients") work_book.save(response) return response I don't know what's wrong with my code but the file is not getting downloaded nor there is the error coming from the code. -
Django: executing UPDATE query always returns rowcount 0
I'm new to programming and I'm not sure, whether the problem is in me or in the Django code. I call link method from my view and update field MatchId on Record model. Database is SQL Server 2017. My view: class RecordViewSet(viewsets.ModelViewSet): """ API for everything that has to do with Records. Additionally we provide an extra `link` action. """ queryset = Record.objects.all().order_by("Id") serializer_class = RecordSerializer permission_classes = [permissions.IsAuthenticated] @action(methods=["post"], detail=False) def link(self, request, *args, **kwargs): idToMatch = request.POST.getlist("Id") recordsToMatch = Record.objects.filter(Id__in=idToMatch) lastMatchId = Record.objects.latest("MatchId").MatchId matchedSuccesfully = recordsToMatch.update(MatchId=lastMatchId + 1) if matchedSuccesfully > 1: return Response(data=matchedSuccesfully, status=status.HTTP_200_OK) else: return Response(data=matchedSuccesfully, status=status.HTTP_404_NOT_FOUND) For some reason matchedSuccessfully always returns zero. Relevant Django code: def execute_sql(self, result_type): """ Execute the specified update. Return the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None finally: if cursor: cursor.close() for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty and aux_rows: rows = aux_rows is_empty = False return rows I rewrote execute_sql as follows: def execute_sql(self, result_type): … -
sending a zip file from hug framework to Django
Background: I am working on a microservice architecture, which has a Django app as a middle communicator. The services are written in hug. Problem: I am uploading a zip file in hug and trying to send it via a post request to Django application, unfortunately the file that I am receiving in hug function is byte string. and post is not able to send it mentioning following error. File "/usr/local/lib/python3.8/cgi.py", line 577, in __bool__ | raise TypeError("Cannot be converted to bool.") my hug function looks like this. def bulkUploadUserPhotos(request, file): apiURL = DJANGO_APP_URL # file is coming from a request. # error coming in below line apiResponse = requests.post( apiURL, files = file ) if apiResponse: return apiResponse.json() else: return { 'msg': 'Failed' } when I try to print file I receive following byte like data. \x8e\t\x8enH9\xa5\xa9\xfe\xa4\x8a\xf2\xeb\'\xb3g\xf7-B\xdd\x03\xbb\xab\x04\xf9\xa9\xfa\r\x0e\x88)){Pc\x94\'\xd2\xb9\xfc^Do\x83$^\x9d/2\xf4\xe7\xeb\xa3\xe1\xfd\xcd\x97\xdbF\x01\xa9=\xd6\xee\xacR\'L^W\xea\xc9\x9a\x82\xd5\xdc%\xd2\r\xeb\xf6\xb3\x93\xee\xf9\x1aJ"\x18\x17R\xe8j\xd9\xbfO\xec|\xe7L\x83V\xff\xc0\xd9\xd9\x19\xf8\xba\x84\xaa%\xf3)\\\t\x93R\x7f\x15\x95R\xa8\x9f\xb5mX<v\x19_\xa6\xeb\xdd\xa7\xbb6\r\x93D\x00\x1c\xd5\n\\\xd0`\xa3 u\xfc\xf53\x1c\x1cZ\xbb\x18\xd0\x1c~\xfc#\xf3\x81\xa5"\x90\xaaIG\x9e\xf4\xa6h\xbf\x96\xe13\xf3\x80e\x94\x9fU*\xc23vXa\xa3\xcb\x89\xa8}\xf4,\xb8Ld\xf8\x91\x1b\x8b\x82:\xa7X$2\xf9\xf2\xf7I\x9f\xb67\xab\x8b>\xe3$\xa1\x08\xb1\x14\xc3\x84\x9c\xcc=^\x8e\xbc\xf5m\x88Pn\xda\xc0\xd2\xc3&)\xabT\x07+\xf8\xf9\x12\x8d\xf0\xa4\xdf>g5R\xce\x89fD\x9d\x80\x11\x99G\xd1\xa9X\xfb\'yX\x04\xb7\x8b\x91\xcc\x99+/\xe7uZ\xff\xd8, -
Getting unique value on the base of Role
I have model name Movie which have many-to-many Relation with Actor Table. Actor Table is further many-to-many relation with Celebrity-Role. My question is i need only unique values on the base of roles Like Actors who's role is Director they show in Movie Table field with Director and only directors should be there and so on. i share my models please have a look. class CelebrityRole(models.Model): CELEBRITY_CHOICES = ( ('Actor', 'Actor'), ('Producer', 'Producer'), ('Writer', 'Writer'), ('Director', 'Director'), ) role = models.CharField(max_length=8, choices=CELEBRITY_CHOICES) def __str__(self): return self.role class Actor(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) name = models.CharField(max_length=200) rank = models.CharField(max_length=5, default=0) gender = models.CharField(max_length=6, choices=GENDER) avatar = models.ImageField(upload_to='CelebrityGallery/', blank=True) description = models.TextField(blank=True) birth_place = models.CharField(max_length=200, blank=True) dob = models.DateField(auto_now=False, auto_now_add=False) height = models.CharField(max_length=20) is_married = models.BooleanField(default=False) movies = models.ManyToManyField( 'movies.Movie', related_name='movies', blank=True) celebrity_role = models.ManyToManyField(CelebrityRole) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Here is my Movie Table class Movie(models.Model): title = models.CharField(max_length=200) year = models.CharField(max_length=25, blank=True) description = models.TextField(blank=True) released = models.CharField(max_length=25) runtime = models.CharField(max_length=25) language = models.CharField(max_length=255) country = models.CharField(max_length=100) metascore = models.CharField(max_length=5, blank=True) imdb_id = models.CharField(max_length=10, blank=False, unique=True, default='tt3032400') imdb_rating = models.CharField(max_length=5, blank=True) imdb_votes = models.CharField(max_length=100, blank=True) budget = models.CharField(max_length=25) box_office = models.CharField(max_length=25, … -
Can I get a code for getting id using javascript and ajax
I am new to development and dont have much idea about this please help me, I am unable to get the code for taking id of the absent student using javascript please help me with it. This is my html code where the list of students is displayed, all student by default are present and I if i mark some student as absent all other students should be saved as present and other marked as absent which were selected HTML code <div class="container"> <form method="POST" action="takeattendance"> {% csrf_token %} <div class="form-group"> <h4 style="color:white;"> Select Subject For Attendance</h4> <select class="btn btn-success" name="subject"> <option selected disabled="true">Subject</option> {% for sub in subjects%} <option value="{{ sub.id }}">{{sub.subject_name}}</option> {%endfor%} </select> </div> <table class="table"> <thead> <tr> <th scope="col" style="color:white;"><b>Email</b></th> <th scope="col" style="color:white;"><b>Roll No.</b></th> <th scope="col" style="color:white;"><b>First Name</b></th> <th scope="col" style="color:white;"><b>Last Name</b></th> <th scope="col" style="color:white;"><b>Year</b></th> <th scope="col" style="color:white;"><b>Division</b></th> <th scope="col" style="color:white;"><b>Batch</b></th> <th scope="col" style="color:white;"><b>Attendance</b></th> </tr> </thead> <tbody> {% for student in students %} {% if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year %} <tr> <td style="color:white;"><input type="hidden" name="student_name" value="{{student.id}}" >{{student.user}}</td> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <div class="form-group"> <select class="btn btn-success" name="status" id="status"> <option selected value="Present">Present</option> <option value="Absent">Absent</option> </select> </div> … -
I want a free alternative. What can I use, is there?
I can't use Rds in my django database I want a free alternative what can I use And is there a way to use Rds without an AWS account -
How to customize/filter django admin panel forms data?
I created models as below; Team model stores different team names, Tournament model is used to create a tournament and add teams into it and finally Game model where I select a tournament, add two teams and create a game. My problem is in Admin panel, while creating a game after selecting a tournament I have to select two teams, in the choice list I am getting all the available teams in the Teams database, instead of just the teams participating in the tournament. class Team(models.Model): name = models.CharField(max_length=30) # Ind, Pak, Aus, Sri, Eng class Tournament(models.Model): name = models.CharField(max_length=50) # Asia Cup: teams = models.ManyToManyField(Team) # Ind, Pak, Sri class Game(models.Model): name = models.CharField(max_length=50) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) # Asia Cup teams = models.ManyToManyField(Team) # Expected: Ind, Pak, Sri My Admin panel customization: class TeamInline(admin.TabularInline): model = Game.teams.through class Game(admin.ModelAdmin): fields = ['name'] inlines = [TeamInline] -
Django CMS - How to add background image in cms
I have been using placeholder to change images and text in html template like this {% block newsimage %} {% placeholder "newsimage" %} {% endblock newsimage %} But in one particular html file the background image have been called from class using css for example- html <div class="container"> In css .container { background: url(../images/sample.jpg); background-size: cover; background-repeat: no-repeat; height: 468px; } So That I cant able to add placeholder for this image how can i add background image for this template in django cms?