Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use cookiecutter-django-mysql to initialize the project and execute python manage.py migrate to report an error
everyone. This is my first time asking a question on stackoverflow, please take care~ First I created the project through cookiecutter https://github.com/mabdullahadeel/cookiecutter-django-mysq and chose mysql5.7 as the storage database Second I specified the environment variable export DATABASE_URL=mysql://root:123123123@127.0.0.1:3306/polo_testing_platform export CELERY_BROKER_URL=redis://localhost:6379/0 export USE_DOCKER=No and I made sure my local mysql version is 5.7 mysql version is 5.7 Then I get an error when I execute python manage.py migrate error messages: Operations to perform: Apply all migrations: account, admin, auth, authtoken, contenttypes, django_celery_beat, sessions, sites, socialaccount, users Running migrations: Applying sites.0003_set_site_domain_and_name...Traceback (most recent call last): File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from django_site_id_seq' at line 1") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/polo/all_project/python学习/polo_testing_platform/manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in … -
Django scaling using Docker
I would like to ask how does Django scale using docker ( including using docker-compose ). For Example, a e-commerce app with 1K actif users to like ~10K visits / day.(Or Should I consider the number of request / second) In the other side, I also want to know how much does Django need (hardware requirements : Number of Core CPU, Ram, Network Traffic ..) for like 10K actif user / day. Many thanks in advance -
Store class instance in mysql
I get the response from the API. Normally, I fetch the data from the response and store it into the mysql It's enough. However, in this case I want to store the response instance itself. Maybe some serializing is necessary though, Generally speaking , is there any way to store the instance itself by python?? -
Django for loop to iterate a dictionary [closed]
enter image description here enter image description here enter image description here I want to display all three records in the table but it is not working... can anyone help me regarding this? -
Django unmanaged postgres view got deleted automatically
I have created a Postgres database view by joining 4 tables. Then created a Django model which is based on this view. It has managed=False It was working fine from a week and today I am seeing the view is missing from database. It has got deleted. Is there any technical reason behind it? -
Django custom display in html of a query
I want to query database and showing in html, but in my database it's an int like 1233405061023 and i want to display in my template like this 12334050XXX23, it's that possible or i have to create another column with the custom formating like i mentioned above and display that column instead of clean one ? -
DRF- Got assertion error when I give Post Request
Error AssertionError: The `.create()` method does not support writable dotted-source fields by default. Write an explicit `.create()` method for serializer `hrm_apps.configuration.serializers.CurrencySerializer`, or set `read_only=True` on dotted-source serializer fields. models.py, class CurrencyMaster(models.Model): code = models.CharField(max_length=3, null=False, unique=True) name = models.CharField(max_length=100, null=False, unique=True) def __str__(self): return self.name class Currency(models.Model): currency_master = models.OneToOneField(CurrencyMaster, on_delete=models.RESTRICT) conversion_rate = models.FloatField(null=False) def __str__(self): return self.currency_master.name views.py, class CurrencyViewSet(viewsets.ModelViewSet): queryset = Currency.objects.all() serializer_class = CurrencySerializer lookup_field = 'id' serializers.py, class CurrencySerializer(serializers.ModelSerializer): currency_master = serializers.CharField(source="currency_master.name") class Meta: model = Currency fields = ['id', 'currency_master', 'conversion_rate'] When i give post request i got assertion error like above, class CurrencySerializer(serializers.ModelSerializer): currency_master = serializers.CharField(source="currency_master.name") class Meta: model = Currency fields = ['id', 'currency_master', 'conversion_rate'] def create(self, validated_data): return Currency.objects.create(**validated_data) def update(self, instance, validated_data): instance.currency_master = validated_data.get('currency_master', instance.currency_master) instance.conversion_rate = validated_data.get('conversion_rate', instance.conversion_rate) return instance I tried above i got this error "ValueError: Cannot assign "{'name': 'ALL - Albania Lek'}": "Currency.currency_master" must be a "CurrencyMaster" instance". How to resolve this??? -
inspectdb unrecognized arguments PackageWeight
Is it possible in Django 1.8 to inspect specific table? When I run (according to this): $ python manage.py inspectdb --database=default PackageWeight It writes: usage: manage.py inspectdb [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--database DATABASE] manage.py inspectdb: error: unrecognized arguments: PackageWeight -
Want to save image URL in Python Django
This is my model class MenuOptions(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) This is my form class MenuOptionsForm(forms.ModelForm): class Meta: model = MenuOptions fields = ['name', 'description'] And this is my view if request.method == 'POST': form = MenuOptionsForm(request.POST) if form.is_valid(): form.save() return redirect('menu-options') else: form = MenuOptionsForm() I want to have the image field in the forms only so that I can upload the image on S3/Google storage I know how to do that and after uploading the image to the storage I want to save only the image_url to the DB, not the image. So it can not be an image_filed in the Django model it has to be a string. -
sqlanydb.OperationalError column not found
When I run python manage.py inspectdb it ends with error messsage Traceback (most recent call last): File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/base.py", line 98, in execute ret = self.cursor.execute(trace(query), trace(args)) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 796, in execute self.executemany(operation, [parameters]) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 767, in executemany bind_count = self.api.sqlany_num_params(self.stmt) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 701, in __stmt_get self.handleerror(*self.parent.error()) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 695, in handleerror eh(self.parent, self, errorclass, errorvalue, sqlcode) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 379, in standardErrorHandler raise errorclass(errorvalue,sqlcode) sqlanydb.OperationalError: (b"Column 'a' not found", -143) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/commands/inspectdb.py", line 25, in handle for line in self.handle_inspection(options): File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/commands/inspectdb.py", line 64, in handle_inspection relations = connection.introspection.get_relations(cursor, table_name) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 62, in get_relations my_field_dict = self._name_to_index(cursor, table_name) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 55, in _name_to_index return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))]) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 46, in get_table_description cursor.execute("SELECT FIRST * FROM %s" % File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 62, in … -
rendering form in html django
I have this app and its working but i'm confused whether to use form method or POST.get method. with form i'm getting so many challenges like rendering form on custom html suppose i have this change password screen, for that i need to create form then use this on html template and with custom html it gets more complicated to use form fields. forms.py: class ChangePasswordForm(PasswordChangeForm): old_password = forms.CharField(label="Old Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) new_password1 = forms.CharField(label="New Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) new_password2 = forms.CharField(label="Confirm Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) class Meta: model = User fields = ('old_password', 'new_password1', 'new_password2') views.py: # Password Change View def changePassword(request): if request.method == 'POST': form = ChangePasswordForm(request.user, request.POST) print(form) if form.is_valid(): print("form valid") user = form.save() update_session_auth_hash(request, user) messages.success(request, "Password Changed Successfully") return redirect('changePassword') else: messages.error(request, "Something Went Wrong, Please Try Again ") return redirect('changePassword') else: form = ChangePasswordForm(request.user) return render(request, 'admin/user_auth/change_password.html', { 'form': form }) html: {% extends "admin/layouts/default.html" %} {% load static %} {% block content%} <div class="row"> <div class="col"> <div class="titleBlock"> <a href="{{request.META.HTTP_REFERER|escape}}"><h1><i class="fas fa-chevron-circle-left mr-3"></i>Back</h1></a> </div> <div class="card"> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class=" … -
Django distinct query is still returning duplicates
I have a shopping list which I can fill by adding all the ingredients from a recipe. I want to query Shopping to see get all unique recipes present in a Shopping List, however my distinct query is returning duplicates? #query ShoppingItems.objects.filter(user=account, shoppingList=shoppingList, recipe__isnull=False).values('recipe').distinct() #returns > <ShoppingItemsQuerySet [{'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}]> #shopping/models.py class ShoppingLists(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) class ShoppingItems(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shoppingList = models.ForeignKey(ShoppingLists, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=220, blank=True, null=True) # chicken # recipes.models.py class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # grilled chicken pasta -
How to join like sql in django models
I have these three models which has not contained foreign key class SchoolReg(models.Model): # TODO: Define fields here user = models.ForeignKey('front.User', on_delete= models.CASCADE) fullname = models.CharField(max_length= 100) dob = models.CharField(max_length= 50) class CandidateCode(models.Model): candidateCode = models.IntegerField() regId = models.IntegerField() regCategory = models.CharField(max_length=20) class Sec1(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, blank= True, null = True) centreName = models.CharField(max_length= 50, blank= True, null = True) compRegNo = models.CharField(max_length= 50, blank= True, null = Tru now I want join these models and make a queryset of student like this SELECT * from school_reg s LEFT JOIN sec1 c on s.user_id = c.user_id LEFT JOIN candidate_code cc on cc.reg_id = s.school_id WHERE c.center_name = "centreName" -
Partially Shifting to react from Django
Basically I have a project in Django, in all it has 7 apps. I want to shift one of them in react. Say app 'Student' is the one which I want in React. I want to know if its possible to do so, if yes then how? Here is what I tried, I created a react project and using npm run build command I got a build of that react project. Now for base url of Student i rendered template which was in react build folder. Something like this. urls.py urlpatterns = [ ... ... path('student/', views.Student, name='student'), .... ] views.py def Student(request): return render(request, 'build/index.html') Where index.html is the file present in build folder. Using this approach i was able to render the react template but the other url routes were not working. Please let me know what's wrong in this approach, if this approach is wrong then do suggest another approach. -
How can i make my python with django website be used my many users? for now it only logs in one user at a time
Developed python website with django but i have a challenge, whenever i'm logged in and another user tries to log in he/she is taken to my dashboard(currently logged in user) instead of being asked to log in to his/her account. So my website is like only one person can use at a time, have tried using decorators (@login required) but still facing same problem. What i'm i lacking kindly -
Copy current form data into new form using django
I have two views, PostCreateView and PostUpdateView. They both route through the same html template, post_form.html. I want to create a Copy button that only appears if I am accessing a record through PostUpdateView. Pressing the Copy button will create a new record pre-filled with all the data from record that I was just on. PostCreateView code: class PostCreateView(LoginRequiredMixin, FormView): template_name = 'trucking/post_form.html' form_class = RecordForm def form_valid(self, form): form.instance.author = self.request.user obj = form.save(commit=False) obj.save() messages.success(self.request, f'RECORD: {obj.container_no} was saved') return super().form_valid(form) def get_success_url(self): if self.request.POST.get('Save_Exit'): return reverse('close') elif self.request.POST.get('Save'): return reverse('post-create') else: return reverse('database') PostUpdateView code: class PostUpdateView(LoginRequiredMixin, UpdateView): form_class = RecordForm model = Post def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) history = Post.objects.filter(id = self.object.id).first().history.all().reverse() data['history'] = get_status_changes(history) return data # checks to make sure the user is logged in def form_valid(self, form): form.instance.author = self.request.user obj = form.save(commit=False) messages.success(self.request, f'RECORD: {obj.container_no} was updated') return super().form_valid(form) def get_success_url(self): if self.request.POST.get('Save_Exit'): return reverse('close') # return render(self.request, 'trucking/email_close.html') elif self.request.POST.get('Save'): return reverse('post-update', kwargs={'pk': self.object.id}) else: return reverse('database') Based on this post I tried creating a view like so: def copy(request): post = Post.objects.get(pk = request.users.post.id) my_form = RecordForm(instance = post) return render(request, 'trucking/post_form.html', {'form': my_form}) However, I get an … -
How to filter in django to get each date latest record
Example Record Table id value created_datetime 1 10 2022-01-18 10:00:00 2 11 2022-01-18 10:15:00 3 8 2022-01-18 15:15:00 4 25 2022-01-19 09:00:00 5 16 2022-01-19 12:00:00 6 9 2022-01-20 11:00:00 I want to filter this table 'Record Table' as getting each date latest value.For Example there are three dates 2022-01-18,2022-01-19,2022-01-20 in which latest value of these dates are as follows Latest value of each dates are (Result that iam looking to get) id value created_datetime 3 8 2022-01-18 15:15:00 5 16 2022-01-19 12:00:00 6 9 2022-01-20 11:00:00 So how to filter to recieve results as the above mentioned table -
Multistage docker build for Django
I am dockerizing my Django application with docker multi-stage build. Now am facing an issue with dependencies Dockerfile FROM python:3.8-slim-buster AS base WORKDIR /app RUN python -m venv venv ENV PATH="/app/venv:$PATH" COPY requirements.txt . RUN pip install -r requirements.txt \ && pip install gunicorn COPY entrypoint.sh . COPY . . FROM python:3.8-slim-buster WORKDIR /app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY --from=base /app /app/ ENV PATH="/app/venv:$PATH" ENTRYPOINT sh entrypoint.sh When running the container it raises import error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
login not working in Django after migrating to 3.2 getting error: django.db.utils.ProgrammingError
I recently migrated my Django version from 2.2 to 3.2 and login stopped working after that. In 2.2 it was working fine. It is giving an error:- > Traceback (most recent call last): > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/handlers/exception.py", > line 47, in inner > response = get_response(request) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/handlers/base.py", > line 181, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/generic/base.py", > line 70, in view > return self.dispatch(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/decorators.py", > line 43, in _wrapper > return bound_method(*args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/decorators/debug.py", > line 89, in sensitive_post_parameters_wrapper > return view(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 146, in dispatch > return super(LoginView, self).dispatch(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 74, in dispatch > response = super(RedirectAuthenticatedUserMixin, self).dispatch( > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/generic/base.py", > line 98, in dispatch > return handler(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 102, in post > response = self.form_valid(form) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 159, in form_valid > return form.login(self.request, redirect_url=success_url) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/forms.py", > line 196, in login > ret = perform_login( > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/utils.py", > line 171, in perform_login > if not _has_verified_for_login(user, email) and signup: > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/utils.py", > line 139, in _has_verified_for_login > ret = EmailAddress.objects.filter(user=user, … -
How to display uploaded pdf file along with machine name and operation number based on select from dropdown
In this project, I want to display machine name and operation number along with uploaded pdf files based on select machine name and operation number from dropdown menu. This project is working but when I add and select another file in same machine name and operation number, it is displaying two pdf files along with previous pdf file of another machine name and operation number, exactly I don't want it. It should display machine name and operation number along with uploaded pdf file based on select from dropdown menu. And also when I upload another pdf files in same machine name and operation number, it should display two pdf files along with same machine name and operation number within same row. This project is working fine but I want above validations. Please anyone can help me out, this will be great for me. Please.. views.py: def upload(request): controlmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machinename', '') operation_no = request.POST.get('operationname','') choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no) cmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines,'choiced_cmachine':choiced_cmachine}) def index(request): if request.method == 'POST': form = ControlmachineForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlmachineForm() controlmachiness = Controlmachine.objects.all() return render(request,'usermaster/upload_file.html',{'form':form,'controlmachiness':controlmachiness}) upload.html: … -
Django inspectdb not creating primary keys
When I run python manage.py inspectdb --database totals > modelstest.py it appears to function as expected and I get my models, but it does not create primary keys and add an id field although everything I can find online says it does, little confused. I went into my settings file and added DEFAULT_AUTO_FIELD='django.db.models.AutoField' but now when I try to migrate again there is nothing to migrate, I flushed my db and tried to migrate again but it didn't really do anything, a little confused how I can migrate again to kick in that auto field setting now? -
how to dump postgres database in django running in docker-container?
I have an application running in a docker container and psql database running in a docker container as well. i want to dump database while in django container, i know there is dumpdata in django but this command takes long time, i also tried docker exec pg_dump but inside django container this command doesn't work. services: db_postgres: image: postgres:10.5-alpine restart: always volumes: - pgdata_invivo:/var/lib/postgresql/data/ env_file: - .env django: build: . restart: always volumes: - ./static:/static - ./media:/media ports: - 8000:8000 depends_on: - db_postgres env_file: - .env Is there any way to do pg_dump without using docker exec pg_dump while in django container? -
How can I add certain number of day to a date, with python - timedelta?
I am stuck with an issue. Basically, I have to add, depending on the type of duration, a certain number of days to a date. My model and functions are like that: models.py from django.db import models import datetime # Create your models here. FRAZIONAMENTO = ( ('Annuale', 'Annuale'), ('Semestrale', 'Semestrale'), ('Quadrimestrale', 'Quadrimestrale'), ('Mensile', 'Mensile'), ) class Polizza(models.Model): cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE) numero_polizza = models.CharField(max_length=100) data_decorrenza = models.DateField() data_scadenza = models.DateField(blank=True, null=True) ramo_polizza = models.CharField(max_length=100, choices=RAMO_POLIZZA) polizza_nuova = models.BooleanField(default=True) frazionamento = models.CharField(max_length=100, choices=FRAZIONAMENTO) premio = models.DecimalField(max_digits=5, decimal_places=2) provvigione = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) creata = models.DateTimeField(auto_now_add=True) aggiornata = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Polizza' ordering = ['data_scadenza'] def __str__(self): return self.ramo_polizza + ' ' + self.frazionamento @property def get_data_scadenza(self): if self.frazionamento == 'Annuale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=365)) elif self.frazionamento == 'Semestrale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=180)) elif self.frazionamento == 'Quadrimestrale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=120)) elif self.frazionamento == 'Mensile': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=30)) return data_scadenza def save(self, *args, **kwargs): self.provvigione = self.get_provvigione super(Polizza, self).save(*args, **kwargs) views.py def nuova_polizza(request): clienti = Cliente.objects.all() polizze = Polizza.objects.all() context = { 'clienti': clienti, 'polizze': polizze, } return render(request, 'anagrafica/nuova_polizza.html', context) def salva_nuova_polizza(request): if request.method == 'POST': cliente … -
Show a part of the template that has been previously filtered
I would like to know what is the most pythonic way to get the following result: Let's say we have a view: def myView(request): context = {} if something: context['A'] = "Whatever" else: context['B'] = "Whatever" return render(request, 'mypage.html', context) In the template, let's say mypage.html we have the following scenario: {% if A %} A code {% else %} B code {% endif %} When the page loads, the code is rendered depending on whether we have A or B in the view context. My question is: if the page renders with the A code (for example), is it possible through a button when clicking on that button to hide A code and show B code instead? -
How to connect uploaded pdf file to dropdown list in django
In this project, I want to display uploaded pdf files along with machine name and operation number based on select from dropdown list. Here, when I select machine name and operation number, It is displaying the pdf file but when I select another machine name and operation number, it is displaying two pdf files along with previous pdf file, exactly I don't want this, How to solve this. And also when I add another pdf file in same machine name and operation number, It should display two pdf files within same row. This project is working correctly, but I want above validations. Please anyone solve this for me, that will be great for me. Please views.py: def control_upload(request): if request.method == 'POST': form = ControlForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlForm() controlmachiness = Controlmachine.objects.all() return render(request,'master/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def control_index(request): controlmachines = Controlmachine.objects.all() return render(request,"master/control_show.html",{'controlmachines':controlmachines}) def control_destroy(request, id): controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() return redirect("/") control_show.html: <div class="col-md-12"> <div class="table-responsive"> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%"> <thead> <th><input type="checkbox" id="checkall" /></th> <th>ID</th> <th>Machine Name</th> <th>Operation Number</th> <th>File</th> <th>Delete</th> </thead> <tbody> {% for control in controlmachines %} <tr> <td><input type="checkbox" class="checkthis" /></td> <td>{{ control.id }}</td> <td>{{ control.machine_name }}</td> <td>{{ …