Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get data from another database
I have created superuser(Admin)inside Admin, I have created a button and after clicking on it is should show data of another database table after clicking on button it should show all data of another Database table inside superuser(Admin) -
Django : Template not found/index.html
I am running a website using Django. There is no problem in login. When i logged in and click on some dashboard, it is showing "page not found"(404). Views.py: def index(request): return(request,'obs_app/index.html') Settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates/index.html') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], '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', ], 'libraries': { 'get_by_index':'obs_app.templatetags.templatefilters', 'get_by_key':'obs_app.templatetags.templatefilters', 'get_dict':'obs_app.templatetags.templatefilters', 'get_items':'obs_app.templatetags.templatefilters', 'multiple':'obs_app.templatetags.templatefilters', }, }, }, ] urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url from obs_app import views urlpatterns = [ url(r'index/',views.index , name = 'index'), path('admin/', admin.site.urls), path('', views.user_login, name='user_login'), path('dashboard',views.obs_index, name='admin_dash'), path('halls/active',views.obs_halls_active,name='active-halls'), path('halls/pending',views.obs_halls_pending,name='pending-halls'), path('febs/userlist', views.febs_user_list, name='febs-users'), path('bookings/user', views.bookings_user, name='bookings-users'), path('bookings/owner', views.bookings_owner, name='bookings-owner'), path('cancellation/user', views.cancelled_user, name='cancelled-user'), path('cancellation/owner', views.cancelled_owner, name='cancelled-owner'), path('terms/obs', views.terms_conditions, name='terms-conditions'), path('terms/febs', views.terms_febs, name='terms-febs'), path('terms/febs/events', views.terms_febs_events, name='terms-febs-events'), Error i am getting is : Page not found (404) The current path, index.html, didn't match any of these. -
Conditionally nest Django serializers
So, I have a foreign key to my User model in many of my models. Now, the serializers for these models are nested, in that they include the entire user object rather than just the id. I have done so as shown bellow: class BadgeSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Badge fields = '__all__' It works as expected. However, I seldom find myself in a situation where I want just the id. I was wondering if there is a way to conditionally nest my BadgeSerializer... -
Unsuccessful command execution on instance id(s)
I am trying to deploy my app on AWS but it seems to stuck at this point: Uploading: [##################################################] 100% Done... 2019-10-22 11:01:57 INFO Environment update is starting. 2019-10-22 11:02:00 INFO Deploying new version to instance(s). 2019-10-22 11:02:09 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2019-10-22 11:02:10 ERROR [Instance: i-#######] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2019-10-22 11:02:10 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2019-10-22 11:02:10 ERROR Unsuccessful command execution on instance id(s) 'i########'. Aborting the operation. 2019-10-22 11:02:11 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. It says that my requirements.txt is invalid, Why ? Requirement.txt Django django-crispy-forms==1.7.0 pytz==2017.3 gunicorn==19.9.0 django-widget-tweaks psycopg2 Please help me in figuring out what I am doing wrong. -
Django form save related object only if form is valid
I think I have a rather uncommon feature here, at least I couldn't find a answer. What I'd like to achieve is a text input with autocomplete on a related model with its label field. the given text should then get_or_create the related model. this already works but the problem is, that the new related model instance is saved on form submit no matter if the form is_valid or not. given the following situation and implementation (shortened for better overview) class Correspondent(models.Model): label = models.CharField(_("label"), max_length=100, unique=True) class Document(BaseModel): correspondent = models.ForeignKey( Correspondent, verbose_name=_("correspondent"), on_delete=models.PROTECT, related_name="documents", ) with the following form: class DocumentForm(forms.ModelForm): correspondent = forms.CharField( label=_("correspondent"), widget=forms.TextInput(attrs={"class": "awesomplete"}) ) class Meta: model = Document exclude = ["created_by", "modified_by"] def clean_correspondent(self, *args, **kwargs): # ToDo: don't save the FKed instance if complete form isn't valid user = self.initial["user"] data = self.cleaned_data["correspondent"] errors = {} try: obj = Correspondent.objects.get(label=data) except: obj = Correspondent(label=data, created_by=user, modified_by=user) obj.save() return obj so the problem here is obj.save() which is called before form.is_valid() and I couldn't figure a way yet how to solve this. I'd like to prevent the creation of a new Correspondent instance if the form isn't valid yet. Let me know if … -
Python Django: Count business days
I need to count business days between two dates. In addition, I must also remove the days listed in a separate table (holidays). So far I have this code. It counts the days but does not remove the days from the separate table (holidays). class Holidays(models.Model): class Meta: ordering = ['date'] date = models.DateField(null=True, verbose_name='Date') class Situation(models.Model): class Meta: ordering = ['date_time_start'] date_time_start = models.DateTimeField(null=True, blank=False, verbose_name='Date/Time Start') date_time_end = models.DateTimeField(null=True, blank=False, verbose_name='Date/Time End') @property def business_days(self): holidays = Holidays.objects.values_list('date', flat=True) oneday = datetime.timedelta(days=1) dt = self.date_time_start.date() total_days = 0 while (dt <= self.date_time_end.date()): if not dt.isoweekday() in (6, 7) and dt not in holidays.values(): total_days += 1 dt += oneday return total_days -
Exception in thred django-main-thread:
Creating forms from models i'm new to django and try to models form but unfortunate get some bizarre error even i twice check my code as well i checked django documentation but not figure out my issue... i visit this django documentation but not figure out yet!!! quite confusing! https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/ Traceback (most recent call last): File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in … -
Django join two models in ListApiView
I listed blog post using django rest api View.py class BlogDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Blog.objects.all() serializer_class = serializers.BlogSerializer models.py class Blog(models.Model): title = models.CharField(max_length=50) content = models.TextField() content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category_id = models.CharField(max_length=50) class Category(models.Model): category_id = models.TextField() category_title = models.TextField() serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'title', 'content', 'created_at',) model = models.Blog But i want to list the blogs under different categories. How to join Cart and Blog model?. Here category id are common in two models. -
__name__ attributes of actions defined in <class 'astromatchapp.report.admin.user.ReportUserAdmin'> must be unique
ERRORS: <class 'astromatchapp.report.admin.user.ReportUserAdmin'>: (admin.E130) __name__ attributes of actions defined in <class 'astromatchapp.report.admin.user.ReportUserAdmin'> must be unique. <class 'astromatchapp.web.admin.user.UserAdmin'>: (admin.E130) __name__ attributes of actions defined in <class 'astromatchapp.web.admin.user.UserAdmin'> must be unique. ?: (urls.E007) The custom handler404 view 'astromatchapp.web.views.http_error.handler404' does not take the correct number of arguments (request, exception). After migrate to my manage.py this error has been generated. -
'in <string>' requires string as left operand, not BoundWidget sendgrid
I am working on a django web application. I have a contact us form. when a user submits the form, the message in the form is sent as a mail to a predefined email id. For sending the email, I am using sendgrid. I created an account and generated an api for this purpose. I stored the api key in a dotenv file and access the api in the settings.py file .env file SENDGRID_API_KEY=XXXXXXXXXXXXXXXXXXXX settings.py import os from dotenv import load_dotenv load_dotenv() ... EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY") views.py def index(request): if request.method == "POST": ContactUsForm = ContactUs(request.POST) if ContactUsForm.is_valid(): firstName = ContactUsForm['firstName'] fromEmail = ContactUsForm['email'] message = ContactUsForm['message'] send_mail(subject=f"{firstName} sent you a message", message=message, from_email=fromEmail, recipient_list=['toaddress@email.com']) return redirect('home') else: ContactUsForm = ContactUs() context = {'contactUs': ContactUsForm} return render(request, 'index.html', context) But when I submit the form, I get this error message TypeError: 'in <string>' requires string as left operand, not BoundWidget I dont know where I went wrong. This is the link I followed to send emails with sendgrid -
Why am i getting importerror: module not found when i have it installed already?
I am migrating from django-sqlite3 to postgresql and so I have installled postgresql and required modules(psycopg2) in my apache2 server. I have installed psycopg2 correctly- >>> import psycopg2 >>> psycopg2.__version__ '2.8.4 (dt dec pq3 ext lo64)' >>> psycopg2._psycopg.__version__ '2.8.4 (dt dec pq3 ext lo64)' Yet, it throws an error as follows-ImportError: No module named psycopg2._psycopg(as shown in my error.log file) I have searched all threads on stackoverflow and github but couldnt find any solution. -
how to import csv data to postgres database using python
I am trying to import the data in my excel sheet to the postgresql database using python, and when i do that i get the following error. i have already converted my excel to csv and then tried using the 'copy' statement to import the data to postgres database. import psycopg2 conn = psycopg2.connect("host=localhost dbname=djangotest user=postgres password=*******") cur = conn.cursor() with open('C:\\Users\\********\\Desktop\\excelsheet.csv', 'r') as f: next(f) # Skip the header row. cur.copy_from(f, 'us_arrays', sep=',') conn.commit() psycopg2.errors.BadCopyFileFormat: missing data for column "ip_address_or_service_machine" CONTEXT: COPY us_arrays, line 1: "(CMDB)",.Device Type,.Frame or Data Tier,.Corp Device,.Encrypt Enabled,.Dedicated Device,".IP Addres..."``` -
Object of type OAuthConnection is not JSON serializable
I'm retrieving products using the bigcommerce API using the following code def get_bigcommerce_products(request): a = api.Products.all() return json.dumps(a) I need a response in JSON. So I used json.dumps. But it's giving me the following error 'Object of type OAuthConnection is not JSON serializable'. I've tried to convert it into a dictionary but not working. So please help me with this. I'm using Python 3.7 and Django 2.2. -
AttributeError: 'UserProfile object has no attribute 'artist_category' django
i have three model i am trying to creating to create Artist and UserProfile when user register this part working fine and i also want to update Artist model when i update UserProfile. models.py: custom user model: class CustomUser(AbstractBaseUser, PermissionsMixin): artist_choice = [ (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ] artist_category = models.IntegerField(choices=artist_choice, null=True) email = models.EmailField(max_length=100, unique=True) name = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) last_login=models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD='email' REQUIRED_FIELDS=[] objects=UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) artist model: class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) name = models.CharField(max_length=100) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return self.name profile model: class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) name = models.CharField(max_length=100) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return self.name creating profile after user register: def create_profile(sender,**kwargs ): if kwargs['created']: user_profile=UserProfile.objects.get_or_create(user = kwargs['instance']) post_save.connect(create_profile,sender=CustomUser) this is the part when i am getting error: … -
Django - Multiple custom models on the same form
I'm using Django 2.1 and PostgreSQL. My problem is that I'm trying to create a form to edit two different models at the same time. This models are related with a FK, and every example that I see is with the user and profile models, but with that I can't replicate what I really need. My models simplified to show the related information about them are: # base model for Campaigns. class CampaignBase(models.Model): .... project = models.ForeignKey(Project, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) .... # define investment campaign made on a project. class InvestmentCampaign(models.Model): .... campaign = models.ForeignKey(CampaignBase, on_delete=models.CASCADE, null=True, blank=True) description = models.CharField( blank=True, max_length=25000, ) .... And the form that I want to create is one that includes the end_date of the FK CampaignBase, and the Description from the InvestmentCampaign. Now I have this UpdateView to edit the InvestmentCampaign, and I need to adapt to my actual needs, that are also update the CampaignBase model: class ProjectEditInvestmentCampaignView(LoginRequiredMixin, SuccessMessageMixin, generic.UpdateView): template_name = 'webplatform/project_edit_investment_campaign.html' model = InvestmentCampaign form_class = CreateInvestmentCampaignForm success_message = 'Investment campaign updated!' def get_success_url(self): return reverse_lazy('project-update-investment-campaign', args=(self.kwargs['project'], self.kwargs['pk'])) # Make the view only available for the users with current fields def … -
'Game' object does not support item assignment
Getting error 'Game' object does not support item assignment games = [] for i in range(len(filterList)): durations = findDurationInHour(filterList[i].startDate,filterList[i].endDate) filterList[i]['duration'] = durations games.append(filterList[i]) filterList = games i am trying to add duration into array object as a key. but on line filterList[i]['duration'] = durations getting error: 'Game' object does not support item assignment -
Why am I getting form is invalid error in django?
During development of website in Django web framework I am getting form is invalid error when validating form. I have searched online for solution but not able to solve my problem. My files are as below. models.py class Customer(models.Model): f_name = models.CharField(max_length = 30, null=True) last_name = models.CharField(max_length = 30, null= True) cont_no = models.CharField(max_length = 30, null= True) pincode = models.IntegerField(default=0) def __str__(self): return self.f_name class Product(models.Model): name = models.CharField(max_length = 30, null= True) uniq_price = models.IntegerField(default=0) def __str__(self): return self.name class Order(models.Model): cust_name = models.ForeignKey(Customer,related_name='first_name', on_delete=models.CASCADE) prod_name = models.ForeignKey(Product, related_name='uniqe_price', on_delete=models.CASCADE) unit_price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) total = models.IntegerField(default=0) forms.py class CustomerForm(forms.ModelForm): class Meta: model = Order fields = "__all__" views.py def add_order(request): if request.method == "POST": form = CustomerForm(request.POST) form.save() return redirect("place_ord") else: form = CustomerForm() home.html <form id="myForm" action="{% url 'add_order' %}" method="POST"> {% csrf_token %} <h1>add order</h1> <label>Customer</label> <select id="custs" name="customer"> <option value="">Select Customer</option> {% for cust in customers %} <option id="{{ cust.id }}" value="{{ cust.f_name }}"> {{ cust.f_name }} </option> {% endfor %} </select><br><br> <label>Product</label> <select id="singleSelectTextDDJS" name="prods" onchange="singleSelectChangeText()"> <option>Select Product</option> {% for prod in products %} <option value="{{ prod.uniq_price }}"> {{ prod.name }} </option> {% endfor %} </select><br><br> <label>Price:</label> <input type="text" name="price" … -
how to set range in calendar for 1 week in Django
I want to set range Monday to Saturday in the calendar in Django where user can select the date between this date and on Sunday user can not change the date def tech_form(request): if request.method == "POST":form = TechForm(request.POST)if form.is_valid():start_date = datetime.date(2019, 1, 1)end_date = datetime.date(2020, 3, 31)Tech.objects.filter(pub_date__range=(start_date, end_date))form=form.save(commit=False)form.save()messages.success(request,"Form Submited succesfully")return redirect('tech')else:form = TechForm()return render(request, 'hellogymapp/forms/tech_form.html', {'form': form})def tech_form(request):if request.method=="POST":form =TechForm(request.POST)if form.is_valid():start_date = datetime.date(2019, 1, 1)end_date = datetime.date(2020, 3, 31)Tech.objects.filter(pub_date__range=(start_date,end_date))form=form.save(commit=False)form.save()messages.success(request,"Form Submited succesfully")return redirect('tech')else:form = TechForm()return render(request, 'hellogymapp/forms/tech_form.html', {'form': form}) please explain -
Can't run the Django Server
I want to run the Djando server. I did everything that requires to do it, but when I type the command " python3 manage.py runserver " nothing happened at all.. I've run " django-admin startproject "project_name" " Then run " cd "project_name" , but nothing happened Then ls And finally tried to run the server, but still nothing.. ' -
Django Call Python Function From Query
When I querying a Model in Django, I want to create a custom field (using "extra" function) which may use as a sorting field. For example, result = foo_model.objects.filter(active=True).extra(select={'cal_field': pythonFunction()}).extra(order_by=['cal_field']) I have 2 questions: Can I create a field which calling a Python function inside "extra"? If it can, how can I pass the current row into the function? Thanks a lot! -
Django admin save_model not advancing primary key in Postgres
So I have a function in the Django admin that allow me to create a duplicate MyModel in the database: def save_model(self, request, obj, form, change): if '_saveasnew' in request.POST: old_obj_id = resolve(request.path).args[0] old_obj = MyModel.objects.get(id=old_obj_id) obj.other_id = old_obj.other_id obj.status = old_obj.status obj.project_id = old_obj.project_id obj.test_url = old_obj.test_url obj.save() super(MyModelAdmin, self).save_model(request, obj, form, change) This creation works fine, but I have another system interacting with this database that is seeing insert failures for every time this function has been called. For example, if I create 2 duplicates entries in the Django admin this way, then the other system will see two errors like IntegrityError duplicate key value violates unique constraint "my_model_pkey" DETAIL: Key (id)=(1234) already exists. -
Ordering list by date of child page
So I have a list that is displaying individual blog pages and they are currently being order by last updated. However I want them ordered by post.specific.date. How can I do this? If more code is needed to help please say. {% for post in posts %} <div class="..."> <div class="..."> {% for item in post.specific.blogpage_images.all|slice:"1" %} {% image item.image fill-400x400-c100 %} <p>{{ item.caption }}</p> {% endfor %} </div> <div class="..."> <h3 class="...">{{ post.title }}</h3> <h5>{{ post.specific.intro }} <span class="...">{{ post.specific.date }}</span></h5> </div> <div class="..."> {{ post.specific.body|richtext }} <div class="..."> <div class="..."> <p> <button class="..."><b><a class="effect-shine" href="{% pageurl post %}">READ MORE »</a></b> </button> </p> </div> <div class="..."> <p> <span class="..."> <span class="..."> <a href="{% pageurl post %}#disqus_thread"> _ </a> </span> </span> </p> </div> </div> </div> </div> <hr> {% endfor %} -
Django Template overriding
I was wondering, when using templates in django, I'm able to extend other base templates and override some of the blocks in the base template. so my question is when I override, would the code in the overridden block still get rendered then overridden, or would it never be run and only the new block is rendered? Example: base.html {% block menu %} {% for option in menu %} ...Create the menu entries {% endfor %} {% endblock menu %} extender.html {% extends base.html %} {% block menu %} ... some other tags {% endblock menu %} In this case does the original for loop in the base.html run if it gets overridden? -
Django POST request in template (without form or a better solution)
I have a shopping cart and I want to add an object to that shopping cart. There is a button which I press and when that happens I want the request to go through. This is what I want to do in the POST request (When Button Is Pressed): Check for Item with the same id as the product I pressed. Create a CartItem with the same Item as the one I checked for above. Add that cart item to my shopping cart linked to my profile. (Not started work yet) Models: class Item(models.Model): name = models.CharField(max_length=100, null=True) info = models.CharField(max_length=100, null=True) price = models.IntegerField(default=0, null=True) discount = models.CharField(max_length=100, null=True, blank=True) discountPrice = models.IntegerField(default=0, null=True) inStock = models.BooleanField(default=False) imagefield = models.ImageField() reviews = models.ManyToManyField(Review, blank=True, related_name="itemreview") class Meta: verbose_name_plural = 'Items' def __str__(self): return "{name}".format(name=self.name) class CartItem(models.Model): item = models.ForeignKey(Item, blank=True, related_name="CartItem", on_delete=models.CASCADE) quantity = models.IntegerField(default=0, null=True) price = models.IntegerField(default=0, null=True) class Meta: verbose_name_plural = 'Cart Items' def __str__(self): return self.item.name def get_total_item_price(self): return self.quantity * self.item.price class ShoppingCart(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(CartItem, blank=True, related_name="orderitem") class Meta: verbose_name_plural = 'Shopping Carts' def __str__(self): return self.user.username def get_total(self): total = 0 for cart_item in self.items.all(): total += cart_item.get_total_item_price() … -
oTree (Django): How to show-hide single choice options depending on selection
I want to make a survey where you can 'accept', 'refuse' or ask for 'more information' (3 options). I already have set up all the single choices, but I need a certain programming into the 3rd option 'more information'. This is my thoughts: 1. Once you click on 'more information' 2.it should ask something like 'are you sure?' and then you can proceed with 'yes' or return to the question with 'no'; then if you click 'yes' a box appears where it gives you certain information and the 2nd 'more information' option appears; 3. then again it follows step 2. This one should be able up to 3 times, but it is not necessary to ask for more information and you can just 'accept' or 'refuse'. I don't know what I can do to approach this task question_1 = models.IntegerField( choices=[[20, 'Accept'], [-20, 'Refuse'], [-3, '1. More Information'], [-2, '2. More Information'], [-1, '3. More Information']], label='Choices', widget=widgets.RadioSelect )