Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add users to groups as they register
I am trying to add a user to groups that I have created in the django admin. How do I implement my view function so that the user is added to a group on registration? I have created a custom UserRegisterform as illustrated below to so that users can indicate Group they are in. I have a problem with implementing my view function so that the users are automatically added to groups I have researched and found this links : https://docs.djangoproject.com/en/2.2/topics/forms/ https://www.guguweb.com/2014/09/10/group-combo-box-django-user-profile-form/ have created a form as follows: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group,User class UserRegisterForm(UserCreationForm): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True) email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'group'] my views.py file from django.shortcuts import render,redirect from .forms import UserRegisterForm from django.contrib.auth.models import Group def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): for value in form.cleaned_data['group']: group = Group.objects.get(name= value) group.user_set.add(user) form.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) when I log into the admin site, i expect to see the user assigned to the group he/she chose. The User is added but not assigned a group -
POST method in Django Rest framework returning server error 500 on EC2 instance
I am trying to build a web app using Django Rest framework. When I run the app on localhost 127.0.0.0/8000 it works fine. But when I deploy it on an EC2 server the POST methods return 500 server error. Here is one of the post methods in the views.py - class customer_location(APIView): def post(self, request, *args, **kwargs): customer_id = json.loads(request.body).get('customer_id') queryset = customers.objects.filter(cid= customer_id) serialize = customer_details(queryset, many=True) return Response(serialize.data, status=status.HTTP_200_OK) The urls.py is like this - from django.conf.urls import include, url from django.urls import path from rest_framework import routers from . import views urlpatterns = [ url(r'^customer_location/$', views.customer_location.as_view(), name='customer_location'), ] The DEBUG mode is set to False and the EC2 instance IP address is added in the ALLOWED_HOSTS. The GET methods are working fine but the POST methods give error. I checked the logs and I am getting this - raise JSONDecodeError("Expecting value", s, err.value) from None And this is for this line in the view.py - customer_id = json.loads(request.body).get('customer_id') The inbound rules of the EC2 instance allows access for HTTP, HTTPS, SSH, PostgreSQL and Custom TCP rule for port 8000. When I run the curl command from the terminal I can get the values for the POST Method- … -
How to cope with circular import
Django==2.2.5 Python 3.7.3 Structure of yandex_general app: . ├── admin.py ├── apps.py ├── __init__.py ├── models.py ├── validators.py ├── views.py ├── yandex_const.py └── yandex_utils.py validators.py from yandex_general.yandex_utils import select_from_yandex_response def validate_retargeting_condition_id(id: int): id = select_from_yandex_response(AdEntity.RETARGETINGLISTS.value["service_name"], ids=[id]) if not id: raise ValidationError("Отсутствует такой Идентификатор условия ретаргетинга") models.py from yandex_general.validators import validate_retargeting_condition_id def validate_retargeting_condition_id(id: int): id = select_from_yandex_response(AdEntity.RETARGETINGLISTS.value["service_name"], ids=[id]) if not id: raise ValidationError("There is no such REtargeting condition") yandex_utils.py from yandex_general.models import YandexResponse def select_from_yandex_response(yandex_direct_object_name: str, ids: int = None, name: str = None) -> dict: try: selection = getattr(YandexResponse.objects.get(key="yandex_response"), yandex_direct_object_name) except ObjectDoesNotExist as e: ... Problem: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/michael/PycharmProjects/ads2/venv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
how to write query for checking list contains
I have a model with name Weekdays that contain a field with name Days. Days is a list of weekdays that already saved. ex: Days=['Monday', 'Sunday', 'Saturday'] there is a Variable in my view.py with name selected_day. ex: selected_day=['Monday'] now I want to find the object that Days field includes selected_day and I need to write a query that checks is Days contain selected_day or not. something like this maybe: my_obj=models.Weekdays.objects.get(Days contain selected_day) -
How to upload list of files to URL via django?
In Django, I was able to get the list of files from the media folder, how to select the list of files and send those files to given URL. User will select the given Location and push the files the locations. @ajax_request def listofilesVIEW(request, dir_name="media"): template_name = 'listofiles.html' path = os.path.join(settings.MEDIA_ROOT, dir_name) images = [] for f in os.listdir(path): if f.endswith(".img"): images.append("%s" % (f)) return render(request, template_name, {'images': images}) Here is the code for the checkbox: <div class="row"><div class="col"> {% for image in images %} <div class="form-check"><label class="info-title form-check-label"><input class="form-check-input" type="checkbox" value="{{ image }}" /> {{ image }} {% endfor %} </div> </div> -
AWS EC2 instance connection refused using Docker
I have tried looking for a solution for this and I don't seem to get one. I have my containers up and running, I have exposed ports 80 and 443 in the security groups configuration but I am getting a connection refused error from my browser. Checked the Nginx logs, nothing. Dockerfile FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev git jpeg-dev zlib-dev libmagic RUN python -m pip install --upgrade pip RUN mkdir -p /opt/services/writer_api/src COPY requirements.txt /opt/services/writer_api/src/ RUN pip install --no-cache-dir -r /opt/services/writer_api/src/requirements.txt COPY . /opt/services/writer_api/src/ WORKDIR /opt/services/writer_api/src production.yml version: "3" services: postgres: restart: always image: postgres ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ web: restart: always build: . env_file: env/prod.env command: gunicorn writer.wsgi:application --reload --bind 0.0.0.0:8000 depends_on: - postgres - redis expose: - "8000" redis: restart: always image: "redis:alpine" celery: restart: always build: . command: celery -A writer worker -l info volumes: - .:/home/user depends_on: - postgres - redis celery-beat: restart: always build: . command: celery -A writer beat -l info volumes: - .:/home/user depends_on: - postgres - redis nginx: restart: always image: nginx:1.13 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d ports: - "80:80" depends_on: - web volumes: pgdata: config/nginx/conf.d/prod.conf # first we declare our upstream … -
Value Error :Time data '2019-03-19T07:01:02Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
I am using dateformat function but when i search for feb month only it shows proper data but when i search for march month it shows error This is my separate dateformat.py file in templatetag folder from django.template import Library import datetime register = Library() @register.filter(expects_localtime=True) def dateformat(value): return datetime.datetime.strptime(value,"%Y-%m-%dT%H:%M:%S.%fZ") and this is my table data line <td>{{x.date_joined| dateformat|date:'d-m-Y' }}</td> Error: ValueError at / time data '2019-03-19T07:01:02Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ' -
Django TemplateSyntaxError: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I'm unsure where my syntax error is, if you can please spot it that would be great. {% extends 'budget/base.html' %} {% block content %} <ul class="z-depth-1"> {% for transaction in transaction_list %} <li> <div class="card-panel z-depth-0 transaction"> <div class="row"> <div class="col l5"> <span class="title"> {{ transaction.title }}</span> </div> <div class="col l5"> <span class="title">{{ transaction.amount }}</span> </div> <div class="col l1"> <span class="title bold">{{ transaction.category.name }}</span> </div> <a href=""> <i class="material-icons right"></i> </a> </div> </div> </li> {% endfor $} </ul> </section> </div> {% endblock content %} And 'budget/base.html' looks like this: {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>BudgetProject</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> {% block content %} {% endblock %} <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> </body> </html> I tried looking at similar problems and I'm fairly certain the syntax for the for loop is correct. My code was working until I added the {% for x in y %} {% endfor %} -
" ' " (Single Quote) got converted to ' How do I replace it or fix it?
I sent a Dictionary to Django Template, Its " ' " got converted to ' How do I convert or Replace it? I have tried using replace function, It doesn't work. Dictionary_passed = {"-" : "100", "GERMANY" : "1500"} In the HTML template I got {&#39;-&#39;:&#39;100&#39;,&#39;GERMANY&#39:&#39;1500&#39; } on Dictionary_passed.replace('&#39;', ''), I get: {&#39l-&#39;:100, 'GERMANY&#39;:1500} -
TypeError: record_club_minutes() missing 2 required positional arguments: 'purchase' and 'fund'
I'm making an app in which students can input their club data and create minutes for their respective clubs. Right now, I'm running into some trouble trying to pass these two variables from one form into another; it keeps on giving the TypeError above. Any help is greatly appreciated! routes.py @login_required def generate_minutes(user_id): user = User.query.get_or_404(user_id) # TODO: use the same form form = record_club_name_form(user) if form.validate_on_submit(): # send user to the record_club_minutes club = form.club_list.data purchitems = form.purchaseitems.data funditems = form.funditems.data return redirect(url_for('clubs.record_club_minutes', user_id=user_id, club_id=club.id, purchase=purchitems, fund=funditems)) return render_template('record_club_name.html', title='Record', form=form, user=user) #THERE MAY BE BUGS HERE @clubs.route("/record_minutes/<int:user_id>/<int:club_id>/record", methods=['GET', 'POST']) @login_required def record_club_minutes(user_id, club_id, purchase, fund): user = User.query.get_or_404(user_id) club = Club.query.get_or_404(club_id) members = club.members form = create_club_minutes_form(club, purchase, fund) # form.purchaseform.entries = purchase # form.fundform.entries = fund if form.validate_on_submit(): minute = Minutes(club_id=club_id, date=form.date.data, time=form.time.data, location=form.location.data, minute=form.notes.data) db.session.add(minute) for index, field in enumerate(form.attendance): if field: attendance = Attendance(student_name=members[index].firstname + members[index].lastname) minute.attendance.append(attendance) db.session.commit() flash('Minutes successfully recorded', 'success') return redirect(url_for('clubs.view_club_name', user_id=user.id)) return render_template('record_minutes.html', title='Record', form=form, user=user, club=club, members=members) Here is forms.py for the record_club_minutes(user_id, club_id, purchase, fund) above. def create_club_minutes_form(club, purchase, fund): num_members = len(club.members) class ClubMinutesForm(FlaskForm): date = DateField('Meeting Date (mm/dd/year)', validators=[DataRequired(), DateRange(max = date.today())], format = '%m/%d/%Y') time = … -
Django app is not connecting with remote database
I have a Django app running on hosting server. I am using postgres database which is running on different server. The app is working properly in my local machine but in hosting server, the app is running but any functionality is not working which is associated with database. For example, user can not authenticated while login even the username and password is correct. My settings for database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB_NAME', 'USER': 'USER', 'PASSWORD': '*****', 'HOST': 'IP_ADDRESS', 'PORT': 'PORT', } } N:B I have given permission to the postgres database. I can access the db from local machine Django version 2.2.5 -
How can i extract single Models db into template in django without for loop?
I am wondering how to extract single model database in django template? i can do with for loop but i want a single model db in templates -
Why I can't save the edit of a Django ModelForm blog?
I was doing the Python Crash Course Ex. 19-1: Blogs, and I'm now stuck at saving the edit of any blog. I tried plugging in the .errors code in the blog.html (for showing each blog) but it shows nothing, so I guess my templates has no field errors (?) Here're some codes I believe crucial for solving the not-saving-the-edit problem. The new_blog function in views.py works fine so I'll skip it. The edit_blog function in views.py: def edit_blog(request, blog_id): idk = BlogPost.objects.get(id = blog_id) if request.method != "POST": form = BlogForm(instance = idk) else: form = BlogForm(instance = idk, data = request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('blogs:blogs')) content = {"editing_blog": form, "psst": idk} return render(request, 'blogs/edit_blog.html', content) new_blog.html: {% extends "blogs/all.html" %} {% block content %} <p>Write a new blog:</p> <form action="{% url 'blogs:new_blog' %}" method='post'> {% csrf_token %} <table border="1"> {{ new_blog }} </table> <p></p> <button name="submit">Submit</button> </form> {% endblock content %} edit_blog.html: {% extends "blogs/all.html" %} {% block content %} <p>Edit the blog:</p> <form action="{% url 'blogs:blog' psst.id %}" method='post'> {% csrf_token %} <table border="1"> {{ editing_blog }} </table> <p></p> <button name="submit">Save changes</button> </form> {% endblock content %} No matter how I change the title, or content, or … -
get the main image of a table with left join in django orm
class Products(models.Model) nombre = models.CharField( max_length = 255, blank = True ) class ProductsImages(models.Model) idProducto = models.ForeignKey( 'Products', related_name = 'imagesProduct', on_delete = models.CASCADE, ) principal = models.BooleanField( default = False ) url = models.ImageField( upload_to = '', blank = True ) for item in Products.objects.values( 'id', 'nombre', 'imagesProduct__id', 'imagesProduct__url' ).filter( imagesProduct__principal = True ): I need to make a left join with a main image and if I don't have the image show null. So far I get all the images and I just need the main one. -
SyntaxError: positional argument follows keyword argument in multiple filter elements query
Keep getting below error. File "/app/community/views.py", line 643 app_1 | (Q(roster_id=rid) | Q(roster__parent_id=rid)), app_1 | ^ app_1 | SyntaxError: positional argument follows keyword argument In this line of code inside a view (views.py). CommunityRosterMembers.objects.filter( community_id=cid, (Q(roster_id=rid) | Q(roster__parent_id=rid)), (Q(rsvp_vote=1) | Q(rsvp_vote=2)) ) The model I am using is: class CommunityRosterMembers(models.Model): community = models.ForeignKey('Community', blank=False, null=False, related_name='community_roster_member_ref_set', on_delete=models.CASCADE) roster = models.ForeignKey('roster.Roster', blank=False, null=False, related_name='roster_community_member_ref_set', on_delete=models.CASCADE) flag = models.ForeignKey('CommunityRosterFlags', blank=False, null=False, related_name='community_roster_flag_ref_set', on_delete=models.CASCADE) member = models.ForeignKey('members.MemberInfo', blank=False, null=False, related_name='community_member_roster_ref_set1', on_delete=models.CASCADE) request_by = models.ForeignKey('members.MemberInfo', blank=True, null=True, related_name='community_requester_roster_ref_set', on_delete=models.CASCADE) date_rsvp_requested = models.DateField(default=timezone.now()) date_rsvp_response = models.DateField(default=timezone.now()) rsvp_vote = models.IntegerField(default=0,blank=False)#0 - Pending, 1 - Accepted, 2 - Maybe, 3 - Declined attendance = models.IntegerField(default=0,blank=False)#0 - Pending, 1 - Attended, 2 - Absent, 3 - Missed def __str__(self): return self.roster.title -
Error generation due to settings.py in django
-Created a project in django with 'CustomUser' model derived from 'AbstractUser' in an app 'users' -Below is the settings file snippet. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'crispy_forms', 'users', I get following error while running python manage.py makemigrations command with unsuccessful migration. ValueError: The field authtoken.Token.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. After much trial and error, I have removed 'rest_framework.authtoken' from the Installed app and the migration error disappeared and my site become functional. Problem is I want to user rest_framework and token based authorisation but if I keep 'rest_framework.authtoken' in settings, migration is not taking place. Please help -
Django's view of its models is inconsistent with the actual database
We have a system consisting of a Django server connected to a PostgreSQL database, and some AWS Lambda functions which need to access the database. When an admin saves a model (PremiumUser - contains premium plan information that needs to be read by the Lambdas), we want to set up a schedule of CloudWatch events based on the saved information. Those events then trigger other Lambdas which also need to directly access the database, as the database state may change at any time and they should work off the most recent state of the database. The issue is that Django seems to think it has saved the values, but when the Lambdas read the database the expected values aren't there. We have tried using Django's post_save signal, calling the Lambdas inside the triggered function; we have tried overriding Django's default PremiumUser.save method to perform super(PremiumUser, self).save(*args, **kwargs), and only then call Lambdas (in case the post_save signal was getting triggered too early); and we have tried overriding the PremiumUser.save method and calling super(PremiumUser, self).save(*args, **kwargs) in the context of an atomic transaction (ie with transactions.atomic():). When we call the Lambdas a few seconds after the admin dashboard has updated, they … -
Bootstrap Modal Not Working on Paginated Datatable Django
I have a datatable where for each row there is a button which launches a bootstrap modal window to edit the record. I thought everything was working well, until I noticed that it only works for the first ten (initially visible) records. Beyond that the button doesn't do anything, but I'm not sure why. Could someone please help me clear this up? JS controlling this all the way at the bottom. index.html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%"> <thead> <tr> <th></th> <th style="width:3%;">Reference</th> <th style="width:7%;">Ultimate Consignee</th> <th style="width:5%;">Vessel</th> <th style="width:7%;">Booking #</th> <th style="width:5%;">POL</th> <th style="width:15%;">DOL</th> <th style="width:5%;">POE</th> <th style="width:5%;">Pickup #</th> <th style="width:5%;">Sales Contact</th> <th style="width:5%;">Trucking Co</th> <th style="width:2%;">Total Cases</th> <th style="width:2%;">Total FOB</th> <th style="width:5%;">Freight Forwarder</th> <th style="width:5%;">Proforma</th> </tr> </thead> <tbody> {% for order in orders %} <tr> <td> <!-- Update book buttons --> <button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' order.pk %}"> <span class="fa fa-pencil"></span> </button> </td> <td>{{ order.reference }}</td> <td>{{ order.ultimate_consignee }}</td> <td>{{ order.vessel }}</td> <td>{{ order.booking_no }}</td> <td>{{ order.POL }}</td> <td>{{ order.DOL }}</td> <td>{{ order.POE }}</td> <td>{{ order.pickup_no }}</td> <td>{{ order.sales_contact }}</td> <td>{{ order.trucking_co }}</td> <td>{{ order.total_cases }}</td> <td>{{ order.total_fob }}</td> <td>{{ order.freight_forwarder }}</td> <td> {% if … -
Django Models Processing information using Business Logic
I have been trying to create a basic finance application using Django Frameworks that allows a user to input basic information such as their state, marriage status, etc in order to process the information with my django model, and spit out the processed answers such as the State Tax Rate, Federal Tax Rate, etc. I have had no problem getting the information from the user using my templates, views, forms, and models, but I have been running into trouble when trying to process the information. I have done my research and it seems that the best place to use "business logic" is in the models. However, I just can't seem to process my users information in order to have my model return an updated State tax rate value from my StateTax method in my models.py file. Here is my code below: Models.py: class Financer(models.Model): STATE_CHOICES=( ('AL','Alabama'), ('CA','California'), ('VA','Virginia') State=models.CharField(max_length=10,choices=STATE_CHOICES) StateTaxRate=models.IntegerField(default=0) def StateTax(self): if self.State in no_tax_states: self.StateTaxRate=3 self.save() elif self.State in variable_tax_states: self.StateTaxRate=2 self.save() elif self.State in flat_tax_states: self.StateTaxRate=1 self.save() def __str__(self): return self.State (This is a barebones version of my model in which I am trying to send the State information to my StateTax method in order to process … -
How can I create a view of database models in ascending order?
I have a model which looks like: from django.db import models from django.db.models import Avg # Create your models here. class Course(models.Model): name = models.CharField(max_length=254, default='') description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='images') def average_rating(self): return self.review_set.aggregate(Avg('rating'))['rating__avg'] def __str__(self): return self.name And I would like to create a view that would present each entry in ascending/decending order of it's average rating. I already have other views that do work like: def price_ascend(request): courses=Course.objects.order_by('price') return render(request, "courses.html", {"courses": courses}) However when trying a similar approach with the average rating: def rating_ascend(request): courses=Course.objects.order_by('average_rating') return render(request, "courses.html", {"courses": courses}) I run into this error: Cannot resolve keyword 'average_rating' into field. Choices are: description, id, image, name, orderlineitem, price, review Why doesn't this work? In my HTML I have: {% for course in courses|dictsortreversed:"average_rating" %} {{ course.average_rating | floatformat }} {% endfor %} This works and shows the average rating of each course. This is code where the Review class is defined from django.db import models from courses.models import Course # Create your models here. class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) course = models.ForeignKey(Course) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) … -
Is there a library that allows for auto populating the rows with class instances?
I'm working on a homework question and I have created different instances of how a pizza can be priced based on the size and the type. The issue I'm running into is that while the table view is useful, it isn't what I wanted and I read you can customize it way more in views.py but I don't see anything that can populate a table in a way where it can filter duplicates as in I have 2 cheese pizzas, one is in the large size and one small with their own pricing. Since it doesn't know anything about the headers. If I did use the listdisplay it will still show duplicates. Question I have is that do I have to manually change the logic flow in the HTML file itself? As in if field_name == the same while checking if the content of the td is the same, don't fill, and fill price if the td is empty. Does that mean I have to use some JS code? This just seems like such a common table issue that I think I must be missing something here (someone must have built a library to go specify your headers and row … -
Using wagtailmenus I want to regroup the main menu and seperate out items that have children vs items that don't have children
I'm build a custom main menu for wagtailmenus. When I get all the items, I want to presort the list of items into two groups. Items with children and items without children. I was thinking of using Django's regroup but I'm a little lost as to how to think about this. Here's what I'm thinking right now: {% regroup menu_items by has_children_in_menu as items %} {% if items %} <ul> {% for it in items %} <li>{{ has_children_in_menu.grouper }} # this would be the name of the parent <ul> {% for imenu in has_children_in_menu.list %} <li>{{ imenu.title }}</li> # the child {% endfor %} </ul> </li> {% endfor %} </ul> {% else %} <ul> {% for parent_item in menu_items %} <li>{{ parent_item.title }}</li> {% endfor %} </ul> {% endif %} Does this make sense? Am I crazy? Maybe I'm thinking about this wrong. What suggestions do you have? -
Ajax form submit and errors to appear in template in JSON format (django)
I have a django site: js $("#contactForm").submit(function(event){ event.preventDefault(); //prevent default action var post_url = $(this).attr("action"); //get form action url var form_data = $(this).serialize(); //Encode form elements for submission $.getJSON( post_url , form_data,function( response ) { //iterate json response $.each( response, function(key, val) { $("#msgSubmit").append( val + "<br />"); //append results to element }); }); }); views.py def contact_form(request): form = ContactForm(request.POST or request.GET) if form.is_valid(): data = { 'success': True, } status = 200 else: data = { 'success': False, 'errors': form.errors.get_json_data(), } status = 400 return JsonResponse(data, status=status) html <form id="contactForm" method="get" action="{% url 'contact-form' %}"> ... <button type="submit">Submit</button> </form> <div id="msgSubmit"></div> When I submit the form: If there is no validation errors, I get 'true' appearing at #msgSubmit. If there is an error, I get nothing. I want JSON errors to appear at #msgSubmit. -
How to get result with ORM from queryset
I want to get result with ORM of Django. But I cannot get result with ORM. I just tried with 'select_related("field_name")'. but doesn't work.. Actually, I don't know using ORM well haha... and.. This Query is my needs SELECT sol.idx, sol.sol_name, sol.sol_warning, sol.user_num_id, sol.auto_run_server, ur.user_ip, pc.cpu_usage, pc.mem_usage, pc.disk_usage FROM solution AS sol INNER JOIN ems.user AS ur ON sol.user_num_id = ur.user_num INNER JOIN pc_status AS pc ON sol.user_num_id = pc.user_num_id; result row is ... idx, sol_name, sol_warning, user_num_id, auto_run_server, user_ip, cpu_usage, mem_usage, disk_usage so.. I used code is " Solution.objects.select_related('user_num') " But I cannot get same result. here are my python codes. models.py class User(models.Model): user_num = models.IntegerField(primary_key=True, auto_created=True) user_ip = models.CharField(max_length=20) user_name = models.CharField(max_length=10) user_pwd = models.CharField(max_length=10) class Meta: db_table = 'user' class Solution(models.Model): idx = models.IntegerField(primary_key=True, auto_created=True) sol_name = models.CharField(max_length=50) sol_warning = models.IntegerField() user_num = models.ForeignKey(User, on_delete=models.CASCADE) auto_run_server = models.IntegerField() class Meta: db_table = 'solution' class PcStatus(models.Model): pc_idx = models.IntegerField(primary_key=True, auto_created=True) cpu_usage = models.IntegerField(default=0) mem_usage = models.IntegerField(default=0) disk_usage = models.IntegerField(default=0) user_num = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'pc_status' -
how to send a message over websocket at a certain time
I am new to websockets and have just now gotten a working websocket connection in my application. I am trying to have the server check once per minute in the database to find upcoming tournaments, and for each player connected to a websocket that is registered in a tournament starting that minute, send a message that tournament with ID xxxxx is starting now. I have the following tournaments/consumers.py: from channels.generic.websocket import WebsocketConsumer import json class TournamentLobbyConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] print("The websocket received a message: '%s'" % message) tournaments/routing.py: from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url('ws/tournaments/$', consumers.TournamentLobbyConsumer), ] tournaments/templates/index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Tournament Lobby</title> </head> <script> var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/tournaments/'); chatSocket.onmessage = function(e) { // var data = JSON.parse(e.data); // var message = data['message']; alert("message received from websocket") }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; </script> {% if tournaments %} <ul> {% for tournament in tournaments %} <li><a href="{% url 'tournament_detail' tournament.id %}"> {{ tournament.name }} {{ tournament.start_time }}</a></li> {% endfor %} </ul> {% else %} <p>No tournaments are available</p> {% …