Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
<textarea not working with django and python
I am trying to make this textarea work, but it doesnt. my view doesnt receive the data from this. My Input works: <input id="contact_email" type="text" name="contact_email" value="" class="form-control" placeholder="Seu E-mail *" required="" data-validation-required-message="Please enter your email address."> What is wrong on that <textarea id="contact_message" type="text" name="contact_message" value="" class="form-control" placeholder="Seu E-mail *" required="" data-validation-required-message="Please enter your email address."></textarea> my view code bellow: def myfunc(request): contact_name = request.GET.get('contact_name') contact_email = request.GET.get('contact_email') contact_mensagem = request.GET.get('contact_mensagem') print('hello world') print(contact_name) print(contact_email) print(contact_mensagem) return HttpResponse("Email Enviado!") -
Django session and cycle_key()
I'm using Django as backend server and it has configure SESSION_ENGINE with django.contrib.sessions.backends.cache, cache is stored in Redis. Despite it appears to be configured correctly, the coockie session_id never change, so if I login and I set session_id to the request, response will give me the same session_id (with the new data). This behaviour exposes me to Session fixtation attack and I do not know why cycley_key() is never called. Someone knows hot to fix this behaviour? Thanks! -
Rapidsms installation
I want to install rapidsms; I use the ubuntu version 19.10. I applied this tutorial https://rapidsms.readthedocs.io/en/develop/tutorial/tutorial01.html And when i used this command : python manage.py syncdb I have this error : (rapidsms-tut-venv) abdou96@abdou96-Vostro-3460:~/rapidsms_tut$ python manage.py syncdb /home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django_tables2/tables.py:175: RemovedInDjango19Warning: SortedDict is deprecated and will be removed in Django 1.9. attrs["base_columns"] = SortedDict(parent_columns) /home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django_tables2/tables.py:197: RemovedInDjango19Warning: SortedDict is deprecated and will be removed in Django 1.9. attrs["base_columns"].update(SortedDict(cols)) /home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/rapidsms/utils/modules.py:7: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9. from django.utils.importlib import import_module Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django/core/management/init.py", line 354, in execute_from_command_line utility.execute() File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django/core/management/init.py", line 328, in execute django.setup() File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django/init.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/selectable/apps.py", line 10, in ready from . import registry File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/selectable/registry.py", line 6, in from selectable.base import LookupBase File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/selectable/base.py", line 12, in from django.urls import reverse ImportError: No module named urls -
How to customize Django's CSRF handling on a per view basis
In a Django application I have 'django.middleware.csrf.CsrfViewMiddleware' enabled. This means that a POST request without a CSRF token will be rejected and result in a HTTP response Forbidden (status code 403). Now I have one view that needs to handle a missing CSRF token in a different way. Instead of a 403 response I want to redirect the user to a different page. I came up with the following solution (based on the docs: https://docs.djangoproject.com/en/3.0/ref/csrf/#scenarios): @csrf_exempt # Disable CSRF middleware @requires_csrf_token # Apply customized CSRF middleware def my_view(request): if getattr(request, 'csrf_processing_done', False): # CSRF success, process request ... else: # CSRF failed, redirect return HttpResponseRedirect(...) Which is nice and short and seems to work perfectly fine. My issue however is that it relies on an implementation detail. The current version of Django only ever sets csrf_processing_done to True in the _accept method of CsrfViewMiddleware (https://github.com/django/django/blob/3.0.4/django/middleware/csrf.py#L141) The requires_csrf_token is based on a customized version of CsrfViewMiddleware that overrides _reject to do nothing (https://github.com/django/django/blob/3.0.4/django/views/decorators/csrf.py#L17) (it keeps _accept the same). So my current implementation will work as long as Django doesn't change the implementation of this middleware and decorator. Since csrf_processing_done is not part of the public API (I asked: https://code.djangoproject.com/ticket/31360), I'm left … -
Form not save with custom form fields
Good morning guys, I have a problem with a form. My code: models class AnagraficaGenerale(models.Model): ragionesociale = models.CharField(max_length=40, null=True, blank=True) forms class AnagraficaGeneraleForm(forms.ModelForm): class Meta: model = AnagraficaGenerale views @login_required def anagrafica_new(request): if request.method == "POST": form = AnagraficaGeneraleForm(request.POST or None) if form.is_valid(): form.save() return redirect('anagrafica_list') else: form = AnagraficaGeneraleForm() return render(request, 'Anagrafiche/anagrafica_new.html', {'form': form}) html {% extends 'FBIsystem/basenobar.html' %} {%load staticfiles %} {% block content %} <div id="page-wrapper"> <div class="panel"> <div class="panel-body"> <h3 class="title-hero"> Nuova Anagrafica </h3> <form method="POST" class="form-horizontal bordered-row"> {% csrf_token %} <div class="example-box-wrapper"> <div class="form-group"> <label class="col-sm-2 control-label" > Ragione Sociale:</label> <div class="col-sm-6"> {{ form.ragionesociale }} </div> </div> </div> <button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button> </form> </div> </div> </div> {% endblock %} Everything seems ok but not save, if I try with {{form.as_table}} it save. I think there is a problem with custom field but I don't know how. whats wrong? TY -
How to make django serve static files in development?
For some reason my django project doesn't see my static files, giving me 404 error, like so: "GET /static/js/main.js HTTP/1.1" 404 1757 I do everything in accordance with the official guide. Here is my project structrure: PMpro: -PMpro (main project) -users (app) -tasks (another app) -static --js --css --etc... -templates --template files... -manage.py My settings.py file: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('home/', TemplateView.as_view(template_name='index.html')) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In my .html file I's collecting static files and linking to corresponding css/js file like so: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/organicfoodicons.css' %}" /> I'm pretty sure I do everything in accordance with the official django guide, and yet my project doesn't see/serve my static files. I have already went through a number of similar problems people were posting here, and I have everything im my code exactly as it was advised, but the problem is still there. Folks, any suggestions? -
Django: Offer has many Products
How to make relation in Django that Offer model has has Products and Products beyond to the one Offer. from django.db import models class Offer(models.Model): city = models.CharField( max_length=100) street = models.CharField( max_length=100) offer_taken = models.BooleanField( default=False) products = # models.OneToManyField(Product) ?? class Product(models.Model): product_name = models.CharField( max_length=100) -
ValueError: not enough values to unpack (expected 2, got 0) in Django
My function doesn't take any arguments but I get this error not enough values to unpack (expected 2, got 0). I can print the values on the terminal but can't be displayed on the browser. I am fetching data from two database tables(Postgres) and put it in a select input in Django template. This is the method suppose to return the data to be displayed def get_categories(): myvars = {} sdet = {} items = CategoriesDB.objects.all() vals = '<option value="">Please Select Category</option>' try: for item in items: section_id = item.section_id gname = repr(item.section.section_name) sdet[section_id] = gname category_id = item.id category_name = item.category_name gcat = {'id': category_id, 'name': category_name} if section_id not in myvars: myvars[section_id] = [gcat] else: myvars[section_id].append(gcat) for var in myvars: otitle = sdet[var] otl = len(otitle) tshort = '%s ...' % (otitle[:100]) if otl > 100 else otitle vals += '<optgroup label="%s" title="%s">' % (tshort, otitle) gitems = myvars[var] for i, itm in enumerate(gitems): gname = str(itm['name']) itm_id = itm['id'] itl = len(gname) itms = '%s ...' % (gname[:100]) if itl > 100 else gname vals += '<option value="%s" title="%s">%s</option>' % ( itm_id, gname, itms) vals += '</optgroup>' except Exception as e: raise e else: # on returning … -
Django ContenTypes not saving "content_object" on Migration
Starting with an existing ModelA. Requirements: depending on ModelA.type, ModelA.example will be a relationship to ModelB or ModelC. pre existing ModelA instances need to be initialized with the default, depending on ModelA.type (ModelA.type is already not nullable) Current Solution: I created a generic relation on ModelA: class ModelA: ... example_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) example_id = models.PositiveIntegerField(null=True) example = GenericForeignKey("example_content_type", "example_id") I ran ./manage.py makemigrations wich created a migration with nullable fields I changed the example_content_type and example_id fields to not null ran makemigrations again and created the following custom RunPython before the auto generated changes: def set_default_example(apps, schema_editor): ModelA = apps.get_model("myExample", "ModelA") all_model_a = ModelA.objects.all() for model_a in all_model_a: example = None if model_a.type == "type_a": example = ExampleForTypeA.objects.create(foo="foo") if model_a.type == "type_b": example = ExampleForTypeB.objects.create(bar="bar") model_a.example = example model_a.save() trying to migrate this is throws with django.db.utils.IntegrityError: column "example_content_type_id" contains null values I manually created and assigned the content_type (only works if I assign the _id field). this still throws with: django.db.utils.IntegrityError: column "example_id" contains null values so I mannully created and assigned the example_id resulting the the following code: def set_default_example(apps, schema_editor): ModelA = apps.get_model("myExample", "ModelA") all_model_a = ModelA.objects.all() for model_a in all_model_a: example = None content_type … -
How to do Facial Recognition in android's chrome browser
I have done facial recognition in my website with OpenCV, Python language, Django framework and it is working in my laptop. Now when i run the website on localhost in android's chrome browser, instead of opening android phone's camera it opens the camera in the laptop. Any solution? -
how to create a new item in an html table after submission of a form?
Basically I am designing a web app (using django) that acts as an email sending service for broadcasting emails to specific users. Within the app I have my outbox which i got from a responsive bootstrap admin template, with mail items. What I would like to happen is for when a message is sent and the form is submit a new mail item would appear in my table containing the some of the contents of the mail that was sent just like gmail (e.g subject) this is the html used : <div class="table-responsive"> <table class="table mail-list"> <tr> <td> <div class="photo1"> <!--<img style="opacity: 0.5;" src="{% static '../static/assets/images/background.jpg' %}" alt=""></div>--> <!-- a single mail--> <div class="mail-item"> <table class="mail-container"> <tr> <td class="mail-left"> <!-- image was here ;-; --> </div> </td> <td class="mail-center"> <div class="mail-item-header"> <h4 class="mail-item-title"><a href="mail-view.html" class="title-color">{% cache None sidebar request.user.username %} {{Subject}} {% endcache %}</a></h4> </div> <p class="mail-item-excerpt">{% cache None sidebar %} {{Body}} {% endcache %}</p> </td> <td class="mail-right"> <p class="mail-item-date">2 hours ago</p> <p class="mail-item-star starred"> <a href="#"><i class="zmdi zmdi-star"></i></a> </p> </td> </tr> </table> </div><!-- END mail-item --> Not sure if this is all the info that would be needed but I am quite new to html and django and so … -
How to render the content of a variable in a different template with Django?
I have a button that generates a report in two variables: one has a short version of the information and the other contains a detailed version on it. The view renders the information of the short one with a template, let's call it template one. I need to place a button in template one that allows to see the content of the second variable in a different template and also in a new browser tab. Since the information is not stored in the database (so I cant' address it with ids) how can I pass the variable that contains the detailed report information (hundreds of rows)? Is it okay to try to pass it using the template tag 'url'...? (It feels like a wrong approach) -
Docker-compose does not work in docker-machine
I have a cookiecutter-django application with docker that works fine if I run it locally with docker compose -f local.yml up. Now I am trying to deploy it so first I created a docker-machine in my computer (using macOS Catalina) and activated it. Now, inside the docker-machine, the docker-compose build works fine, but when I run it, the application crashes. Any idea what can be happening? I have been trying to solve this for almost a week now... This are my logs when I do docker-compose up in the docker-machine: Creating network "innovacion_innsai_default" with the default driver Creating innovacion_innsai_postgres_1 ... done Creating innovacion_innsai_django_1 ... done Creating innovacion_innsai_node_1 ... done Attaching to innovacion_innsai_postgres_1, innovacion_innsai_django_1, innovacion_innsai_node_1 postgres_1 | 2020-03-16 08:41:12.472 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2020-03-16 08:41:12.472 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_1 | 2020-03-16 08:41:12.473 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2020-03-16 08:41:12.494 UTC [21] LOG: database system was shut down at 2020-03-16 08:31:09 UTC postgres_1 | 2020-03-16 08:41:12.511 UTC [1] LOG: database system is ready to accept connections django_1 | PostgreSQL is available django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", … -
MultiValueDictKey Error when submitting a form
I am new in Django, I am working on a website where user can edit his profile (first name, last name, username, email) and also change his profile picture with a separate form. The profile picture form save file when submitted, but the updateform display 'MultiValueDicKeyError at /account/edit' 'profile_pic' when the form is submitted. Here is my views. def profile_edit_view(request): form = ProfilePic(request.Post or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): pp = form.save(commit=False) pp.user = request.user pp, created = Profile.objects.get_or_create(user=request.user) pp.profile_pic = request.FILES['profile_pic'] pp.save() return redirect... else: form = ProfilePic() updateform = UpdateUserForm(request.POST or None, instance=request.user) if request.method == 'POST': if updateform.is_valid(): updateform.save() return redirect.... else: updateform = UpdateUserForm() context = {'form':form, 'updateform':updateform} return render(request, 'profile_edit.html' context) -
Django Ajax Image submit
I am trying to upload and save an image file using Django and respond the image itself to use in ongoing javascript functions. The problem is that the image doesn't get saved, the request.FILES is empty. When using request.body, I can see that there is not the actual file path, but a C://fakepath. Because I want the uploaded image to use immediately, I do the post using a jquery ajax call. views.py: def image_feedback(request): if request.method == 'POST': image = request.FILES.get('image') ImagesUpload.objects.create( image = image, ) return HttpResponse('success') models.py: class ImagesUpload(models.Model): image = models.ImageField(upload_to=renaming_file) def __str__(self): return str(self.image) form_template.html: <form id="image_form" enctype="multipart/form-data">{% csrf_token %} <button class="btn btn-secondary" onclick="$('#id_image').click()">Import Image</button> {{ form_image.image }} <input id="hidden-submit-img" value="SUBMIT" type="submit" style="visibility:hidden"> </form> jquery ajax call: <script> $(document).ready(function () { // This jquery changes the appearance of the django { form_image } var imgElement = $('#id_image'); imgElement.css('visibility', 'hidden'); // This function triggers the hidden submit, // which triggers the ajax image request imgElement.on({ change: function () { $('#hidden-submit-img').click(); }, }); }); // This jquery is for the ajax post of the image $('#image_form').submit(function (event) { event.preventDefault(); $.ajax({ data: { image: $('#id_image').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, type: "POST", enctype: 'multipart/form-data', url: "{% url 'website:image-feedback' %}", … -
How to get total data creted in manytomany field
here in this i want to fetch no of Players_Participants added by the user,in this i am getting total no of Players_Participants class MyUser(AbstractBaseUser): user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) def __str__(self): return str(self.user_name) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) Players_Participating=models.ManyToManyField(MyUser,related_name='related') def __str__(self): return str(self.Host) class MyUserViewSet(viewsets.ViewSet): def create(self,request): user_name=request.data.get('user_name') user=MyUser() user.user_name=user_name return Response({"response":'delivered'}) class SessionViewSet(viewsets.ViewSet): def create(self, request): Host= request.data.get('Host') Sport = request.data.get('Sport') Players_Participating=request.data.get('Players_Participating') new=Session() new.Host=MyUser.objects.get(user_name=Host) new.Sport=Sport new.Players_Participating=Players_Participating new.save() def list(self,request): users = Session.objects.all() use = [] player_list=[] for user in users: for players in user.Players_Participating.all(): player_list.append(players.user_name) use.append({ 'Host':user.Host.user_name, "Sport":user.Sport, "Players_Participating":player_list, }) return Response({"success":True, "users":use, "pages":paginator.num_pages}) -
Include 0 to a annotate count if not found in django Queryset.?
I don't know how to phrase my question correctly but what I am doing is I am querying a table based on certain id and then getting the count of the unique field in a column and that count I am giving to matplotlib to plot but what problem I am facing is if a certain value is not found the label size mismatches with the count and plot doesn't work. Below is my query: workshop_feedback = WorkshopFeedbackResponse.objects.filter(workshop_conducted=workshop_id) count = workshop_feedback.values('q1').annotate(count=Count('q1')) sizes = [item['count'] for item in count] #converting to list for matplotlib bar char labels = [1,2,3] #option of choices for q1 fig, ax = plt.subplots() ax.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.savefig(os.path.join(settings.BASE_DIR, filename)) #filename is random image filename Which i am creating image of the graph My column name is q1 and it can contain 1,2,3 as an option depending upon what user has filled but suppose if I don't have 1 or either option the count doesn't reflect that. Exception Value: 'label' must be of length 'x' Above is the error I get from if count of certain value is missing. So How to get … -
Django: 'HttpResponseRedirect(reverse())' redirects to the same page
HttpResponseRedirect(reverse('success')) leading to the same page which requested with URL changed. views def dashboard_tools(request): ... if request.method == "POST": ... return render(request, "tools/loading.html", {}) # return redirect('success') # return HttpResponseRedirect(reverse('success')) return render(request, "tools/dash_tools.html", {'data':all_entries}) def success(request): return render(request, "tools/loading.html", {}) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'$',tools.views.dashboard_tools,name="tools"), url(r'^success/', tools.views.success, name="success"), ] The return render(request, "tools/loading.html", {}) redirects to correct page but return redirect('success') and return HttpResponseRedirect(reverse('success'))fails to do so. The redirect and HttpResponseRedirect redirects to the same page with url http://127.0.0.1:8000/success/ -
'QueryDict' object has no attribute 'user'
I'm currently working on my project in Django, I need the foreign key (designation) to be displayed respective to the current user. It displays perfectly fine just like I wanted, but it throws an error while I submit the form, 'QueryDict' object has no attribute 'user'. forms.py def __init__(self,req,*args,**kwargs): super(EmployeeForm,self).__init__(*args,**kwargs) self.fields['designation'].queryset = req.user.designation.all() views.py form = DesignationForm(request) -
Initial Value of Select2Multiple widget
I am working on a searchinput with additional parameters given through a django autocomplete light Select2Multiple widget. class SearchParameterForm(forms.Form): p = forms.MultipleChoiceField( widget=autocomplete.Select2Multiple(url='search-parameter-autocomplete'), label='Search Parameter', required=False, ) & class SearchParameterAutocomplete(LoginRequiredMixin, autocomplete.Select2ListView): def get_list(self): parameter_list = ['only stocked'] for my_storage in Storage.objects.filter(workgroup=self.request.user.profile.workgroup).all(): for workgroup in my_storage.workgroup.all(): parameter_list.append(workgroup.name) return list(set(parameter_list)) I would like to set the initial value of the Widget depending on some parameters (e.g. self.request.user.profile.workgroup.name) Setting the initial value of the field either directly in the class with some dummy values or in the view did not work. I would also like to store the selected values on page refresh. initial = {"id": "AK2", "text": "AK2"} initial = ['AK1'] initial = 'AK1' Is there a way to do this with django or jquery? ~Fabian -
Redirected to same page after POST method django
I am creating this project in django. I am working on reporting films, where I go to a film-detail view, then hit the report button. A report_form shows up where I justify why I am reporting, and then I click report. Everything works fine, but there is one thing. After reporting I get sent back to a random(?) film-detail view, but I would like to go back to the view for the film I am reporting. But how??? views.py class FilmReportView(LoginRequiredMixin, CreateView): model = Report fields = ['reason'] def form_valid(self, form): form.instance.reporter = self.request.user form.instance.reports_id = self.kwargs['pk'] return super().form_valid(form) def get_success_url(self): return "film/<int:pk>/report" report_form.html {% extends "board/base.html" %} {% load crispy_forms_tags %} {% load materializecss %} {% block content %} <div class="valign-wrapper row login-box"> <div class="col card hoverable s10 pull-s1 m6 pull-m3 l8 pull-l2"> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="card-content"> <span class="card-title">Jusity why you want to report this film?</span> <div class="row"> {{ form|materializecss }} </div> </div> <div class="card-action right-align"> <input type="reset" id="reset" class="btn-flat grey-text waves-effect"> <input type="submit" class="btn green waves-effect waves-light" value="Report"> </div> </form> </div> </div> {% endblock content %} urls.py urlpatterns = [ path("", views.films_view, name="board-home"), path("film/add", FilmAddView.as_view(), name="film-add"), path("film/<int:pk>/", FilmDetailView.as_view(), name="film-detail"), path("film/<int:pk>/report", FilmReportView.as_view(), name="film-report"), ] … -
What extraordinary feature can I add to my web page?
I am making a job portal as a mini-project. I wanted to add an extraordinary feature that is not in most job portal website. I am making it using Django in the backend. -
Password Reset email is only sent the host email only in django 2.x
I've added a functionality to my django application, to send gmail(google mail) to user who forgot their password, But, it only sends email to the user I've added in the settings.py file of my project.Can you resolve this problem to mail to all users who request to reset their password? This is the variables, I added in the settings.py file. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_USER') -
How to define default field value but not on database level?
I want to have default value of text field being calculated for user. Eg. Now year=2020, so User choice would be 2020 and 2021 in dropdown field. But in next year(2021) I want to have 2021 and 2022 values to be only possibile choices. Field is defined like this in models.py: year = models.CharField(default=default_year(), max_length=4, choices=year_choices(), ) where: def default_year(): return str(datetime.now().year) def year_choices(): current_year = datetime.now().year years = [] years.append([str(current_year), str(current_year)]) years.append([str(current_year + 1), str(current_year + 1)]) return tuple(years) So it works for now, but because of migration it will not change in next year, right? Whats causing trouble is migration: migrations.AlterField( model_name='movie', name='year', field=models.CharField(choices=[['2020', '2020'], ['2021', '2021']], default='2020', max_length=4), ), How to avoid appying hardcoded values in migration file, or set calculted values in form in other way? -
How to make Dynamic Carousel in django using Bootstrap 4
I'm trying to make dynamic carousel in django using Bootstrap 4. But still i can't do that. Anyone please help to done it. Thanks. views.py def dept(request, name): dept_detail = department_detail.objects.get(name = name ) depts_detail = departments.objects.get(name = name ) course = depts_detail.course_set.all() carousel = depts_detail.carousel_set.all() context = {'dept': dept_detail, 'courses':course, 'carousel':carousel} return render(request, "Departments/dept.html", context) models.py class carousel(models.Model): Department = models.ForeignKey(departments,on_delete=models.CASCADE, null = True) Image = models.ImageField(upload_to='Carousel', null = True) Img_title = models.CharField(max_length=30, null=True) Img_desc = models.CharField(max_length=500, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.Department.name template <div id="gallery" class="carousel slide carousel-fade" data-ride="carousel" data-aos="fade-up" data-aos-delay="300"> <ul class="carousel-indicators" > <li data-target="#gallery" data-slide-to="0" class="active"></li> <li data-target="#gallery" data-slide-to="1"></li> <li data-target="#gallery" data-slide-to="2"></li> </ul> <div class="carousel-inner"> {% for img in carousel %} <div class="carousel-item active" data-interval="100"> <img src="{{img.Image.url}}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block rounded position-absolute bg-custom"> <h5>{{img.Img_title}}</h5> <p>{{img.Img_desc}}</p> </div> </div> {% endfor %} </div>