Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name. Even though I deleted that part
I'm implementing a search functionality in my Meme List View: class MemeListView(ListView): model = Meme paginate_by = 100 ordering = ['-created_at'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() search_value = self.request.GET.get("search", False) if search_value: memes = Q(title__icontains=search_value) objects = Meme.objects.filter(memes).select_related().distinct().order_by('-created_at')[:10] context['meme_list'] = objects context['search'] = search_value return context The only part of template that contains logout(I deleted it and restarted the server. The error is still there) {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href='{% url 'site:logout' %}'>Logout</a> </li> {% endif %} Now the issue is only if I search for a thing that has 0 results. If I search and find something everything works fine. Any Idea what is going on? -
How I display wagtail blog post in other pages like homepage
Noob here. So as the title I'm trying to display blog around my pages. What I'm trying to achive is: homepage who has a list of the latest post. Blog index Page. Blog category pages. a sidebar to use in my other pages. So that's has been my step so far: set up a wagtail project; install wagtail-blog; moved blog folder to Lib in my root folder set up root, template, and staticfolder. As I know by now my blog will show up only in my blog_index_page.html as a http:127.0.0.1/blog/ and blogpost showing up in 127.0.0.1/blog/blog-post-name. So blog looks like working fine. I'm really struggling to unbderstand how to implement the latest post in my homepage; making a category blog page and the sidebar who display latestpost around my site. so that's my code: blog/models.py from django.core.exceptions import ValidationError from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.conf import settings from django.contrib.auth import get_user_model from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from django.shortcuts import get_object_or_404 from django.template.defaultfilters import slugify from wagtail.snippets.models import register_snippet from taggit.models import Tag from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from .abstract import ( BlogCategoryAbstract, BlogCategoryBlogPageAbstract, BlogIndexPageAbstract, BlogPageAbstract, BlogPageTagAbstract … -
Request to Django views that start Celery tasks time out
I'm deploying a Django app with Docker. version: '3.1' services: b2_nginx: build: ./nginx container_name: b2_nginx ports: - 1904:80 volumes: - ./app/cv_baza/static:/static:ro restart: always b2_app: build: ./app container_name: b2_app volumes: - ./app/cv_baza:/app restart: always b2_db: container_name: b2_db image: mysql command: --default-authentication-plugin=mysql_native_password restart: always environment: MYSQL_ROOT_PASSWORD: - MYSQL_DATABASE: cvbaza2 volumes: - ./db:/var/lib/mysql - ./init:/docker-entrypoint-initdb.d rabbitmq: container_name: b2_rabbit hostname: rabbitmq image: rabbitmq:latest ports: - "5672:5672" restart: on-failure celery_worker: build: ./app command: sh -c "celery -A cv_baza worker -l info" container_name: celery_worker volumes: - ./app/cv_baza:/app depends_on: - b2_app - b2_db - rabbitmq hostname: celery_worker restart: on-failure celery_beat: build: ./app command: sh -c "celery -A cv_baza beat -l info" container_name: celery_beat volumes: - ./app/cv_baza:/app depends_on: - b2_app - b2_db - rabbitmq hostname: celery_beat image: cvbaza_v2_b2_app restart: on-failure memcached: container_name: b2_memcached ports: - "11211:11211" image: memcached:latest networks: default: In this configuration, hitting any route that is supposed to start a task just hands the request until it eventually times out. Example of route class ParseCSV(views.APIView): parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): path = default_storage.save("./internal/documents/csv/resumes.csv", File(request.data["csv"])) parse_csv.delay(path) return Response("Task has started") Task at hand @shared_task def parse_csv(file_path): with open(file_path) as resume_file: file_read = csv.reader(resume_file, delimiter=",") for row in file_read: new_resume = Resumes(first_name=row[0], last_name=row[1], email=row[2], tag=row[3], … -
wsgi: ModuleNotFoundError: No module named 'django' error
I am trying to host my Django app on my Ubuntu server and when trying to access my website, I get this error from the Apache log: ModuleNotFoundError: No module named 'django' I am using a venv for my Django app with python version 3.8 (I have also compiled and installed mod_wsgi in my venv). Running pip freeze I see that I do have Django installed in my venv: APScheduler==3.8.1 asgiref==3.5.0 backports.zoneinfo==0.2.1 certifi==2021.10.8 charset-normalizer==2.0.10 colorama==0.4.4 commonmark==0.9.1 deepdiff==5.7.0 Django==4.0.1 django-cors-headers==3.11.0 djangorestframework==3.13.1 idna==3.3 lxml==4.7.1 mod-wsgi==4.9.1.dev1 ordered-set==4.0.2 prettytable==3.0.0 psycopg2-binary==2.9.3 Pygments==2.11.2 pytz==2021.3 pytz-deprecation-shim==0.1.0.post0 requests==2.27.1 rich==11.1.0 six==1.16.0 soupsieve==2.3.1 sqlparse==0.4.2 tzdata==2021.5 tzlocal==4.1 urllib3==1.26.8 wcwidth==0.2.5 whitenoise==5.3.0 And just in case it might solve it, I installed Django globally but still got the error in Apache. I have been trying to follow some of the common solutions but can't seem to get it to work. Is there anything I am missing or any setting that may be off? I do notice my Apache says it is configured with 3.6, could this be the cause? is there a way to make it use 3.8 which is my python3 default? My wsgi for my Django project (backend/core/wsgi.py): import os, sys sys.path.append('/home/brickmane/djangoapp/pricewatcher/backend/') sys.path.append('/home/brickmane/djangoapp/pricewatcher/backend/core/') sys.path.append('/home/brickmane/djangoapp/pricewatcher/venv/lib/python3.8/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application … -
Static files show in test server but not in production
I have a problem with my Django app not finding static files. When I try to look up the file in the test server, it shows up, on the console I get: [01/Feb/2022 21:34:25] "GET /static/2022/2022-01-12/20220630.pdf HTTP/1.1" 200 295223 But when I try to look at the file in the production server I get this in the error log: 2022/02/01 21:34:08 [error] 6769#6769: *317 open() "/home/pi/Django/my_project/static/2022/2022-01-12/20220630.pdf" failed (2: No such file or directory), client: 192.168.178.**, server: ********, request: "GET /static/2022/2022-01-12/20220630.pdf HTTP/1.1", host: "*******", referrer: "http://myraspi4/documents/doc_show/261" In the settings file I have static directories set up like this: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [ '/mnt/ssd/doc_storage', ] Permissions are -rwxrwxrwx on all files. Other files in other subdirectories show up no problem. What am I doing wrong? -
Creating a function to auto-populate field with another model's field
I want to auto-populate item_selected field from my Order model with the items of the Order (which also a field from Order model). Its difficult for me because they represent different things but similar. Please follow me I will explain better below: From the image above. What I want is to have item selected populate by whatever is selected in items, so in this case, I want "titletitle2" be chosen in item selected since it is selected in Items. So no matter how many times "titletitle2" is selected in items it will just be chosen in item selected once. I assume this can be achieved in the Models, this is the Estore Model below: class eOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey('blog.Post', on_delete=models.CASCADE) item_variations = models.ManyToManyField( ItemVariation) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price def get_total_discount_item_price(self): return self.quantity * self.item.discount_price def get_amount_saved(self): return self.get_total_item_price() - self.get_total_discount_item_price() def get_final_price(self): if self.item.discount_price: return self.get_total_discount_item_price() return self.get_total_item_price() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(eOrderItem) item_selected = models.ManyToManyField( 'blog.Post', blank=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, … -
Styling an html form [closed]
I am trying to have an html form where i can have users style their texts such as make some parts bold, italic, list items, add pictures etc just like the stackoverflow ask question form. Here is a sample I want to save the input using python flask or django into a database and load the data exactly the way it was sent to the database (styled). -
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 24: 'trans'. Did you forget to register or load this tag?
My question is related to DJANGO application After developed my code using locale capability {% trans 'value' %} tag in the correct order all works fine until I turned DEBUG = False in the settings.py.The following error shows: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 24: 'trans'. Did you forget to register or load this tag? The application blocked showing the following message in the Screen. A server error occurred. Please contact the administrator. In the server the following message has been showed. Traceback (most recent call last): File "C:\Python38\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Python38\lib\site-packages\django\core\handlers\wsgi.py", line 133, in __call__ response = self.get_response(request) File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 130, in get_response response = self._middleware_chain(request) File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 49, in inner response = response_for_exception(request, exc) File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 103, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 142, in handle_uncaught_exception return callback(request, **param_dict) File "C:\Python38\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Python38\lib\site-packages\django\views\defaults.py", line 88, in server_error template = loader.get_template(template_name) File "C:\Python38\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Python38\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Python38\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Python38\lib\site-packages\django\template\engine.py", line 125, in find_template template = … -
Real time updates from Rest API
I created the REST API in Django and android application in Java. I need to send/receive real-time updates from the API I developed. May anyone tell me the possible solution to achieve this, Django channels or polling data periodically or other alternatives. Right now I have rest endpoints and data is synchronized using the button(in the android application) to poll data. -
when my project run in locally at that time email is send successfully . but when i deploy my project in heroku that time i get error
SMTPAuthenticationError at /products/registration_phase2/ (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu\n5.7.14 lB4WsSLkRxiExbfj6x9Dp7AeoK9Y8OAbTy2PD236kQLn5wAbGEkCO5hpMPOuH6qb4DGi6\n5.7.14 2_bs9L4dKNiEm63cGZbj4a8UGEPry8XAh437kKQYVIF63wHKoG4OgjwYzRxtyBh->\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 bs8sm7309041qkb.103 - gsmtp') Request Method: POST Request URL: https://aas-system.herokuapp.com/products/registration_phase2/?id=15 Django Version: 3.2.11 Exception Type: SMTPAuthenticationError Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu\n5.7.14 lB4WsSLkRxiExbfj6x9Dp7AeoK9Y8OAbTy2PD236kQLn5wAbGEkCO5hpMPOuH6qb4DGi6\n5.7.14 2_bs9L4dKNiEm63cGZbj4a8UGEPry8XAh437kKQYVIF63wHKoG4OgjwYzRxtyBh->\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 bs8sm7309041qkb.103 - gsmtp') Exception Location: /app/.heroku/python/lib/python3.9/smtplib.py, line 662, in auth Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Tue, 01 Feb 2022 18:33:35 +0000 -
Django REST to_representation: Have serializer fields appear last
I have the following serializer class: class DataLocationSerializer(QueryFieldsMixin, serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = MeasurementsBasic fields = ['temp', 'hum', 'pres', 'co', 'no2', 'o3', 'so2'] def to_representation(self, instance): representation = super().to_representation(instance) representation['timestamp'] = instance.time_received return representation The data is returned in a JSON file structured like this: { "source": "ST", "stations": [ { "station": "ST1", "data": [ { "temp": -1.0, "hum": -1.0, "pres": -1.0, "co": -1.0, "no2": -1.0, "o3": -1.0, "so2": null, "timestamp": "2021-07-04T21:00:03" } ] } ] } How can i make it so the timestamp appears before the serializer's fields? -
I'm trying to add a search functionality to my ListView but it gives Method Not Allowed (POST): error
My search form: <form class=" my-2 my-lg-0 d-flex flex-row-reverse" method=POST action="{% url 'memes:all' %}" > {% csrf_token %} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> <input class="form-control mr-sm-2" name="search" placeholder="Search" aria-label="Search"> </form> My List View: class MemeListView(ListView): model = Meme paginate_by = 100 ordering = ['-created_at'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() search_value = self.request.GET.get("search", False) if search_value: memes = Meme.objects.filter(name_contains=search_value) objects = Meme.objects.filter(memes).select_related().distinct().order_by('-created_at')[:10] context['meme_list'] = objects context['search'] = search_value return context My url: path('', MemeListView.as_view(), name='all'), error: "GET / HTTP/1.1" 200 4455 Method Not Allowed (POST): /all/ Method Not Allowed: /all/ [01/Feb/2022 19:23:22] "POST /all/ HTTP/1.1" 405 0 I've done almost identical search functionality in my other crud and it seems to work. What's the issue? -
How to pass additional arguments to class view in django?
def edit_course(request,course_id): course=Courses.objects.get(id=course_id) return render(request,"hod_template/edit_course_template.html",{"course":course,"id":course_id}) The code above shows a view in django that is defined as a function. I want to recreate the same view as a class based view in django but I couldn't pass in an additional argument such as course_id into the class based view as it shows an error. Can someone tell me how to recreate that above function into a class based view ? -
Get an error when migrate to MySQL in the Django project
I get the same error when I try to browse the app models. My project is on C Panel and connected to MySQL django.db.utils.OperationalError: (1118, 'Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs') -
Django- how can I get the selections of a many-to-many field in my model's table?
I have a django model (MyModel) where one of the fields (tags) is a ManyToManyField field --tag's value is actually another model (Tag). When a user creates a MyModel instance/entry in the Django admin panel they choose at least one tag from a list of tags for that entry. bytes/models.py class Tag(models.Model): CATEGORY_CHOICES = ( ('topic', 'topic') ) tag = models.CharField(max_length=100, unique=True) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) class MyModel(models.Model): id = models.CharField(max_length=30, primary_key=True) title = models.CharField(max_length=300, default='') author = models.CharField(max_length=300) copy = models.TextField(blank=True, default='') tags = models.ManyToManyField(Tag) I'm trying to write a custom Django management task where I use SQL to get all of the data from MyModel (on a PSQL server): import psycopg2 class Command(BaseCommand): def handle(self, *args, **options): config = settings.DATABASES['default'] try: query = F'''SELECT * from bytes_mymodel''' conn = psycopg2.connect(..use config to connect to server) cursor = conn.cursor() cursor.execute(query) results = cursor.fetchall() print(results) However when I print the 'results' I get a list of tuples - each tuple is a MyModel instance/entry. However, I don't see what tags are selected for the tags entry of each MyModel instance. For example: [('abc', 'The Title Here', 'Written By', 'Lots of copy'), ('efg', 'The Second Title Here', 'Written By', 'Lots of … -
How can I encrypt <int:pk> inside my URLs?
I think it's a dumb question, but I can't solve this problem anyway. I'm building a simple card game with chatrooms in Django. When a mod creates a room, to enter this room you need to use the following URL: cardgame/room/<int:pk> where inside of <int: pk> is replaced by the id of the room created. My problem is that some random user could enter the room of id=x just using a link like cardgame/room/x without being invited. I wanted to encrypt the id number whenever a room is created, just like when you create a Google meet call but I dont know how to this using Django/Python. How can I do this? -
exec() function in python not executing in django
Hope you all are fine. I want to use the exec() function in django to execute my strings picked from the database. The code I wrote is working in just python script but not working in Django views. Below is my code in python script which I'm running in notebook. ticker = 'AAPL' title = 'f"hey {ticker} is a really doing good."' exec('title = ' + title) print(title) But same code in Django views is not executing. Below is the code in views.py. ticker = 'AAPL' title = queryset.title #The title here is The {ticker} is not doing good. exec('title = ' + title) It is not giving the write anwser, just returning the first title as shown below. The {ticker} is not doing good. Thats is the {ticker} body. If anyone have any solution, kindly help me to figure it out. -
Django Redirect If Authenticated Mixin
i want to create a mixin to be redirect user to a specified page if they're already authenticated. i want to be able to use this mixin in different parts of the application without having to rewrite the logic over and over again. i get a accounts.views.view didn't return an HttpResponse object. It returned None instead. error if the user is not authenticated but it works if user is authenticated. accounts is the app_name here's my code in mixin.py class RedirectIfAuthenticatedMixin: """ RedirectIfAuthenticatedMixin: redirect authenticated user to different page via redirect_to parameter """ redirect_to = None def get(self, request): """ Get request handler to check if user is already authenticated then redirect user to specified url with redirect_to """ if request.user.is_authenticated: return HttpResponseRedirect(self.get_redirect_url()) # return ??? <- WHAT TO WRITE HERE TO ALLOW REQUEST TO CONTINUE EXECUTION def get_redirect_url(self): """ Get the specified redirect_to url """ if not self.redirect_to: raise ImproperlyConfigured('no url to redirect to. please specify a redirect url') return str(self.redirect_to) -
STARTTLS extension not supported by server in django
i am using gmail to do this, and i'm still at devlopment. it just keep throwing this error, yesterday it was working, sometimes it would also stop and show this error, but throughtout today it havent been working as expected setting.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "testemail@gmail.com" EMAIL_HOST_PASSWORD = "mypassword" views.py def mail_letter(request): emails = NewsLetter.objects.all() df = read_frame(emails, fieldnames=['email']) mail_list = df['email'].values.tolist() print(mail_list) if request.method == "POST": form = MailMessageForm(request.POST) if form.is_valid: form.save() # Sending Messages title = form.cleaned_data.get('title') message = form.cleaned_data.get('message') send_mail( title, message, '', mail_list, fail_silently=False, ) # Success Alert messages.success(request, f"Messages sent successfully") subscribed = True return redirect('elements:mail_letter') else: form = MailMessageForm() -
Django Admin: manage auth.models User from different model
I would like to manage auth.models.User is_active attribute from my custom UserProfile model via admin page. class UserProfile(models.Model): user = models.OneToOneField( User, verbose_name=_('User'), related_name='user_profile', on_delete=models.CASCADE, ) invited_by = models.ForeignKey( User, verbose_name=_('Invited by'), on_delete=models.SET_NULL, related_name='profile_invitations', null=True, blank=True, ) avatar = ResizedImageField( size=[512, 512], crop=['middle', 'center'], quality=90, verbose_name='avatar', null=True, blank=True, upload_to=get_user_upload_path ) attrs = models.CharField( _('User data'), max_length=10000, ) phone_number = models.CharField( _('Phone number'), max_length=80, null=True, blank=True, validators=[phone_regex_validator], ) def __str__(self): return '{}({})'.format(self.__class__.__name__, self.user.username) def save(self, **kwargs): if self.phone_number: self.phone_number = create_alphanumeric_string(self.phone_number) super().save(**kwargs) @property def attributes(self): return json.loads(self.attrs or '{}') @attributes.setter def attributes(self, value): self.attrs = json.dumps(value or {}) and in my admin.py @admin.register(UserProfile) class UserProfileAdmin(admin.ModelAdmin): list_display = ('user', 'attrs', 'invited_by') search_fields = ('user__username',) What I want to achieve is to allow from UserProfile admin view change is_active field from auth.models.User. My question is what is the best way to solve this? Write new custom form and attach it to admin view or somehow attach this field to UserProfile model? Or maybe different solution? -
Selectively escape strings in html using python/django
I'm working with email content that has been formatted in html. What I have found is that email addresses are often formatted similarly to html tags. Is there a way to selectively escape strings in html code, but render others as-is? For example, email addresses are often formatted as "Guy, Some <someguy@gmail.com>" How can I escape this, which python sees as an html tag, but leave <br></br><p></p>, etc. intact and render them? -
How can I add a image on a post in django?
I want to create an upload image button in django admin post models. When an image is uploaded, will be nice to be displayed on both blog card and then on post detail on the website. Here is my code until now. How should I do this in order to make this work? Here is my blog.html page <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="column"> {% for post in post_list %} <div class="card mb-4"> <div class="card-body"> <img class="card-image">{{post.header_image}}</img> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p> <p class="card-text">{{post.content|slice:":200"}}</p> <a href="{% url 'post_detail' post.pk %}" class="btn-grey">Află mai multe</a> </div> </div> {% endfor %} </div> </div> </div> Here is my post detail.html <div class="container"> <div class="detail-row"> <div class="card-detail-body"> <h1> {{ post.title }} </h1> <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p> <p class="card-text ">{{ post.content | safe }}</p> </div> </div> </div> Here is models.py from django.db import models import datetime from django.contrib.auth.models import User STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=1048) slug = models.SlugField(max_length=1048) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') related_name=('blog_posts') content = models.TextField() status = models.IntegerField(choices=STATUS, default=0) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title And here are … -
Multiple checkboxes validation rules, only works when every checkbox selected
I have a template which goes through a queryset and creates a checkbox for each item which seems to be a validation problem. I can only submit this when I check every checkbox and I just can't seem to figure out what is wrong. my template: <form method="POST"> {% csrf_token %} <fieldset> {% for choice in choices %} {{ choice.description }} <input type="checkbox" value="{{choice.section}}" name="sections" required=""> {% endfor %} <button type="submit">Submit</button> </fieldset> my forms.py class AddSectionForm(forms.Form): sections = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple()) -
Multiple databases for the same model in Django
Django seems to support multiple databases and allows each model to override methods to route to a specific database (official doc). Two questions: Does it support routing for the same model into different databases, for example for partitioning (say I want to split my users across multiple databases based on a predicate like the length of the username or the first letter, etc...) How does it works/render in the admin UI? I would need to aggregate the data from all databases in my case. -
Background process in Django
I am a freshman in Django and I have a problem with understanding of implementation background processes. For example, I have: model.py class Person(models.Model): name = models.CharField(max_length=23) math_grade = models.IntegerField(null=True, blank=True) phys_grade = models.IntegerField(null=True, blank=True) avg_grade = models.IntegerField(null=True, blank=True) class PersonAdmin(admin.ModelAdmin): list_display=('name', 'math_grade ','phys_grade', 'avg_grade') admin.py from django.contrib import admin from .models import * admin.site.register(Person, PersonAdmin) How to implement the next thing: Automatically check (periodically) if math_grade and phys_grade are saved into the DB for this Person, and then automatically f.e. save avg_grade as (a+b)/2