Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting ProgrammingError at ... using Heroku
I made some changes to my models.py file and now I return this error when I try to access my heroku app's admin page: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) The above exception (column testingland_mapcafes.cafe_image_url does not exist LINE 1: ...s"."venue_type", "testingland_mapcafes"."source", "testingla... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1828, in changelist_view 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File … -
How do i make my categories function correctly?
so im trying to seperate my blog posts into different categories but right now it all just appears as my username blogcategory.html {% extends "base.html" %} {% block page_content %} <div class="col-md-8 offset-md-2"> <h1>{{ category | title }}</h1> <hr> {% for post in posts %} <h2><a href="{% url 'blogdetail' post.pk%}">{{ post.title }}</a></h2> <small> {{ post.created_on.date }} | Categories: {% for category in post.categories.all %} <a href="{% url 'blogcategory' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> <p>{{ post.body | slice:":400" }}...</p> {% endfor %} </div> {% endblock %} blogdetail.html {% extends "base.html" %} {% block page_content %} <div class="col-md-8 offset-md-2"> <h1>{{ post.title }}</h1> <small> {{ post.created_on.date }} |&nbsp; Categories:&nbsp; {% for category in post.categories.all %} <a href="{% url 'blogcategory' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> <p>{{ post.body | linebreaks }}</p> <h3>Leave a comment:</h3> <form action="/blog/{{ post.pk }}/" method="post"> {% csrf_token %} <div class="form-group"> {{ user.username|default:'Guest' }} </div> <div class="form-group"> {{ form.body }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <h3>Comments:</h3> {% for comment in comments %} <p> On {{comment.created_on.date }}&nbsp; <b>{{ user.username|default:'Guest'}}</b> wrote: </p> <p>{{ comment.body }}</p> <hr> {% endfor %} </div> {% endblock %} blogindex {% extends "base.html" %} {% block page_content %} <div … -
No module named 'corsheaders' docker-compose up
Hy everyone! I'm new in the Django world. I develop a Django website and I want to make a Docker container with the appliation and run it on my localhost. I created my Dockerfile and my docker-compose.yaml but when I run docker-compose up it gives the following error. Attaching to mysite-web-1 mysite-web-1 | Watching for file changes with StatReloader mysite-web-1 | Exception in thread django-main-thread: mysite-web-1 | Traceback (most recent call last): mysite-web-1 | File "/usr/local/lib/python3.10/threading.py", line 1009, in _bootstrap_inner mysite-web-1 | self.run() mysite-web-1 | File "/usr/local/lib/python3.10/threading.py", line 946, in run mysite-web-1 | self._target(*self._args, **self._kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper mysite-web-1 | fn(*args, **kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run mysite-web-1 | autoreload.raise_last_exception() mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception mysite-web-1 | raise _exception[1] mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/init.py", line 381, in execute mysite-web-1 | autoreload.check_errors(django.setup)() mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper mysite-web-1 | fn(*args, **kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/init.py", line 24, in setup mysite-web-1 | apps.populate(settings.INSTALLED_APPS) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate mysite-web-1 | app_config = AppConfig.create(entry) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 223, in create mysite-web-1 | import_module(entry) mysite-web-1 | File "/usr/local/lib/python3.10/importlib/init.py", line 126, in import_module mysite-web-1 | return _bootstrap._gcd_import(name[level:], … -
Unable to run django test in CircleCI
I am implementing CircleCI for one of the projects. The project is built on Django 3.2. My test cases run properly when I run using python manage.py test blog, when I run the same in CircleCI it returns , ====================================================================== ERROR: project.blog (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: project.blog Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'project.blog' Here is my CircleCI config version: 2 jobs: build: docker: - image: circleci/python:3.8 steps: - checkout - run: name: Installing dependencies command: | python3 -m venv venv . venv/bin/activate pip3 install -r requirements.txt - run: name: Running migrations command: | . venv/bin/activate python manage.py migrate --skip-checks - run: name: Running tests command: | . venv/bin/activate python manage.py test blog I understand that CircelCI clones the project in project folder. Is that something that I am missing in config? -
defaultdict new structure in django
i have this defaultdict(list) in my outout defaultdict(<class 'list'>, {'List of tubes': ['2324', '98', '7654', 'List of auto:': [147, 10048, 1009, 10050, 10, 1647, 10648, 649, 1005]}) How i can add a space inside AND WITOUT {(, ? to obtain 'List of tubes': '2324', '98', '7654' 'List of auto:': 147, 10048, 1009, 10050, 10, 1647, 10648, 649, 1005 -
Django display date with user current timezone
I have such model class SomeModel(models.Model): some_field = models.CharField(max_length-100) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Created at')) settings.py TIME_ZONE = "UTC" USE_TZ = True The problem: in postgres created_at value is 2022-01-19 01:18:29.096177+03 now I want to show the user, that object was created on 2022-01-19. But when I call created_at.date() it shows 2022-01-18 How to fix that? -
Django formset labels
I am creating a hosptial management system.For this query on stackoverflow there are four models in play. Order, Pharmacyitem, PharmacySalesBills and Inventory, with formsets set up for PharmacyItem and Order. The natural flow of the creating a pharmacy item, populating a sales bill and inventory work as they should. I.e date, new sales item record created and adjustment to inventory stock and sales bill generated using sales item. My idea is for a doctor to create a order, the pharmacist, does a search at any given time on the order model, and uses the model as a bridge to the pharmacy sales item model, to get quantity and name of product and patient from order object. and then using a booleanfield on the order model, which changes to true once the pharmacy item / sales bill has been created. Question: If a doctor prescribes 3 items, via template using formset, and each form in formset, will have its own id. Do i create an additional field in the order model, that acts as an identifier for the current order [so using the above example all 3 items]. Or is there a way formset can take a label, that shows the … -
How to work with foreign key with mutiple selection
Hi Everyone i am trying to achieve select multiple car with foreign key relation because we need to store data with mutiple row, i am tried with manytomany fied but this is not effective as per our requirement, thats way i am trying solve this with foreign key, pls help me out. models.py class Car_team(BaseModel): team = models.ForeignKey( Team, models.CASCADE, verbose_name='Team', null=True, ) car=models.ForeignKey( Car, models.CASCADE, verbose_name='Car', null=True) city =models.ForeignKey( City, models.CASCADE, verbose_name='City', ) start_date=models.DateField(null=True, blank=True) end_date=models.DateField(null=True, blank=True) forms.py class CarTeamForm(forms.ModelForm): start_date=forms.DateField(initial=datetime.date.today, label='Start Date') car = forms.ModelMultipleChoiceField(queryset=Car.objects.all(), required=True, widget=forms.CheckboxSelectMultiple) class Meta: model = Car_team fields = ['car','team','city','start_date'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(CarTeamForm, self).__init__(*args, **kwargs) self.fields['start_date'].widget.attrs['readonly'] = True widgets = { 'car': forms.CheckboxSelectMultiple(attrs={'class': 'form-control select2'}), } views.py def add_carteam(request, city_id=None, id=None): if id is not None: carteam = get_object_or_404(Car_team, city_id=city_id, pk=id) else: carteam = None if request.method == 'POST': form = CarTeamForm(request.POST, request.FILES,instance=carteam) if form.is_valid(): car = form.cleaned_data['car'] team = form.cleaned_data['team'] start_date = Car_team.objects.filter(car__in=car).values_list('start_date', flat=True).filter(end_date__isnull=True) # if start_date: # messages.error(request,'Car already assigned to another team!') query = Car_team.objects.filter(car__in=car).exists() query_set = Car_team.objects.filter(car__in=car).values_list('team', flat=True) team_name = Team.objects.filter(pk__in=query_set).values_list('name', flat=True) car_id = Car_team.objects.filter(car__in=car).values_list('car', flat=True) car_number=Car.objects.filter(pk__in=car_id).values_list('car_number', flat=True) if query_set and start_date: messages.error(request,'Car already assigned to team {} {}!'.format(team_name,car_number)) # if query: # … -
Attach additional data to Django Rest (DRF) request object only when user logs in
I have a Branch model that contains all the branches a user could be a part of. Another model UserBranchRelation that contains the relation of a user with a particular branch. Each user has a particular role inside a particular branch. Admin users have more permissions as compared to a simple member. Moreover, a user could be an admin inside one branch and a member in another. I am trying to come up with a neat solution that would let me attach the user's branch and role to the request object on login. Now whenever an authenticated request is received, I should not need to fetch the branch repeatedly as it would already have been attached to the request object on successful login. Inside my views, I would then use permissions to return data based on user's branch and limit access based on role. Here are my models. # Branch Model class Branch(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) # User and Branch relationship class UserBranchRelation(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.CASCADE) role = models.CharField( max_length=20, choices=RoleChoices.choices, default=RoleChoices.MEMBER ) -
App not compatible with buildpack - django project with java script
When I try to deploy my app to Heroku then I received: -----> Building on the Heroku-20 stack -----> Using buildpacks: 1. heroku/python 2. https://github.com/heroku/heroku-buildpack-static.git -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I've been trying to spend a lot of time. Most of the solution is not working. Is it a buildpack issue or something else? Additionally, I connected my GitHub account to Heroku and tried deploying from the GitHub main branch. However, I still receive the error. Here is my GitHub address: https://github.com/Whitemoon2000/Final-year-project -
can't use setUpTestData variable in setUp
i define this line of code in but i got self.user not define user class TestSample(TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() business = BusinessFactory() cls.user = business.main_owner def setUp(self): self.api_client = APIClient() self.client, self.token, self.user = self.client_login( self.api_client, phone=self.user ) -
Django - django.db.utils.IntegrityError: duplicate key value violates unique constraint
I'm trying to build a server at django that will hold my mobile device update files: class updates(models.Model): namedev = models.CharField(max_length=200) devip = models.CharField(max_length=200) nameupdate = models.CharField(max_length=200) datesend = models.DateTimeField(max_length=200) status = models.CharField(max_length=100) And every time I use the "create ()" function it fails to create a column in the database, def create(nameDev,ipDev,nameUpdate,dataSend,status): updates.objects.create(namedev=nameDev,devip=ipDev, nameupdate=nameUpdate,datesend=dataSend,status=status) print("------------------------------test1-------------------------") and I get it: [enter image description here][1] [enter image description here][1] -
Button behavior in django template (href + function)
I have a next problem: <div class="col-4"> <a class="btn btn-warning" href="{% url 'home' %}" role="button">Save and Back</a> {{ request | mail}} </div> The logic is next: I want to click on button and send an email with redirecting to home page. My mail is a filter tag. Unfortunately I can't add my filter to the view, because I am using this view in another place, where I don't want to send an email. My current solution send an email before click on button. Do you have any idea? -
Django custom template tags to remove specific URL query strings
I'm trying to create a simple tag for a django template which removes a specified URL query string. It's purpose is to remove some applied filtering, ie remove saved=1 from http://localhost/?saved=1&source=news&week=5 I have created a custom tag: @register.simple_tag(takes_context=True) def defilter(context, *args): query = context['request'].GET.copy() for key in args: if key in query.keys(): query.pop(key) return query.urlencode() I have then created a link in a django template which recontructs the url get paramters but removes the specified key: <a href="{% url 'articles' %}?{% defilter saved %}">Remove Saved</a> Any ideas why this isn't working the way I expect? I get no errors, it just doesn't remove the specified key. Many thanks -
Django: Is it possible to select unique combinations of two foreign keys without the use of distinct?
I have the following models: class Exercise(models.Model): name = models.CharField(max_length=300) # ... class UserWorkout(models.Model): user = models.ForeignKey(User) # ... class WorkoutSet(models.Model): exercise = models.ForeignKey(Exercise) user_workout = models.ForeignKey(UserWorkout, related_name="sets") date_time = models.DateTimeField(default=timezone.now) weight = models.DecimalField(max_digits=10, decimal_places=6) # ... This is example data for the WorkoutSet model to get a better picture: ID weight DateTime Exercise UserWorkout - 10.0 22/02/2022 3 UUID('755925da-9a43-490c-9ffa-3222acd1dcfa') - 15.0 22/02/2022 3 UUID('755925da-9a43-490c-9ffa-3222acd1dcfa') - 15.0 22/02/2022 3 UUID('755925da-9a43-490c-9ffa-3222acd1dcfa') - 55.0 24/02/2022 5 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') - 57.5 24/02/2022 5 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') - 15.0 24/02/2022 3 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') - 20.0 24/02/2022 3 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') I'm trying to filter this data so it shows how many times each exercise has been performed (i.e. how many workouts it's associated with). So the above data would look like: Exercise UserWorkout 3 UUID('755925da-9a43-490c-9ffa-3222acd1dcfa') 5 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') 3 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') Ultimately I'm going to count how many times each Exercise has been done like this: qs = # some filter statement qs = qs.values('exercise').annotate(frequency=Count('exercise')) I can't use distinct because it doesn't work with annotate: NotImplementedError: annotate() + distinct(fields) is not implemented. Is what I'm trying to achieve possible? Perhaps through a subquery? My SQL is rusty so not sure if that's possible at all. -
Django API return user's data after login
i am using KnoxLogin and when i login , it's return only token and expire date , i want to return more information for example which group contain and etc... models.py class Organization(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(default='0000000',max_length=100) type = models.CharField(default='0000000',max_length=20) owner_id = models.CharField(default='0',max_length=100) def __str__(self): return str(self.name) class User_org(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User,related_name='UserInfo', on_delete=models.CASCADE) organization = models.ForeignKey(Organization,related_name='UserInformation',on_delete=models.CASCADE) def __str__(self): return str(self.user) views.py # Login API class LoginAPI(KnoxLoginView): permission_classes = [permissions.IsAuthenticated,] def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer2 = OrganizationSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return Response(serializer2) and this is my organization serializer and want to show this fileds after login , how do this ? class OrganizationSerializer(serializers.ModelSerializer): UserInformation = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = Organization fields = '__all__' -
How to give unique together in flask?
I am defining a table in Flask like groups = db.Table( "types", db.Column("one_id", db.Integer, db.ForeignKey("one.id")), db.Column("two_id", db.Integer, db.ForeignKey("two.id")), UniqueConstraint('one_id', 'two_id', name='uix_1') #Unique constraint given for unique-together. ) But this is not working. -
How can I integrate MDB(Material Bootstrap Design) with Django? and what is the suitable files tree organization
How can I integrate MDB(Material Bootstrap Design) with Django? -
TemplateDoesNotExist Error Django not-defined template appers
First, I got an error message on web browser here. It says, 'TemplateDoesNotExist at / index.html, base/item_list.html'. Console error message says, Internal Server Error: / Traceback (most recent call last): File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\template\response.py", line 63, in resolve_template return select_template(template, using=self.using) File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\template\loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: pages/index.html, base/item_list.html [23/Feb/2022 16:19:38] "GET / HTTP/1.1" 500 83837 In the first place, I don't even create or declare 'base/item_list.html' in any file in Django project. I've created 'config' project and 'base' app. Project 'config' file organization here. App 'base' file organization here. config/urls.py here. from django.contrib import admin from django.urls import path from base import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.IndexListView.as_view()), ] base/views/item_views.py here from django.shortcuts import render from django.views.generic import ListView from base.models import Item class IndexListView(ListView): model = Item template_name = 'pages/index.html' base/views/init.py here. from .item_views import * So, templates/pages/index.html here. {% extends 'base.html' %} {% block main %} {% for object in object_list %} <p> <a href="/items/{{object.pk}}/"> {{object.name}} … -
"'str' object has no attribute 'tag'" error in Django Tutorial
I am following the Django Tutorial to learn how to work with it, but I have encountered an error very early in it and I'm not sure how to fix it. It happened while creating the django project and doing the 'Write your first view' section: https://docs.djangoproject.com/en/dev/intro/tutorial01/#write-your-first-view After following those steps carefully, while executing python3 manage.py runserver the following error appears: AttributeError: 'str' object has no attribute 'tag' This is the full error trace: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/home/noctis/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/noctis/.local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/noctis/.local/lib/python3.9/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/home/noctis/.local/lib/python3.9/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/noctis/.local/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/noctis/.local/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/noctis/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 448, in check for pattern in self.url_patterns: File "/home/noctis/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/noctis/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/noctis/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/noctis/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File … -
How to pass a list of dictionaries in a function?
I am working on a teacher grading system in Django. I want functionality in which there is some entry like subject id and student's marks from the frontend. My app on the backend takes these two-parameter and creates a list of dictionaries with subject id and marks and pass it on another function and that function will sum up all the marks and give me a total and next average and percentage etc. But right now, I am stuck with total only so, when I pass this list of dictionaries in a function it gives me an error. class Marks_entry: def marks_entry(subject_id, marks): try: subject_id = int(input(f'Enter subject id: ')) marks=int(input(f'Enter marks: ')) except ValueError: print(f'You can only try integers:') marks_entry=[] marks_entry.append({ "subject_id": subject_id, "marks": marks }) marks_calculation = marks_calculation(marks_entry) return marks_calculation def marks_calculation(marks_entry): total = sum(item['marks'] for item in marks_entry) return total marks=0 subject_id= 0 b= Marks_entry b.marks_calculation(marks, subject_id) error is: Enter subject id: 1003 Enter marks: 58 Traceback (most recent call last): File "c:\Users\Lenovo\Documents\TGS\controller.py", line 53, in <module> b.marks_entry(subject_id, marks) File "c:\Users\Lenovo\Documents\TGS\controller.py", line 43, in marks_entry marks_calculation = marks_calculation(marks_entry) UnboundLocalError: local variable 'marks_calculation' referenced before assignment -
Django / GraphQL -- 2 types have fields that are referencing each other causes a crash
I have 2 graphql types that each have fields that refer to the other. There is an error because one of the types has not been declared when the first one is read. The issue is that the type should be instantiated before using it in a field. But since the two types refer to each other, One is always being referred to before it has been instantiated. Any ideas on how to solve? Here is a link to the parts of the code that are relevant: https://gist.github.com/olivermontalbano/ce8db9fd62619b983ed68b6933ff7e64 -
Django ManyToManyField with through -- how can I not lose data not selected in the QuerySet?
Django Newbie here. I have some trouble with a ManyToMany relationship and a through field. I am trying to create a tool where staff members can apply for shifts on events (Bar, entry control, etc.). Therefore I created a Staff object (this is the person with all her roles etc.) and linked it by ManyToManyField to a ScheduledShift object (which contains event date, time and duties). I want to be able to present each day as a view to the user where he/she can just tick the shifts he/she is available that day. This works and it also writes the correct data (i.e. the staff id and the shift id for all the shifts he/she ticked) for that day into the "through" table (StaffShift object). The relevant code looks like this: models.py class Staff(models.Model): ... shifts = models.ManyToManyField(ScheduledEventShift, through='StaffShift') class StaffShift(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE) shift = models.ForeignKey(ScheduledEventShift, on_delete=models.CASCADE) views.py class StaffShiftUpdateView(ObjectUpdateView): model = Staff ... def get_form(self, form_class=None): form = super().get_form(form_class=self.form_class) day = datetime(self.kwargs.get('year'), self.kwargs.get('month'), self.kwargs.get('day')) form.fields['shifts'].queryset = ScheduledEventShift.objects.filter( event__event_date=day).order_by('event__event_date') return form ('event' is a property in the ScheduledEventShift object) My problem is that by writing those ids into the through table, all other rows for that user that … -
I'm trying to save an image using django html form without using model ! is it possible
I am getting attribute error. AttributeError at /file_upload 'TemporaryUploadedFile' object has no attribute 'save' views.py Thank you so much -
how to filter by month from template
I'm attempting to channel a datetime field by month and year. Though no one can really say why while entering both month and year I get back a vacant set returned. Model class SpareParts(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) amount = models.IntegerField(blank=False, null=False) date = models.DateField(blank=False, null=False) And i want to filter on the basis of vehicle and month vise and here is mine view VIEWS.py def view_spare(request): sparepart = SpareParts.objects.all() vehicle_filter = request.POST.get('vehicle') # get the value of the date field month_filter = request.POST.get('month') # get the value of the date field if vehicle_filter: if month_filter: sparepart = sparepart.filter(vehicle=vehicle_filter,date__month=month_filter).aggregate(Sum('amount')) return render(request,'invoice/spare_parts_list.html',{'sparepart':sparepart}) and i want render the whole month sum of amount in template