Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to model.filter(value__istartswith__in=['xx','YY'])
On django 2.2.3 would it be possible to combine the startswith and in filter s? I need to check if the value startswith from a list. IGNORA = ['xx','yy.', ] # something like this model.filter(value__istartswith__in=IGNORA) def check_code(codice): for x in IGNORA: if codice.startswith(x): return True return False Can it be done someway? -
What are the parsers used for in the Django Rest Framework?
I have a simple file model class Documents(models.Model): """ uploaded documents""" author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) upload = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=255, blank=True, null=True) datafile = models.FileField() created = models.DateTimeField(auto_now_add=True) type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) To display the list of uploaded documents and add new files, I use the class class DocumentsListView(viewsets.ViewSetMixin,generics.ListCreateAPIView): queryset = Documents.objects.all() serializer_class = DocumentsSerializer def perform_create(self, serializer): serializer.save(author=self.request.user) serializer.py class DocumentsSerializer(AwsUrlMixin, serializers.ModelSerializer): type_name = serializers.CharField(source='type.type', read_only=True) type = serializers.PrimaryKeyRelatedField(queryset=Doctype.objects.all()) view_file = serializers.SerializerMethodField() author = serializers.CharField(source='author.username', read_only=True) created = serializers.DateTimeField(format=date_format, input_formats=None, default_timezone=None, read_only=True) class Meta: model = Documents fields = ('id', 'author', 'filename', 'datafile', 'type', 'type_name', 'created', 'view_file') I use the standard DRF interface and I display everything normally and add new files to the database. While reading the documentation I came across parsers such as MultipartParser, FileUploadParser, which are also used when adding new files. I can't underatand when to use them and what function they perform, because now everything works without them. The documentation hasn't given me a clear understanding of when I need to use parsers. I try to add parser_classes = (MultiPartParser, FileUploadParser) to serializers.py and nothing change. Everything works as it did before. I'd appreciate it if you'd make that clear … -
Python Beam Analysis on web (FEM / FEA)
For my uni project, i am to code a beam shear force and bending moment calculator using the direct stiffness matrix method. I have done the backend code on python to calculate the needed shear force and bending moment diagrams. I am quite new to programming so I would like to know how to deploy the python code onto a website. Should I use Django/ Flask or anything else. The aim is for an input web app like this: https://beamguru.com/online/beam-calculator/ Apologies if it's a stupid question. -
Turn shell output into method for Django model
I am trying write a method for one of my models, that will end up with a list of boolean values based on a manytomany field. So I am looping though category id's and comparing them with a queryset, but I can't work out how to translate what I get in the shell to a function. I've been struggle with OOP for about 3 years now, which is why I started learning django in the first place. but basically, in the django shell, I can do this to get the queryset I want: p1 = Project.objects.get(id=2) p1.update_categories.all().values_list('id', flat=True) The problem I have is that this is for one project and I can't figure out how you translate that into something that will work for all instances. So far I have this: def checkmark(self): ''' Generates a list of True or False based on many to many field for Project and UpdateCategory ''' checkmark = [] # This is the line giving me issues queryset = Project.objects.filter(project=self, update_categories) # this bit all works fine categories = UpdateCategory.objects.all().values_list('id', flat=True) for cat_id in categories: if cat_id in queryset: checkmark.append(True) else: checkmark.append(False) return checkmark So what I am doing here is creating an empty … -
Can I put 2 models in a single class in Django Views.py?
Objective: I'm trying to display products and orders from 2 different tables in a template. I'm having difficulties on how can I possibly join two models in 1 class in views.py. I have tried django rest framework but that's not the scope of my app. Here is my code: class UserDashboardTemplateView(ListView): #I want to insert the ORDER model in this class also model = Product context_object_name = 'product' template_name = 'product/dashboard.html' The data must be displayed in this format: {% for o in orders %} <tr> <td>{{ o.status }}</td> </tr> {% endfor %} -
Django-Q set Q_CLUSTER 'sync': True doesn't work for unit tests
I am using Django-Q to send async emails with Django 2.2, DRF 3.9 and Postgres 10.9 The setup works fine except when it comes to unit tests. I refer to the following issue which is the exact same thing I am facing: https://github.com/Koed00/django-q/issues/266 As per the link, one of the solutions was to do change the sync setting to 'True' for testing purposes. This is what i have in tests.py: from django.conf import settings settings.Q_CLUSTER['sync'] = True class UserAPITestCase(APITransactionTestCase): print(settings.Q_CLUSTER) 'print' shows that the 'sync':True has been added, but the async_task still runs in async mode. However if I were to add the sync setting in the settings file directly everything works as it should and the async_task runs synchronously. It's like django-q isn't taking in the setting if it is updated later. How do I fix that? -
Path as an invalid syntax in Django
I'm new with Django, so I was following a tutorial about making a To-Do App. It was everything okay, until I got this error, I've been trying over and over again to re-write it, but I keep getting the same error. from django.contrib import admin from django.urls import path from hello.views import myView from todo.views import todoView from todo.views import addTodo urlpatterns = [ path('admin/', admin.site.urls), path('sayHello/', myView), path('todo/', todoView) path('todo/', addTodo), ] Then, I go to the command prompt, after writing the python manage.py runserver, I get the next error: File"C:\Users\usuario\Desktop\WebProject\WebProject_project\urls.py" line 26 path('todo/', addTodo), ^ SyntaxError: invalid sintax -
NoReverseMatch at /cart/ 'car' is not a registered namespace Error in Python Django
I ran my Django project and I got this error when I went to /cart/. NoReverseMatch at /cart/ 'car' is not a registered namespace I checked all of my code but never written 'car'. This is my urls.py of project. from django.contrib import admin from django.urls import path, include from shop import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('shop/', include('shop.urls')), path('search/', include('search_app.urls')), path('cart/', include('cart.urls')), path('order/', include('order.urls')), path('account/create/', views.signupView, name='signup'), path('account/login/', views.signinView, name='signin'), path('account/logout/', views.signoutView, name='signout'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) This is my urls.py of cart app. from django.urls import path from . import views app_name='cart' urlpatterns = [ path('add/<int:sitting_id>/', views.add_cart, name='add_cart'), path('', views.cart_detail, name='cart_detail'), path('remove/<int:sitting_id>/', views.cart_remove, name='cart_remove'), path('full_remove/<int:sitting_id>/', views.full_remove, name='full_remove'), ] This is my models.py of cart app. from django.db import models from shop.models import Sitting class Cart(models.Model): cart_id = models.CharField(max_length=250, blank=True) date_added = models.DateField(auto_now_add=True) class Meta: db_table = 'Cart' ordering = ['date_added'] def __str__(self): return self.cart_id class CartItem(models.Model): sitting = models.ForeignKey(Sitting, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() active = models.BooleanField(default=True) class Meta: db_table = 'CartItem' def sub_total(self): return self.sitting.price * self.quantity def __str__(self): return self.sitting This is my views.py of cart … -
How to set up django project with gunicorn service on gunicorn.socket?
I'm trying to run my django project on gunicorn socket as service. But it fails to start; Can anybody help me with this? I tried by following this link: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 I'm also using virtualenvwrapper to manage my virtualenvs. Here is my configuration files: /etc/systemd/system/gunicorn.socket: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=mohsen Group=www-data WorkingDirectory=/home/mohsen/Desktop/SummerCampDocs/carpooling/carpooling ExecStart=/home/mohsen/.virtualenvs/carpooling/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock carpooling.wsgi:application [Install] WantedBy=multi-user.target By running this commands: sudo systemctl start gunicorn.socket sudo systemctl enable gunicorn.socket sudo journalctl -u gunicorn.socket sudo systemctl status gunicorn I get the following message: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2019-08-28 12:38:18 +0430; 33min ago Process: 14000 ExecStart=/home/mohsen/.virtualenvs/carpooling/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock carpooling.wsgi:application (code=exited, status=1/FAILURE) Main PID: 14000 (code=exited, status=1/FAILURE) Aug 28 12:38:18 mohsen-ThinkPad-T490 gunicorn[14000]: self.stop() Aug 28 12:38:18 mohsen-ThinkPad-T490 gunicorn[14000]: File "/home/mohsen/.virtualenvs/carpooling/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop Aug 28 12:38:18 mohsen-ThinkPad-T490 gunicorn[14000]: time.sleep(0.1) Aug 28 12:38:18 mohsen-ThinkPad-T490 gunicorn[14000]: File "/home/mohsen/.virtualenvs/carpooling/lib/python3.6/site-packages/gunicorn/arbiter.py", line 245, in handle_chld Aug 28 12:38:18 mohsen-ThinkPad-T490 gunicorn[14000]: self.reap_workers() Aug 28 12:38:18 mohsen-ThinkPad-T490 gunicorn[14000]: File "/home/mohsen/.virtualenvs/carpooling/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Aug 28 12:38:18 mohsen-ThinkPad-T490 gunicorn[14000]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Aug 28 12:38:18 mohsen-ThinkPad-T490 gunicorn[14000]: … -
Passing a username from django login to angular navbar
I am using django login template as the first page a user will see, upon successful login they will then be on the angular side because of the <app-root> tag in my django home template. I have a navbar component in angular and I would like to display the users name and give them an option to logout. I can see it is getting the name correctly as it shows if I have it before the <app-root> tag. I am currently trying to pass {{user.username}} into the <app-root> tag and then eventually through to the navbar component but nothing appears on the navbar. Django Template: {{user.username}} //this bit shows the correct name <app-root [theUser] = "{{user.username}}"> <div class="container-fluid"> <div class="row align-items-center"> <div class="col text-center"> <div class="spinner-border p-5 m-5" role="status"> <span class="sr-only">Loading . . .</span> </div> </div> </div> </div> </app-root> app.component.html: <app-nav-bar [theUserName]="theUser"></app-nav-bar> nav-bar.component.html: <h4>{{theUserName}}</h4> I expected the username to be passed through the angular components and be displayed on the navbar. There is nothing being displayed, I can see the h4 is empty on dev tools. -
ssl_error_rx_record_too_long Mozilla and chrome
Hello guys I'm getting an error and i tried a lot but I can't figure it out. I deployed my django on apache wamp server and I have configured the ssl but I'm getting an error ssl_error_rx_record_too_long. On httpd-ssl I have default:443 and SSLEngine on. httpd-vhosts <VirtualHost *:82> ServerName localhost WSGIPassAuthorization On ErrorLog "logs/MMA.error.log" CustomLog "logs/MMA.access.log" combined WSGIScriptAlias / "C:\Users\Administrator.HR-JUGOR\Anaconda3\envs\MMA\Mobile\wsgi_windows.py" <Directory "C:\Users\Administrator.HR-JUGOR\Anaconda3\envs\MMA\Mobile"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static "C:\Users/Administrator.HR-JUGOR/Anaconda3/envs/MMA/Mobile/static" <Directory "C:\Users/Administrator.HR-JUGOR/Anaconda3/envs/MMA/Mobile/static"> Require all granted </Directory> </VirtualHost> -
Python Imports - Reference Top Level Module Instead of the "In-Level" Module
Python v2.7 Directory Structure: - project - manage.py - utils - __init__.py - somescript.py - apps - __init__.py - someapp - views.py - utils.py project.apps.someapp.views: // imports from utils import somescript // rest of the stuff Raises ImportError: cannot import name somescript Tried a dotted relative import: // imports from ...utils import somescript // rest of the stuff This raises ValueError: Attempted relative import beyond toplevel package. This is a Django project. It runs through manage.py. Command: ./manage.py runserver 0:41000 -
Gunicorn issues deploying to Heroku with heroku-community/apt
Trying to deploy my Django app to Heroku with custom apt. It builds it, but have this outputs: 2019-08-28T08:08:19.641167+00:00 heroku[web.1]: Starting process with command `gunicorn app_name.wsgi --log-file -` 2019-08-28T08:08:21.351678+00:00 heroku[web.1]: State changed from starting to crashed 2019-08-28T08:08:21.356871+00:00 heroku[web.1]: State changed from crashed to starting 2019-08-28T08:08:21.330571+00:00 heroku[web.1]: Process exited with status 127 2019-08-28T08:08:21.272791+00:00 app[web.1]: bash: gunicorn: command not found 2019-08-28T08:08:35.615536+00:00 heroku[web.1]: Starting process with command `gunicorn app_name.wsgi --log-file -` 2019-08-28T08:08:37.625634+00:00 heroku[web.1]: State changed from starting to crashed 2019-08-28T08:08:37.539106+00:00 app[web.1]: bash: gunicorn: command not found 2019-08-28T08:08:37.606357+00:00 heroku[web.1]: Process exited with status 127 This is my deploy script: sudo heroku buildpacks:add --index 1 https://github.com/heroku/heroku-buildpack-apt sudo heroku config:set APT_CACHING=yes sudo git push heroku master An Aptfile has only vlc If I deploy without buildpack-apt everything is fine. What is the problem? -
django ModelChoiceField, to_field_name
when I compile my code, This error message is returned. 'ModelChoiceField' object has no attribute 'to_field_name' ModelChoiceFiled is in the 'school_code' field. I already type to_field_name. class UserRegister(forms.ModelForm): class Meta: mstSchool = MstSchool.objects.filter(use_yn__exact="Y").order_by("code") model = MstUser fields = [ 'name', 'id', 'password', 'school_code'] widgets = { 'id' : forms.TextInput(attrs={'placeholder' : 'User ID', 'class':'form-control'}), 'password' : forms.TextInput(attrs={'placeholder' : 'password', 'class':'form-control school-password', 'type':'password'}), 'name' : forms.TextInput(attrs={'placeholder' : 'name', 'class':'form-control school-name'}), 'school_code' : forms.ModelChoiceField(queryset=MstSchool.objects.filter(use_yn__exact="Y").order_by("code"), empty_label="(Nothing)", to_field_name="school_code") } 'ModelChoiceField' object has no attribute 'to_field_name' -
Django Logging is not working in a module
Project Structure: |-project_root |- app1 |- starter.py |- submitter.py |- management |- commands |- submitter.py |- starter.py |- app2 |- project |- settings.py settings.py ... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'detailed': { 'format': '%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d - %(message)s' }, 'simple': { 'format': '%(levelname)s - %(filename)s - %(lineno)d - %(message)s' }, 'time': { 'format': '%(asctime)s - %(name)s - %(message)s' }, 'bare': { 'format': '%(message)s' } }, 'handlers': { 'stream': { 'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter': 'detailed', } }, 'loggers': { '<project name>': { 'handlers': ['stream'], 'level': 'INFO', 'propagate': True, } } } starter.py import logging # other imports logger = logging.getLogger(__name__) def starter_func(): logger.info("starter") return submitter.py import logging # other imports logger = logging.getLogger(__name__) def submit(): logger.info("submit") return commands: starter.py from django.core.management.base import BaseCommand from app1.starter import starter_func class Command(BaseCommand): help = "" def handle(self, *args, **options): starter_func() submitter.py from django.core.management.base import BaseCommand from app1.submitter import submit class Command(BaseCommand): help = "" def handle(self, *args, **options): submit() when I run python manage.py submitter, it prints logs. But when I run python manage.py starter, it doesn't print logs. I tried printing logger.disabled, for submitter it's False, but for starter it is True. What is causing this? -
How to authentication via appleId with django
i want to authentication via appleId with django , what package support this , please help? -
context does not get overwritten with new value
I try to add or overwrite some context values in a detail view. However the results are not displayed on the page, any idea how this is possible ?? Latest django version. id and amount are part of the model. amount should be overwritten and drunk should be added. class EntryDetailView(DetailView): context_object_name = 'entry' model = models.Entry template_name = 'web/entry_detail.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['amount'] = "what shall we do with the drunken sailer" context['drunk'] = "so drunken" return context The template contains : <div class="jumbotron"> id : {{ entry.id }} <br> amount: {{ entry.amount }}<br> drunk: {{ entry.drunk }}<br> </div> I get : id : 1 amount: 5 drunk: while i would expect id : 1 amount: what shall we do with the drunken sailer drunk: so drunken -
How can I pass arguments/parameters to the redux action in django API?
How can I pass the name, age, height arguments to my redux action ? I am using django rest api as the backend export const Search_Results = (name, age, height) => { return dispatch => { axios.get("http://127.0.0.1:8000/api/") .then(res => { const info = res.data; dispatch(presentResult(info)) }); } }; The presentResult is export const presentResult = results => { return { type: actionTypes.PRESENT_RESULTS, results: results } }; My reducer is const presentResult = (state, action) => { return updateObject(state, { results: action.results }); }; switch (action.type) case actionTypes.PRESENT_RESULTS: return presentResult(state, action); -
How to filter case-insensitive on oneToOneField in django
I'm trying to filter case-insensitive on the auth_user model which has a oneToOne relation with my model as shown in code beneath. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) headline = models.TextField(max_length=120, null=True) Normally to filter case-insensitive '__icontains' does the job, however if I filter with the following code, it is still case-sensitive even though I used icontains. profiles = profiles.filter(Q(user__first_name__icontains=search) | Q(user__last_name__icontains=search)).order_by('-id') I think the problem is with using 'user__first_name' since it is a field of a module related to profile and filtering on 'headline' which is a direct field of profile can be done case-insensitive. Any idea what the best solution is for this problem? -
how to do elastic search in model and related models in django
i am using django_elasticsearch_dsl which is running on 9200 port number and i have two models models.py class Category(models.Model): title = models.CharField(max_length=255, blank=True, null=True) class Book(models.Model): name = models.CharField(max_length=255, blank=True, null=True) categories = models.ManyToManyField('Category') document.py @posts.doc_type class PostDocument(DocType): class Meta: model = Media fields = [ 'id', 'title' ] related_models = [Category] def get_instances_from_related(self, related_instance): """If related_models is set, define how to retrieve the book instance(s) from the related model.""" if isinstance(related_instance, Category): return related_instance.book_set.all() search.py from elasticsearch_dsl.query import Q p = Q("multi_match", query=request.GET.get('q'), fields=['name','categories__name'], type='phrase_prefix') s = PostDocument.search().query(p) result = s.execute() this search code only works for the books models and i am unable to retrieve using related Category model my required output should be like i have two books like jungle and cuop and jungle book linked to Category model (Category name is sport) so if search ?q=ju output should show only jungle (working with above code) and if search ?q=sport output should show only jungle (but not cuop) -
Django "OperationalError at /admin/login/ no such table: institutemanagement_customuser"
I want to extend default Django User Model. I have done this code for that purpose and made migrations by every mean but facing the same error "OperationalError at /admin/login/ no such table: institutemanagement_customuser". Below is my settings.py and models.py file settings.py """ Django settings for studentmanager project. Generated by 'django-admin startproject' using Django 2.2.3. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!uc)2%be(w4c4%xn^3z@pmj5l2$(zor_2l1_g%bu!ggv3z^hy%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'institutemanagement.apps.InstitutemanagementConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'studentmanager.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'studentmanager.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } … -
Django admin inline modify can not be saved
I'm using django-admin to serve my page. And when I use the TabularInline, I can save the form. But when I do some modify, the form can not be saved. I did some search and seems there is no others have the same issue. The sample code is here https://paste.fedoraproject.org/paste/sGfyBWoUz5SblzEZpcWjkw . Does anyone can give me some suggestion? class Release(models.Model): id = models.AutoField(primary_key=True, editable=False) version = models.CharField(max_length=16, blank=False, null=False, unique=True) note = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'release' class CurrentFirmware(models.Model): id = models.AutoField(primary_key=True, editable=False) release = models.ForeignKey(Release, on_delete=models.CASCADE) version = models.CharField(max_length=255) build = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'current_firmware' class CurrentFirmwareInline(admin.TabularInline): model = CurrentFirmware fields = ('version', 'build') extra = 1 class ReleaseAdmin(admin.ModelAdmin): inlines = [CurrentFirmwareInline, ] admin.site.register(Release, ReleaseAdmin) What I want is when I make some change on current firmware. It can be updated to the current_firmware table. Such as remove a record, modified an exists record, or add an record. -
Querying many-to-many relationship returns nothing
I'm making a queryset: def get_context_data(self, name, **kwargs): context = super(ListDetailsOfTestSuite, self).get_context_data(**kwargs) context['test_suite'] = TestSuite.objects.filter(name=name) temp = TestSuite.objects.get(name=name) context['test_cases'] = temp.test_cases.all() return context models: class TestCase(models.Model): name = models.CharField(max_length=200) documentation = models.CharField(max_length=2048, blank=True) steps = models.CharField(max_length=2048, blank=True) tags = models.CharField(max_length=200, blank=True) setup = models.CharField(max_length=2048, blank=True) teardown = models.CharField(max_length=2048, blank=True) template = models.CharField(max_length=200, blank=True) timeout = models.IntegerField(default=10) def __str__(self): return self.name class TestSuite(models.Model): name = models.CharField(max_length=200) documentation = models.CharField(max_length=2048, blank=True) setup = models.CharField(max_length=2048, blank=True) teardown = models.CharField(max_length=2048, blank=True) force_tags = models.CharField(max_length=200, blank=True) timeout = models.IntegerField(default=10) # user can have multiple test suites user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) # Suite can contain a list of test cases but also a number of other test suites test_cases = models.ManyToManyField(TestCase, through='SuiteCaseThroughModel') def __str__(self): return self.name class Meta: ordering = ('name',) class SuiteCaseThroughModel(OrderedModel): test_case = models.ForeignKey(TestCase, on_delete=models.CASCADE) test_suite = models.ForeignKey(TestSuite, on_delete=models.CASCADE) order_with_respect_to = 'test_suite' However I'm getting nothing and I'm confident that the problem is in the filtering condition, because when I run context['test_cases'] = TestCase.objects.all() I get what I expect. The idea is to retrieve all test cases from a particular test suite, hence with little bit of research I came up with: temp = TestSuite.objects.get(name=name) context['test_cases'] = temp.test_cases.all() -
Django redirect to another view
I have small problem with redirecting from one view to another according to Django topic. Already read some answers like: ans_1, ans_2, but can't find solution. My view functions: def add_day_tasks(request): users = User.objects.all() if request.method == "POST": ... return redirect('add_tasks_continue', data=locals()) def add_tasks_continue(request, data): ... return render(request, 'eventscalendar/add_task_continue.html', locals()) My url: app_name = 'calendar' urlpatterns = [ url(r'^$', calendar), url(r'^calendar/add_day_task/$', add_day_tasks), url(r'^calendar/add_task_continue/$', add_tasks_continue, name='add_tasks_continue'), ] Thank you all for your time -
Dymaically generating form choices from db content
Using rest frameworks serializers and renderes, I want to generate a html radio button input that takes its choices from a field in the database. For example, given I have "A", "B", and "C" as content of an organizations model, I want a from with these three choices as radio buttons. Can you use standard model serializers to do this?