Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i filter date exec sql
Hi my problem is i try to filter date but url load but form not. I try to filter but not filter i dont know what is the problem.. When i try to swap date the url its ok but in form not load results ok always same date in form Img url / Inputs HTML views.py def BootstrapFilterView(request): fecha = datetime.now() format_min = fecha.strftime('%d-%m-%Y') date_max = fecha + timedelta(days=1) format_max = date_max.strftime('%d-%m-%Y') cursor.execute("[Pr].[dbo].[NX_Pr]" + "'" + str(format_min) + "'," + "'" + str(format_max) + "'") qs = cursor.fetchall() operacion = request.GET.get('orden') if format_min and format_max: url_listapdf = reverse('materials_all') + '?date_min=' + format_min + '&date_max=' + format_max elif format_min and not format_max: url_listapdf = reverse('materials_all') + '?date_min=' + format_min elif not format_min and format_max: url_listapdf = reverse('materials_all') + '?date_max=' + format_max else: url_listapdf = reverse('materials_all') context = { 'queryset': qs, 'format_min': format_min, 'format_max': format_max, 'url_listapdf': url_listapdf } return render(request, "app/necesidades.html", context) HTML: <form method="GET" action="."> <div class="card-body"> <u><legend class="blue">FECHA</legend></u> <div class="input-group date"> <b class="b-form">DESDE:</b><input type="text" class="form-control" id="publishDateMin" name="date_min" value="{{format_min}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> <div class="input-group date"> <b class="b-form">HASTA: </b> <input type="text" class="form-control" id="publishDateMax" name="date_max" value="{{format_max}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> <br /> -
How to connect s3 amazon to your django project?
guys sorry for disturbing you. Hope you all are doing great actually I have uploaded the images as well as static files in the s3 bucket but now the error is when we go to the path images does not appear! and when we inspect it, it shows the correct path where the image should be placed and when we access this from s3 we get to see every image here so I was wondering that do we need to change the URLs? and if yes how to do it?? -
wrapping password reset confirm url in a href doesn't work
I have a password reset template with the following redirect to a password confirm view: <a href="{{ protocol }}://{{ domain }}{% url 'consumer_portal:password-reset-confirm' uidb64=uid token=token %}">Change password</a> When I click "Change password" on the browser it doesn't work. However I can copy the url on the change password text and paste it in my browser and it will redirect me to change my password. Anyone know why clicking it doesn't work but pasting it in the browser does? For context, my reset confirm template has the standard link check {% if validlink %} <p>Please enter your new password twice so we can verify you typed it in correctly.</p> <form method="post"> {% form %} </form> {% else %} <p>password reset invalid</p> -
Can anyone help me identify that heroku application error
After opening app I deployed, there is an error: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Can you please help me solving or identifying that error? There are logs » Warning: heroku update available from 7.47.6 to 7.53.1. 2021-05-17T08:07:01.958623+00:00 app[api]: Release v1 created by user filip.antoniak99@gmail.com 2021-05-17T08:07:01.958623+00:00 app[api]: Initial release by user filip.antoniak99@gmail.com 2021-05-17T08:07:02.185037+00:00 app[api]: Enable Logplex by user filip.antoniak99@gmail.com 2021-05-17T08:07:02.185037+00:00 app[api]: Release v2 created by user filip.antoniak99@gmail.com 2021-05-17T08:09:13.560585+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=ergonomizer.herokuapp.com request_id=5b27d2eb-9b93-4169-b5a1-c5041f0c46d4 fwd="37.249.138.76" dyno= connect= service= status=502 bytes= protocol=https 2021-05-17T08:09:13.788320+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/favicon.ico" host=ergonomizer.herokuapp.com request_id=0f06c72b-8d59-4409-9946-a343a7ac7b57 fwd="37.249.138.76" dyno= connect= service= status=502 bytes= protocol=https 2021-05-17T08:10:38.000000+00:00 app[api]: Build started by user filip.antoniak99@gmail.com 2021-05-17T08:10:57.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/9afe7277-a8cc-4782-b52d-bb5698d2273c/activity/builds/be2f281b-2961-4df6-8abd-bd691199f6d4 2021-05-17T08:14:21.000000+00:00 app[api]: Build started by user filip.antoniak99@gmail.com 2021-05-17T08:14:40.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/9afe7277-a8cc-4782-b52d-bb5698d2273c/activity/builds/aba64d28-3b09-4ca9-a0db-a5277ff0eac5 2021-05-17T08:18:00.000000+00:00 app[api]: Build started by user filip.antoniak99@gmail.com 2021-05-17T08:18:20.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/9afe7277-a8cc-4782-b52d-bb5698d2273c/activity/builds/9273f61b-0a02-414f-b7cc-0674b19f8b80 2021-05-17T08:27:17.000000+00:00 app[api]: Build started by user filip.antoniak99@gmail.com 2021-05-17T08:27:35.000000+00:00 app[api]: Build failed -- check your build output: … -
Django FastApi 2 servers
Please help me. I have a project on Django, in which some of the processes go through celery. But now I want to transfer all the complex data processing to another server. I plan to use FastApi. But the question arose - how to properly organize the work with the client files that will be processed . Do I need to receive files from the client and save them on the second server, or do I need to save them on the first server and send them over tcp? Perhaps there are other options ? How do I do this ? -
django templates without db, model
I am creating a bulletin board that communicates by DB <> API <> WEB(db-less) method. How should I use {% if user.is_authenticated %} and {% if user.username == A or B %} and so on. when there is no DB or Model? -
Django prefetch_related and N+1 - How is it solved?
I am sitting with a query looking like this: # Get the amount of kilo attached to products product_data = {} for productSpy in ProductSpy.objects.all(): product_data[productSpy.product.product_id] = productSpy.kilo # RERUN I do not see how I on my last line would be able to use prefetch_related. In the examples in the docs it's very simplified and somehow makes sense, but I do not understand the whole concept enough to see myself out of this. Could I please get explained what's being done and how? I find this very important to understand, and where met by my first N+1 here. Thank you up front for your time. -
Class based view is not redirecting to Home after Upload
I am building a BlogApp and I build a Feature of multiple photo upload at a Time. When i add pictures the , I want to redirect to home BUT it stills on that same page. I have also tried HttpResponse but it is still not redirecting. views.py class UploadMultiple(View): def get(self, request): photo = Gall.objects.all() return render(self.request, 'new_gal.html', {'photos': photo}) def post(self, request): form = GallForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return redirect('home') I have also tried :- return HttpResponseRedirect(reverse('home')) When i select then photos are saving BUT it is not redirecting to home page. I have no idea, what am i doing wrong. I am new in using Class Based Views. Any help would be Appreciated. Thank You in Advance. -
How to make a permission for checking the Model only can be update by the belonged users?
The below is my code about model Domain's Update: serializer.py: class DomainUpdateSerializer(serializers.ModelSerializer): class Meta: model = Domain fields = "__all__" models.py: class Domain(models.Model): domain_name = models.CharField(max_length=512, help_text='domain. eg.example.com') cname = models.ForeignKey( unique=True, to=CNAMEModel, on_delete=models.DO_NOTHING, related_name="domains", help_text="CNAME") ssl_cert = models.TextField(max_length=40960, help_text="SSL cert + ca-bundle") ssl_key = models.TextField(max_length=40960, help_text="SSL key") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.domain_name def __unicode__(self): return self.domain_name class Meta: verbose_name = "domain" verbose_name_plural = "domain" ordering = ['ctime'] class CNAMEModel(models.Model): name = models.CharField(max_length=64, unique=True, help_text=". eg:gat.demo.com") desc = models.CharField(max_length=5120, null=True, blank=True, help_text="desc") desc_en = models.CharField(max_length=5120, null=True, blank=True") user = models.OneToOneField(unique=True, to=AuthUser, on_delete=models.DO_NOTHING, help_text="belong user") is_active = models.BooleanField(default=True) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.name def __unicode__(self): return self.name class Meta: verbose_name = "CNAME" verbose_name_plural = "CNAME" ordering = ['ctime'] views.py: class DomainUpdateAPIView(UpdateAPIView): serializer_class = DomainUpdateSerializer permission_classes = [IsAuthenticated, IsAdminUser] queryset = Domain.objects.all() You see Domain belong to CNAME, CNAME belong to a user. I have a question, how can I make a permission for checking the Domain only can be update by the belonged users or AdminUser(IsAdminUser have solved)? -
Django ORM more than one row returned by a subquery used as an expression
My Subquery behaves differently on different machines. Subquery looks like: Sale.objects.filter(object_id=OuterRef("id"), is_canceled=False) .values("object") .annotate(total_amount=Coalesce(Sum("amount"), 0)) .values("total_amount") On my local machine I have 3 Sale instances and the result of the query is: <QuerySet [{'object': 1, 'total_amount': 210}]> On my dev machine I have 2 Sale instances and the result of a call looks like this: <QuerySet [{'object': 100, 'total_amount': 20}, {'object': 100, 'total_amount': 10}]> I checked the query Django ORM generates in both cases and it looks the same SELECT "object_sale"."object_id", COALESCE(SUM("object_sale"."amount"), 0) AS "total_amount" FROM "object_sale" WHERE ("object_sale"."object_id" = 1) GROUP BY "object_sale"."object_id", "object_sale"."price" ORDER BY "object_sale"."price" ASC -
How to fix "Infinite loop caused by ordering" error in Django
When trying to create an instance of a model from the Django admin site on some models that are inherited according to a similar principle, the following error pops up: enter image description here Please tell me how can I fix this? class Task(BaseEntity): """ Задача - проведение каких либо работ BaseProperties: title, created_at, closed_at, author, description, comment, photo BaseEntity: Временные: date_start_work_p, date_start_work_f, date_end_work_p, date_end_work_f Сотрудники: curator, working_team, observers, Связи админ. сущностей: lead_source Коммерческие: client_LE, expenses_p, expenses_f, expenses_is_calculated, contract_price_p, contract_price_f __str__.title BaseHavingSlug: slug BaseHavingManager: manager, assistants BaseHavingParent: project_parent, deal_parent, stage_parent, task_parent """ type_task = models.ForeignKey('TypeTask', on_delete=models.PROTECT, related_name='type_task', null=True, verbose_name='Тип Задачи') working_status_task = models.ManyToManyField('WorkingStatusTask', related_name='working_status_task', verbose_name='Рабочие статусы') closure_status_task = models.ForeignKey('ClosureStatusTask', on_delete=models.PROTECT, related_name='closure_status_task', verbose_name='Статус закрытия', null=True, blank=True) status_task = models.ForeignKey('StatusTask', on_delete=models.PROTECT, related_name='status_task', null=True, verbose_name='Статус Задачи') # если не null – связь по срокам previous_task = models.ForeignKey('Task', on_delete=models.PROTECT, related_name='previous_task_related', verbose_name='Предыдущая задача', null=True, blank=True) # Как считать стоимость – в деньгах или в часах in_money = models.BooleanField(default=True, verbose_name='В деньгах') # Затраченные рабочие часы # Изменить после заполнения можно только через согласование working_hours_p = models.PositiveSmallIntegerField(verbose_name='Рабочие часы (план)', unique=True) working_hours_f = models.PositiveSmallIntegerField(verbose_name='Рабочие часы (факт)', unique=True) # Как считать ФОТ – от плана или от факта salary_is_from_fact = models.BooleanField(default=True, verbose_name='В деньгах') salary = MoneyField(max_digits=19, decimal_places=4, default_currency='RUB', verbose_name='ФОТ', … -
Error When submit comment for the second post in Django
I creating a blog in this blog feed there are posts and for each post there are comments, So my problem when I submit a comment for the first post is submitting successfully but when I try to submit a comment for the second post or third it doesn't submit My comments Form class PostCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = PostCommentIDF fields = {'post', 'content'} widgets = { 'content': forms.Textarea(attrs={'class': 'rounded-0 form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True', }) } def save(self, *args, **kwargs): PostCommentIDF.objects.rebuild() return super(PostCommentForm, self).save(*args, **kwargs) My comments view @login_required def add_comment_post(request): if request.method == 'POST': if request.POST.get('action') == 'delete': id = request.POST.get('nodeid') c = PostCommentIDF.objects.get(id=id) c.delete() return JsonResponse({'remove': id}) else: comment_form = PostCommentForm(request.POST ) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.save() result = comment_form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result': result, 'user': user}) return JsonResponse({'result': "No action took"}) My comment form in home page template <form id="Postcommentform" class="Postcommentform" method="post" style="width: 100%;"> {% load mptt_tags %} {% csrf_token %} <select class="d-none" name="post" id="id_post"> <option value="{{ video.id }}" selected="{{ video.id }}"></option> </select> <div class="d-flex"> <label class="small font-weight-bold">{{ comments.parent.label }}</label> {{ comments.parent }} {{comments.content}} <button value="Postcommentform" id="Postnewcomment" type="submit" style="color: white; border-radius: 0;" class="d-flex … -
DRF spectacular swagger ui problem when extending a new TokenAuthentication for DRF
when extending a new Token Authentication class from rest_framework_simplejwt.authentication.JWTAuthentication drf-spectacular swagger-ui authorize button disappears and there is no way to add token bearer, I guess when you subclass it goes wrong. steps to reproduce: first, create a Django project with rest framework and drf-spectacular and simple jwt installed and configured with documentation guidance. got to /swagger-ui/ and it works fine. then create a subclass of JWTAuthentication like below: from rest_framework_simplejwt.authentication import JWTAuthentication as JWTA class JWTAuthentication(JWTA): pass and in your settings: REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'path_to_your_module.JWTAuthentication', ), } and now if you go to /swagger-ui/ there is no authorize button!!! how can I fix this? and I even tried to create an AuthenticationExtension like: from drf_spectacular.contrib.rest_framework_simplejwt import SimpleJWTScheme class SimpleJWTTokenUserScheme(SimpleJWTScheme): target_class = 'spec.test.JWTAuthentication' but there is no way to register it anywhere nor on the internet nor in the documentation!! how can I fix authorize button when overriding an Authentication class?? -
Image is not passing to view (cropperjs, django, ajax)
I have an user profile where he can crop his image, and so after cropping, and printing data in view nothing is passed to view Form <form method="post" action="change_photo/" id="avatar_changing_form"> {% csrf_token %} <label for="upload_image"> {% if item.image%} <img src="{{item.image.url}}" alt="" style="max-height:300px"> {%else%} <img src="{%static 'avatar_sample.png' %}" id="uploaded_image" class="img-responsive img-circle" /> {%endif%} <div class="overlay"> <div class="text">Click to Change Profile Image</div> </div> <!-- <input type="file" name="image" class="image" id="upload_image" style="display:none" /> --> {{imageForm.image}} </label> </form> JS & Ajax $(document).ready(function(){ const imageForm = document.getElementById('avatar_changing_form') const confirmBtn = document.getElementById('crop') const input = document.getElementById('upload_image') const csrf = document.getElementsByName('csrfmiddlewaretoken') var $modal = $('#modal'); var image = document.getElementById('sample_image'); var cropper; $('#upload_image').change(function (event) { var files = event.target.files; var done = function (url) { image.src = url; $modal.modal('show'); }; if (files && files.length > 0) { reader = new FileReader(); reader.onload = function (event) { done(reader.result); }; reader.readAsDataURL(files[0]); } }); $modal.on('shown.bs.modal', function () { cropper = new Cropper(image, { aspectRatio: 1, viewMode: 3, preview: '.preview' }); }).on('hidden.bs.modal', function () { cropper.destroy(); cropper = null; }); $('#crop').click(function () { cropper.getCroppedCanvas().toBlob((blob) => { console.log('confirmed') const fd = new FormData(); fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('file', blob, 'my-image.png'); $.ajax({ type: 'POST', url: imageForm.action, enctype: 'multipart/form-data', data: fd, success: function (response) { console.log('success', response) $modal.modal('hide'); … -
CSRF token missing - django/ajax
CSRF token missing - django/ajax Have already tried each and every solution proposed in this article but nothing seems to work for me. "CSRF token missing or incorrect" while post parameter via AJAX in Django $(document).on('click', '.attendance_submit', function(){ var urlname = '{% url "test" %}' var tableSel = $('.attendance_table tr:not(.group)'); alert("DATA :"+html2json(tableSel)); $.ajax({ url : urlname, type: 'POST', dataType: 'json', contentType: 'application/json', data: { csrfmiddlewaretoken: '{% csrf_token %}', 'TableData': html2json(tableSel) }, success: alert('Attendance updated successfully') }); return false; }); PS: CSRF Token is also enabled in the form which I am using in this template, even tried removing from the form but to no avail. -
I have some issues with Django templates that I downloaded
I am working on Django templates so I downloaded one template "Travello" and I am trying to customize it but the template can not be loaded CSS, js files. so I am getting errors like this... Refused to apply style from '' because its MIME type ('text/HTML) is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET http://127.0.0.1:5500/templates/%7B%%20static%20'js/jquery-3.2.1.min.js'%20%%7D net::ERR_ABORTED 400 (Bad Request) please help me I'm just a beginner... thank you for helping me -
Deploying heroku - Push failed
I need some help to solve this. I don't have much experience with Heroku, this is my first time doing it but I need to deploy some app really quickly. I've tried to disable collectstatic with heroku config:set DEBUG_COLLECTSTATIC=1 -a name_of_app But it haven't made any change. Can anyone help me, please ? Here are logs: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the buildpack default: python-3.9.5 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.9.5 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.3.1 Downloading asgiref-3.3.1-py3-none-any.whl (19 kB) Collecting Django==3.1.5 Downloading Django-3.1.5-py3-none-any.whl (7.8 MB) Collecting django-crispy-forms==1.10.0 Downloading django_crispy_forms-1.10.0-py3-none-any.whl (107 kB) Collecting pytz==2020.5 Downloading pytz-2020.5-py2.py3-none-any.whl (510 kB) Collecting sqlparse==0.4.1 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Installing collected packages: asgiref, sqlparse, pytz, Django, django-crispy-forms Successfully installed Django-3.1.5 asgiref-3.3.1 django-crispy-forms-1.10.0 pytz-2020.5 sqlparse-0.4.1 -----> $ python Project/manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_784131b5/Project/manage.py", line 22, in <module> main() File "/tmp/build_784131b5/Project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File … -
how to do a aggregate sorting across various django models?
I have 4 models User, Posts, Comments, Friends. Please refer the below models now I need an API for the top 10 recent activities done by the user which can be a combination of all the three i.e recent posts by the user + recent comments made by the user + recent friend added by the user or it can be one only comments or it can be only on posts or it can only be friends basically I need the top 10 recent things done by the user , how can I sort this data's by date across the three models and put in a single result list? so I can pagination to the result list User model- stores all details about the users class User(models.Model): ...... '' '''' Posts model- stores the posts created by the users class Posts(models.Model): ...... '' '''' Comments - stores the comments made by the users on a post class Comments(models.Model): ...... '' '''' Friends - stores the friends information class Friends(models.Model): ...... '' '''' -
Template inheritance: Change Nav-Tab active tab and URL with Click on Tab (Django, Bootstrap)
I'm currently designing a Web-App with Django and Bootstrap. I have several HTML files which I want to load dynamically in one "Parent" HTML-file via different URL's. Everything is working so far. My Goal is to use a Tab or Nav-Bar for the Template inheritance. As soon as I click on another Tab, the corresponding URL becomes targeted an the HTML content should open in the selected Tab . I can't manage both at the same time. Either the Tab opens or the new URL is loaded. In the second case the default Tab is active again which is caused by reloading the page. I also tried using a JavaScrip function to load the new URL and afterwards show the corresponding Tab. But no success so far... Im happy with every hint regarding my problem. Thanks a lot -
How to transform a queryset instance to dictionary Django
In order to optimize my function, I would like to transform a queryset to a dictionary and stock it in cache. Here is my instance and the output: nodes = Node.objects.select_related().all() <QuerySet [<Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network IDF )>, <Node: Node : No name of ( Network … -
Need to create users reference chart using python, django
I am creating an MLM application using python, Django, need to print all users according to reference users in a tree diagram. The new user added automatically in the reference of the user. I want this design But getting In cmd, i am getting the user with refer user name but not able to display in template. (views.py) def referringtree(request): mainuser = User.objects.filter(username__contains=request.user) user = User.objects.all() allud = [] udd = [] for us in user: username = us.username print(username) allud.append(username) ud = UserDetails.objects.filter(refer_by = username) for u in ud: print(u.email) uemail = u.email udd.append([username, uemail]) subuser = UserDetails.objects.filter(refer_by = mainuser[0].username) alluser = UserDetails.objects.all() return render(request, 'referring_tree.html', {'mainuser':mainuser, 'subuser':subuser, 'alluser':alluser, 'user':user, 'username':allud, 'udd':udd}) (template) <figure class="top-scroll"> <ul class="usertree"> <li> {% for mainuser in mainuser %} <span>{{mainuser.username}}<img class="user-avtar-tree" src="{% static 'images/user-icon.png' %}"> </span> {% endfor %} <ul> {% for subuser in subuser %} <li> <span>{{subuser.email}}<img class="user-avtar-tree" src="{% static 'images/user-icon.png' %}"> </span> <ul> {% for alluser in alluser %} {% if alluser.refer_by == subuser.email %} <li><span>{{ alluser.email }}<img class="user-avtar-tree" src="{% static 'images/user-icon.png' %}"></span> </li> {% endif %} {% endfor %} </ul> </li> {% endfor %} </ul> </li> </ul> </figure> -
NoReverseMatch at /... With no argument not found
Please at all. I'm currently facing this issue trying to redirect to previous page after form submission ** NoReverseMatch at /studentportal/8/result/resultcreate/ Reverse for 'student_result' with no arguments not found. 1 pattern(s) tried: ['studentportal/(?P[0-9]+)/result/$'] ** Views.py class ResultCreateView(CreateView ): template_name = 'studentportal/result_create.html' form_class = ResultModelForm queryset = StudentResult.objects.all() model = StudentResult def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) def get_success_url(self): return HttpResponseRedirect(reverse('studentportal:student_result')) Urls.py app_name = 'studentportal' urlpatterns = [ path('student_list', StudentListView.as_view(), name='student_list'), path('<int:pk>/', StudentDetailView.as_view(), name='student_detail'), path('create/', StudentCreateView.as_view(), name='student_create'), path('<int:pk>/update/', StudentUpdateView.as_view(), name='student_update'), path('<int:pk>/delete/', StudentDeleteView.as_view(), name='student_delete'), path('<int:pk>/result/', StudentResultView.as_view(), name='student_result'), path('<int:pk>/result/resultcreate/', ResultCreateView.as_view(), name='result_create'), ] Template html <form method="POST" action=" "> {% csrf_token %} {{ form|crispy }} <button class="regBtn">Submit</button> <form/> -
Accessing inline fields within inline get_formset in Django Admin
I have the following example where I have buildings(address, location,...) and apartments(name, size, type, building). One building containing multiple apartments. class BuildingAdmin(admin.ModelAdmin): inlines = [ApartmentInline,] class ApartmentInline(admin.StackedInline): def get_formset(self, request, obj=None, **kwargs): formset = super(ApartmentInline, self).get_formset(request, obj=None, **kwargs) #Here i'd like to see the values of inline fields, for example size or building that. #Similar to how one can access ModelAdmin fields with obj.location within get_form formset.form.base_fields["type"].widget = SelectMultiple(choices=custom_choices) return formset I'd like to be able to get the current apartments instance and field values when editing the object (for example size), so that I can create custom choices (querying other DB's or API's) for another field (type). -
not able to execute urls.py in pycharm
enter image description here NOT ABLE TO EXECUTE "URLS" FILE IN PYCHARM. EVEN IF I CREATE NEW FILE NAMED URLS THAT ALSO WONT WORK. TRIED EVERYTHING TO MAKE THIS WORK BUT NOTHING WORKED. PLEASE HELP HOW TO SOLVE THIS PROBLEM. -
database not updated by a task running in celery beat
Hello I have a celery task that is suppose to run every 1 hour to fetch a key and it runs and even acts like it has updates the database but it does not update in reality @app.task def refresh_token(): r = requests.get(AUTH_URL, auth=HTTPBasicAuth(CONSUMER_KEY, CONSUMER_SECRET)) obj = json.loads(r.text) obj['expires_in'] = int(obj['expires_in']) try: mpesa_token = MpesaAccessToken.objects.get(id=1) mpesa_token.access_token = obj['access_token'] mpesa_token.save() print(obj) print(mpesa_token.access_token) print("saved") except: print(obj) mpesa_token = MpesaAccessToken.objects.create(**obj) return 1 the last thee prints all shows in the logs but checking the admin panel, the values are not updated however when I use a view and make a request then call the function, the database get updated, could anyone know what is going on