Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django axes resets cool off the moment another failed login occurs
Currently, django axes will reset the cool off timer to the latest time a failed login attempt happens eg. after 3 login failed login attempts axes will lock out the user account for 15 minutes until 1015am(unlock at 1030am). If i attempt a 4th time at 1020am it will extend the lockout to 1035am. Is there anyway to modify axes so that it will not reset the cool off time on login attempt failure? -
Django redirect using an object id?
The main issue I'm having is using the {% url 'Name' %} feature In my html file "productview.html" {% extends "droneApp/base.html" %} {% block content %} <div> {{ objects.name }}<br> </div> <button onclick="window.location.href='{% url 'Checkout/{{objects.id}}' %}'"> {% endblock %} The productview.html page's url is http://127.0.0.1:8000/Store/Product/1 Where 1 is the product id I'm trying to redirect to the checkout page using a button. But I don't understand how to redirect to my html Checkout.html In a previous html file we used href='Checkout/{{item.id}}' but if we use that in this file it just causes the urls to stack into http://127.0.0.1:8000/Store/Product/Checkout/1 instead of http://127.0.0.1:8000/Store/Checkout/1 How do I properly redirect to the right html file? urls.py file from django.urls import path from .import views urlpatterns = [ path('', views.Store, name= "Store"), path('Checkout/<id>', views.createlocation, name="Checkout"), path('Product/<id>', views.product_details, name="Product") ] Which is imported from another urls.py file path('Store/', include('storeApp.urls')), -
How do I configure Django's auth user model to have a UUID (Postgres DB)
I'm using Python 3.9 and Django 3.2. Here is my folder structure + cbapp - settings.py + models - __init__.py - custom_user.py - manage.py Here's what my customer_user.py file looks like $ cat models/custom_user.py import uuid from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Additionally, I have configured this in my settings.py file AUTH_USER_MODEL = 'models.CustomUser' However, when I run "python manage.py makemigrations", I get this error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'models.CustomUser' that has not been installed I have no idea what this means. I have this in my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cbapp', ] ... AUTH_USER_MODEL = 'models.CustomUser' -
Django Models, Custom Model Managers and Foreign Key -- don't play well together
I will simplify the problem as much as I can. I have Three model classes: # abstract base class MyAbstractModel(models.Model) # derived model classes Person(MyAbstractModel) LogoImage(MyAbstractModel) Each Person has: `image = ForeignKey(LogoImage, db_index=True, related_name="person", null=True, on_delete=models.PROTECT)` The MyAbstractModel defines a few model managers: objects = CustomModelManager() objects_all_states = models.Manager() as well as a state field, that can be either active or inactive CustomModelManager is defined as something that'll bring only records that have state == 'active': class CustomModelManager(models.Manager): def get_queryset(self): return super().get_query().filter(self.model, using=self._db).filter(state='active') In my database I have two objects in two tables: Person ID 1 state = 'active' Image ID 1 state = 'inactive' ------ NOW for the issue ---------------- # CORRECT: gives me the person object person = Person.objects.get(id=1) # INCORRECT: I try to get the image id which which works. I get the image object. image = photo.image PROBLEM: I have queried for the person object under objcets manager which is supposed to bring only those items with active status. the image in this person's foreign key is NOT active -- why am I getting it? It's not using the objects model manger to get it. WORKAROND ATTEMPT: added base_manager_name = "objects" to the MyAbstractModel class meta. … -
How to change model attribute in database by using ajax in django?
I have created a real time messages in my project by using AJAX. I refer from this tutorial, https://youtu.be/IpAk1Eu52GU Below is the code for the function. view_questions.html {%block content%} <h2>{{meeting_id}} - Panelist Review Question</h2> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "/panelist/getMessages/{{meeting_id}}/", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.questions) { var temp="<div class='container darker'><b>"+response.questions[key].shareholder_id + "</b>"+"<br><b>"+response.questions[key].sharehold_name + "</b><p>" + response.questions[key].question_id + "</p>"+ "<p>"+response.questions[key].question + "</p><span class='time-left'>"+response.questions[key].date_created+ "</span><input type='submit' name='filter_btn' class='btn btn-primary' value='Filtered' /></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occured') } }); },1000); }) </script> {% endblock %} </body> views.py def getMessages(request, meeting_id): meeting = Meetings.objects.get(meeting_id=meeting_id) questions = Questions.objects.filter(meetings_id=meeting) shareholder = [] for i in questions: shareholder.append( { "question_id": i.question_id, "question" : i.question, "date_created": i.date_created, "shareholder_id": i.shareholders.shareholder_mykad, "sharehold_name": i.shareholders.shareholder_name, } ) # print(list(shareholder)) return JsonResponse({"questions":list(shareholder)}) def questionsView(request, meeting_id): context = {'meeting_id':meeting_id} return render(request, 'view_question.html', context) models.py class Questions(models.Model): question_id = models.AutoField(primary_key=True) question = models.CharField(max_length=400, null=True) is_filtered = models.BooleanField(default=False) meetings = models.ForeignKey(Meetings, on_delete=CASCADE, related_name='questionMeeting') shareholders = models.ForeignKey(AuthenticationShareholders, on_delete=CASCADE, related_name='questionShareholder') date_created = models.DateTimeField(default=timezone.now, null=True) def __str__(self): return str(self.meetings) The real time chat is working but the problem is that I want to create a button that allow user to filter the real time messages by … -
Django ModelForm is not showing any data
I'm new to Django and need some help here, I want to make a page where sellers can sell your items with coupons code and customers can get these coupons. A little mix with JS and I hid the coupon, you have to "purchase" the item, so you can have it. I have 3 tables, "Produto" (Product), "Pedido" (Order) and "Cliente" (Client) and when the custumer try to "purchase" the item, it's only appearing his/her name ! Can someone help me please ? My view.py @login_required(login_url='login') def liberarForm(request, pk): produto = Produto.objects.get(id=pk) #The Product IDs are working in admin panel cliente = Cliente.objects.get(user=request.user) if request.method == 'POST': form_produto = LiberaProduto(request.POST) form_cliente = LiberaPedido(request.POST) if form_cliente.is_valid() and form_produto.is_valid(): form_cliente.save() form_produto.save() return redirect('/') else: form_produto = LiberaProduto(initial={'produto': produto}) #not working form_cliente = LiberaPedido(initial={'cliente': cliente}) context = {'form_cliente': form_cliente, 'form_produto': form_produto} return render(request, "liberar.html", context) My form.py class LiberaPedido(ModelForm): class Meta: model = Pedido fields = '__all__' exclude = ['produto', 'status', 'data_criado'] class LiberaProduto(ModelForm): class Meta: model = Produto fields = ['nome', 'lojista', 'status', 'estoque'] My models.py class Cliente(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) chapa = models.DecimalField(null=True, max_digits=20, decimal_places=0) cpf = models.DecimalField(null=True, max_digits=20, decimal_places=0) telefone = models.CharField(max_length=15, null=True) email = models.CharField(max_length=200, null=True) data_criado = … -
Django DB2 with Multiple Schemas
I would like to know whether it is possible for the Python(3.8.10)-Django(3.2) to connect to the DB2 with multiple schemas. Currently, I am using the settings similar to the example in the GitHub DATABASES = { 'default': { 'ENGINE' : 'ibm_db_django', 'NAME' : 'mydb', 'USER' : 'db2inst1', 'PASSWORD' : 'ibmdb2', 'HOST' : 'localhost', 'PORT' : '50000', 'PCONNECT' : True, #Optional property, default is false }, 'MYSCHEMA': { 'ENGINE' : 'ibm_db_django', 'NAME' : 'mydb', 'USER' : 'db2inst1', 'PASSWORD' : 'ibmdb2', 'HOST' : 'localhost', 'PORT' : '50000', ‘SCHEMA’ : ‘MYSCEHMA’, # no error for adding the ‘SCHEMA’ parameter (or not) until running 'PCONNECT' : True, #Optional property, default is false } However, it is using db2inst1 as the default schema. Is it possible to use other schema? For instance, I am using MYSCHEMA for the application. For the above settings, I am not sure what I could fill the schema name in the DATABASE variables. I have added in corresponding coding: SomeModel.objects.using(‘MYSCHEMA’).all() #The default is to use the “default” database connection. Once it is running in the Django, it will show db2inst1.tabname is an undefined name. (Table willing to use: MYSCHEMA.tabname) -
Easy 'for loop' for datetime field not working in Django(google chart)
I'm trying to use google chart in my Django project, the google chart required a format like ['label1', 'label2', 'label3', new Date(Y, m, d), new Date(Y, m, d), null, 100, null], it's like a list, so I'm trying to keep things simple first, I only replaced the date and leave other fields as default. I have a model in Django that has a start_date field and a due date field, so the only thing I'm doing not is to put them into the 2 'new Date' and for loop, somehow the codes were not working, I would really appreciate it if someone can have a look, cheers. models.py ''' start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) ''' views.py ''' def visualisation(request, project_id): project = Project.objects.get(id=project_id) counts_data = Todo.objects.aggregate( to_do_count=Count('id', filter=Q(status='to_do')), in_progress_count=Count('id', filter=Q(status='in_progress')), done_count=Count('id', filter=Q(status='done')) ) todos = project.todo_set.order_by('-project_code') return render(request, 'todo_lists/progress.html', {"counts_data":counts_data,'team':team,'todos':todos}) ''' HTML ''' function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Task ID'); data.addColumn('string', 'Task Name'); data.addColumn('string', 'Resource'); data.addColumn('date', 'Start Date'); data.addColumn('date', 'End Date'); data.addColumn('number', 'Duration'); data.addColumn('number', 'Percent Complete'); data.addColumn('string', 'Dependencies'); data.addRows([ {% for todo in todos %} ['Introduction', 'Introduction Project', 'Introduction', new Date({{ todo.start_date|date:"Y,m,d"}}), new Date({{ todo.due_date|date:"Y,m,d"}}), null, 50, null], ]); {% endfor %} var options = … -
Is there a way to get all the exercise_uuids from array in JSONField in Django?
I have been looking and exploring similar questions but couldn't find anything. Is this even possible? I am using Django==3.2 and Postgres 12 class MyModel(models.Model): data = models.JSONField() Format of data [ { "exercises": [ { "exercise_id": 1 }, { "exercise_id": 2 }, { "exercise_id": 3 } ] }, { "exercises": [ { "exercise_id": 4 }, { "exercise_id": 5 }, { "exercise_id": 6 } ] } ] Desired Output [1,2,3,4,5,6] -
I am configuring a babel file but the error "tells me" to break the JavaScript syntax rules
That's the code 'presets' : [ [ '@babel/preset-env', { 'targets': { 'node': '10' } } ], '@babel/preset-react' ], 'plugins' : [ '@babel/plugin-proposal-class-properties' ] } ``` And the error is : > frontend@1.0.0 dev C:\Users\invis\OneDrive\Área de Trabalho\JACARANDA\jacaranda\frontend > webpack --mode development --watch asset main.js 1.41 KiB [emitted] [compared for emit] [minimized] (name: main) 1 related asset ./src/index.js 39 bytes [built] [code generated] [1 error] ERROR in ./src/index.js Module build failed (from ./node_modules/babel-loader/lib/index.js): C:\Users\invis\OneDrive\Área de Trabalho\JACARANDA\jacaranda\frontend\babel.config.js:2 'presets': [ ^ SyntaxError: Unexpected token ':' at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._compile (internal/modules/cjs/loader.js:1036:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) at Module.load (internal/modules/cjs/loader.js:937:32) at Function.Module._load (internal/modules/cjs/loader.js:778:12) at Module.require (internal/modules/cjs/loader.js:961:19) at require (internal/modules/cjs/helpers.js:92:18) at loadCjsDefault (C:\Users\invis\OneDrive\Área de Trabalho\JACARANDA\jacaranda\frontend\node_modules\@babel\core\lib\config\files\module- types.js:85:18) at loadCjsOrMjsDefault (C:\Users\invis\OneDrive\Área de Trabalho\JACARANDA\jacaranda\frontend\node_modules\@babel\core\lib\config\files\module- types.js:57:16) at loadCjsOrMjsDefault.next (<anonymous>) webpack 5.59.1 compiled with 1 error in 480 ms``` But when I put equals sign in the place of colons,it gives me another error saying "SyntaxError: Invalid left-hand side in assignment" ,I have a tutorial's file where I took some information and syntax to try to fix this bug,but nothing changed between them,so I'm very confused what to do,if you could help me I would appreciate a lot THANKS! -
Change the status when a barcode is scan using django
I have a web page where it shows a table of data, how do I make it so that when I scan a 2D barcode which is a MCO Number barcode with a 2D barcode scanner, it will change the current status and the next status? This is my current page with the data here, so when a user scan a MCO Number barcode with the scanner, it will change the status and the next status. How do i do that? Views.py @login_required() def investigation(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q( serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().filter(Q(nextstatus='Technical Investigation')).order_by("-Datetime") # Sort BY: part = request.GET.get('sortType') valid_sort = ["partno", "serialno", "Customername", "mcoNum"] # Sort the workshop data in ascending order acording to the part number, serial number, customer name and the MCO Number if (part is not None) and part in valid_sort: allusername = allusername.order_by(part) page = request.GET.get('page') paginator = Paginator(allusername, 10) # 1 page will only show 10 data, if more than 10 data it will move it to the next page. try: allusername = paginator.page(page) except PageNotAnInteger: allusername = … -
Avoid Celery retries for unregistered task
We have a Django app with celery to handle an asynchronous tasks. We use AWS SQS as the task broker. We ended up with a bad task to be processed (removed the task implementation without removing the celery-beat entry). This resulted in errors: Received unregistered task of type KeyError('some_deleted_task'). The message has been ignored and discarded. Once we cleaned up the celery-beat entries, we continued getting errors ~2min (visibility timeout on SQS was set to 2 minutes). Behaviour seemed to be: Task added to queue, in SQS as 'Available' Worker picks up the task, moves the SQS message to 'in flight' Worker fails immediately due to missing implementation. two minutes later, SQS moves the message from 'in flight', back to 'available' Goto 2 To clear the errors, we purged the SQS queue, but this could have resulted in losing other tasks. I'd like to configure celery so it won't keep trying these missing tasks indefinitely. -
Why is plotly failing to load in django project?
I am using Plotly.react() function to render a graph on my template HTML file. In the function, I am passing in the id for the HTML element where I want the graph to render, data for both x&y axis, plot type, and layout information. Excerpt from my code: var metricsOneGraphDiv = document.getElementById('metricsOne'); var metricsOneTraces = [{ x: {{rmabRisks.dates|safe}}, y: {{rmabRisks.counts}}, type: 'scatter', }] var metricsOneLayout = {{rmabRisksLayout | safe}} Plotly.react(metricsOneGraphDiv, metricsOneTraces, metricsOneLayout); I get the following error from the Firefox console when I try loading this view Loading failed for the <script> with source https://cdn.plot.ly/plotly-latest.min.js. I have tried to reinstall plotly, however, I get stuck waiting for the pip install to complete. Can someone please suggest a possible solution? Thanks in advance -
The page does not display information about created links in the admin panel. Django
The page should display a feedback form and links created in the admin panel. Created models: from django.db import models class ContactModel(models.Model): # feedback form name = models.CharField(max_length=50) email = models.EmailField() website = models.URLField() message = models.TextField(max_length=5000) create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name} - {self.email}' class ContactLink(models.Model): # links icon = models.FileField(upload_to='icons/') name = models.CharField(max_length=200) def __str__(self): return self.name I connected the models to the admin panel: from django.contrib import admin from .models import ContactModel, ContactLink @admin.register(ContactModel) class ContactModelAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'email', 'create_at'] list_display_links = ('name',) admin.site.register(ContactLink) Everything works correctly, you can create links in the admin panel. Below views.py: from django.shortcuts import render from django.views import View from .models import ContactLink class ContactView(View): def get(self, request): contacts = ContactLink.objects.all() form = ContactForm() return render(request, 'contact/contact.html', {'contact': contacts, 'form': form}) urls.py: from django.urls import path from . import views urlpatterns = [ path('contact/', views.ContactView.as_view(), name='contact'), path('feedback/', views.CreateContact.as_view(), name='feedback'), ] I go through the for loop through the code to return links from the admin panel: #links <div class="contact__widget"> <ul> {% for contact in contacts %} <li> <img src="{{ contact.icon.url }}"> <span>{{ contact.name }}</span> </li> {% endfor %} </ul> </div> #feedback form <form action="{% url 'feedback' %}" method="post"> … -
MultiValueDictKeyError at /homepage/detail when trying to query database with django
I understand from other posts that MultiValueDictKeyError is related to whatever is in the .html file isn't reaching the database. I haven't found a specific solution that seems to work for me though. Here is the views.py: def detail(request): try: if request.method == 'POST': name = request.POST['name'] state = request.POST['state'] tm = TM.objects.filter(Name__icontains=name, State__icontains = state) return render(request, 'homepage/detail.html', {'name': name, 'state' : state, 'tm': tm}) else: return render(request, 'homepage/detail.html', {}) except TM.DoesNotExist: raise Http404("Info Does Not Exist") Here is the detail.html: <html> <head> <title>Territorial</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> {% load static %} <link rel="stylesheet" href="{% static 'html5up-read-only/assets/css/main.css' %}" /> {% load static %} <link rel="stylesheet" href="{% static 'html5up-read-only/assets/css/detail.css' %}" /> </head> <body class="is-preload"> <h2>Territory Managers</h2> {% if name %} {{ name }} {{ state }} {% else %} <h3> No results </h3> {% endif %} and here is the models.py: class TM(models.Model): #Change this to territory manager and delete database and recreate Name = models.CharField(max_length = 200,null=True) Cell = models.CharField(max_length= 200, null=True) EmailAddress = models.EmailField(null=True) Notes = models.CharField(max_length=500, null=True) Distributor = models.CharField(max_length=200,null=True) State = models.CharField(max_length=200,null=True) Brand = models.CharField(max_length=200,null=True) def __str__(self): try: if self.Distributor is not NullBooleanField: return self.Name + ' - ' + self.Distributor … -
I have created model form using django. The form isnt saving on submit though. The page keeps displaying the invalid form page
index.html <div class="container add_dog_form"> <form method="POST"> {% csrf_token %} <div class="row" id="namefield"> {{ form.as_table }} </div> <div class="row"> <button type="Submit" id="form_submit">Submit</button> </div> </form> </div> forms.py class DogForm(forms.ModelForm): class Meta: model = Dog fields = ['name', 'dog_pic'] views.py class IndexView(generic.ListView): template_name = "takyi1/index.html" context_object_name = "dogs_context" dog_form = DogForm def get_context_data(self, **kwargs): self.dogs_context = super().get_context_data(**kwargs) self.dogs_context['dogs'] = self.dog self.dogs_context['form'] = self.dog_form return self.dogs_context def post(self, request, *args, **kwargs): form = self.dog_form(request.POST) if form.is_valid(): form.save() return HttpResponse('Valid Form') else: return HttpResponse('inValid Form') -
Django template tags in HTML
I am trying to point an image source to a filepath tag I have specified in my views.py, but for some reason it won't load in the project index file, but will in the specific projects pages. And all my other tags on the same page work, so Am unsure what I am doing wrong? <img src="{{ filepath }}" class="card-img-top" alt="Project Image"> Appears in the page as <img src="" class="card-img-top" alt="Project Image"> which shows the alt text. Views.py filepath = "/static/img/" + project.title + ".png" -
cannot retrieve values from database django
I have a table I am trying to retrieve values from. It has two foreign keys and that is it. I use get_or_create on the table and create an object. I verify with the admin panel that the object is there. Then, I try to retrieve it but I do not get the values even though I can see them in the admin panel. Here is the table: class req(models.Model): to = models.ForeignKey(User,on_delete=models.CASCADE) from = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "request sent" In the piece of code below, what I retrieve I try to display it as it is in the p tag and also I tried doing req.to and req.from.first_name but in vain, I did not see any values. def get(self, request): u = get_user(request) try: my_requests = req.objects.get(from=u) except req.DoesNotExist: fr = None if fr == None: return redirect(reverse('dogpark:index')) if my_requests != False: context_dict['req'] = my_requests return render(request, 'myapp/req.html', context=context_dict) Can anybody see the problem that I cannot and comment ? -
pytest parametrize is deleting my fixturedata after first parametrize value
I have two fixtures: @pytest.fixture def all_users(): all_existing_group_names = Group.objects.all().values_list( "name", flat=True ) tmp_list = [] for group_name in all_existing_group_names: user = User.objects.create(username=f"user-{group_name}", password=group_name) group = Group.objects.get(name=group_name) user.groups.add(group) tmp_list.append(user) return tmp_list and @pytest.fixture def admin_user(all_users): User.objects.all() # is empty the second time return all_users And this is how my test looks like Class TestSomething: @pytest.mark.parametrize('first_val, second_val', [('test', 'test'), ('test2', 'test2'),..]) @pytest.mark.django_db(transaction=True) def test_something(self, all_users, first_val, second_val): ... In my test i am deleting some model instances through a post request(which in the view is wrapped with a transaction.atomic request). This is why i need transaction=True, because the deleted objects need to be there again when the second run of parametrize runs. Now, my problem is that if i use transaction=True, on the second run it will revisit my fixtures but now suddenly my database is empty, the Groups.objects.all() method doesn't return anything at all. If i switch back to transaction=False, it works but this way i have a problem because my post request deleted stuff that i need for the next parametrize run. What am i doing wrong? I don't get it :( ughhh -
Django Rest Framework - Write an explicit `.update()` method for serializer
I'm trying to make a put request using DRF but this error appears: AssertionError: The `.update()` method does not support writable dotted-source fields by default. Write an explicit `.update()` method for serializer `model.serializers.ModelSerializer`, or set `read_only=True` on dotted-source serializer fields. This is the view: class Model(GenericAPIView): def put(self, request, pk): model = MyModel.objects.filter(id=pk).first() serializer = ModelSerializer(model, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the serializer: class ModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' def update(self, instance, validated_data): status = validated_data.pop('status', None) model = super().update(instance, validated_data) if status: model.set_status(status) model.save() return model What is wrong with the update() method? Also, how can I only update one field of the object? -
Django: is there something like an id of a queryset?
I am looking for something that I can use to have the value of a queryset. This would be the replacement of the use of filters like this: # Normal myquerysetA = Model.objects.filter(name="John",age=20) # Value i wanna query_id = myquerysetA.query_id() # Equivalent myquerysetB = Model.objects.filter(query_id=77777) myquerysetB == myquerysetA True -
Кнопка "Вернуться назад" со всеми заполненными параметрами формы Django
При ошибке на стороне сервера после отправки формы должна выходить страница с ошибкой и кнопкой вернуться назад. Если нажать на кнопку, то произойдёт редирект на страницу формы, и поля формы должны быть заполнены также, как до первой отправки. Не совсем понимаю, как это реализовать. Сохранение полей формы можно реализовать через request.session, но как их вывести? -
I have two images in the same static folder. Why is Django only rendering one of them?
I am trying to create a carousel on my homepage in my Django Project. Carousel code in base.html: {% load static %} <!doctype html> <html lang="en"> (irrelevant header and navbar code here) <div id="carouselHomepage" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselHomepage" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselHomepage" data-bs-slide-to="1" aria-label="Slide 2"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static '/shirts.png' %}" class="d-block w-100" alt=""> </div> <div class="carousel-item"> <img src="{% static '/banner.png' %}" class="d-block w-100" alt=""> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselHomepage" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previouss</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselHomepage" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Nexts</span> </button> </div> (irrelevant body and jquery scripts here) </html> Note I have loaded static at the top of the file. The images banner.png and shirts.png are both in my app/static folder. The banner.png image is loading fine, but the shirts.png doesn't load and I see an error in my project terminal in VS Code: "GET /static/shirts.png HTTP/1.1" 404 1789 I can't figure out what this 1789 error means. There are a few other images in my static folder, and I get this error when trying to include any picture other than banner.png, which is giving no issues and loading … -
I'm trying to connect Django with Mysql but 'm getting an error 'list' object has no attribute '_default_manager'
Views.py file from django.shortcuts import render from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView from .models import News_Post,Category from .forms import addArticleForm,updateArticleForm from django.template import loader from django.urls import reverse_lazy import mysql.connector # Create your views here. mydb = mysql.connector.connect( host="localhost", user="root", password="goodboy123", database = "nexus360" ) cursor = mydb.cursor() # -- Display all the news on the homePage according to the latest date -- # class HomeView(ListView): cursor.execute("select * from news_post") model = cursor.fetchall() template_name='home.html' ordering=['-date'] def get_context_data(self,*args,**kwargs): cursor.execute("select * from category") category_menu= cursor.fetchall() context=super(HomeView,self).get_context_data(*args,**kwargs) context["category_menu"]=category_menu print(context) return context Models.py Here is the models.py file but I don't think this file is required. I'm new to Django and don't have much idea from django.db import models from django.contrib.auth.models import User from django.urls import reverse import datetime from ckeditor.fields import RichTextField #---------Creating the tables-------# #---------Category Table---------# class Category(models.Model): name=models.CharField(max_length=30) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') # -----UserAccount Table-----# class UserAccount (models.Model): user_id=models.CharField(max_length=100, null=False , primary_key=True) email=models.EmailField(null=True) contact_no=models.CharField(max_length=13) password=models.CharField(max_length=100) # -----Table column of news articles class News_Post(models.Model): title=models.CharField(max_length=100) # News_content=models.TextField() News_content=RichTextField(blank=True,null=True) date=models.DateField(default='DEFAULT VALUE') #post_date=models.DateField(auto_now_add=True) author=models.ForeignKey(User,on_delete=models.CASCADE) category=models.CharField(max_length=30,default='Politics') def __str__(self): return self.title + ' | '+ str(self.author) def get_absolute_url(self): return reverse('home') **urls.py ** Here is the Urls.py file from django.urls import path from .views import … -
django admin error when adding element to a table (Please correct the errors below)
I've spend the whole day on an error tell by django admin = Please correct the error bellow) when saving data The thing is i don't get any other indication about the error and i have no idea how to solve the problem models.py class meeting(models.Model): time = models.DateTimeField() capacity = models.CharField(max_length=25, default=0) USERNAME_FIELD = 'time' REQUIRED_FIELDS = ['time'] admin.py class MeetingAdmin(BaseUserAdmin): list_display = ('time', 'capacity') list_filter = ('time', 'capacity') fieldsets = ( (None, {'fields': ('time', 'capacity')}), ) add_fieldsets = ( (None, { 'classes': ('time', 'capacity'), 'fields': ('time', 'capacity'), }), ) search_fields = ('time',) ordering = ('time',) filter_horizontal = () admin.site.register(User, UserAdmin) admin.site.register(meeting, MeetingAdmin)