Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inlineformset / Ajax: ['ManagementForm data is missing or has been tampered with']
I try to implement an ajax request to populate select option but failed with a internal server error 500 and the message ['ManagementForm data is missing or has been tampered with'] utilisateurprojet_edit.html contain the inlineformset and each formset contain 2 select fields. I want to popupale field 2 based on field 1 selected value. I already do this in 'classic' template (without inlineformset) I do have a ManagementForm in the template 'utilisateurprojet_edit.html' that trigger the ajax request but the template 'access.html' that is called by ajax is empty for the moment (will receive select options) without the ajax call, I have no problem utilisateurprojet_edit.html (inlineformset nested) ... <form id="utilisateureditform" method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <a style="margin-right: 40px" data-target="" class="" href="{% url 'project:edit_utilisateur' %}">Nouvel utilisateur</a> <br> <br><div class="dropdown-divider"></div><br> <h2>Applications</h2><br><br> <!-- {{ application|crispy }} --> <!-- curieusement si j'enlève cette ligne le style crispy disparait --> {{ application.management_form|crispy }} {% if application.non_form_errors %} <div id="non_form_errors" class="alert alert-block alert-danger" > {% for error in application.non_form_errors %} <ul> <li>{{ error|escape }}</li> </ul> {% endfor %} </div> {% endif %} <div class="row"> <div class="col-6"><p>Nom de l'application</p></div> <div class="col-5"><p>Droits</p></div> <div class="col-1"><p></p></div> </div> {% for application_form in application %} <div class="row link-formset"> {% if … -
Django template jinja for loop
Can someone suggest me how to iterate a dictionary in django template? dic1={5: ['jaw replacement - 23-Jun-2020 (16:20:09.164240)', 'jaw replacement done - 23-Jun-2020 (16:20:51.158085)', 'jaw replacement done,almost done - 23-Jun-2020 (16:25:40.066955)', 'jaw replacement done,almost done 1 - 23-Jun-2020 (16:27:00.355605)', 'jaw replacement done,almost done 2 - 23-Jun-2020 (16:31:35.111660)']} this is the context i am passing i need something like this in template for i in dic1: print(i) list1=dic1[i] for k in list1: print(k) {% for i in notes %} {% with list1=dic1[i] %} {{list1}} {% endwith %} {% endfor %} This is not working. -
Is str.split() vulnerable to denial of service attacks?
I have a base64 uri that I want to capture and process from a POST request: def post(self, request, *args, **kwargs): image_data = request.POST.get('signature_base64', None) imgformat, imgstr = image_data.split(';base64,') However, my code linter (SonarCloud) flags this as potentially exposed as a DoS attack. Regular expressions can have an exponential execution time depending on the pattern and the length of the input string. The example below, for instance, can lead to a denial of service of the application: Pattern: /(a+)+b/ Input string: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacb It is recommended: to fix the hard-coded regex patterns that use CPU intensive features (avoid if possible captures, nested quantifiers and back-references, for instance replace the above pattern with (/a+b/)). when the regex pattern is defined with an user-controlled input, this last should be sanitized in order to escape characters which are part of the regular expression syntax. I am unsure how I would go about preventing this. Is the linter correct? What would be best practice in this case? -
Incresing session variable value in django
I'm creating a token everytime user access webpage, And the Token End have a 3 digit counter,Each time user refresh the page the counter should increment ,But i Can't Figure it out.How to initialize the session variable for the first time and increment in the rest of session. Views.py def home(request): request.session['num'] = 1 request.session['num'] += 1 res = ''.join(random.choices(string.ascii_uppercase + string.digits,k=10 )) res1 = ''.join(res+str(request.session['num'] ).zfill(3)) request.session['tk'] = res1 return render(request,'home.html',{'res':res1}) home.html {% block content %} <h1>Token Generation </h1> <form action="{% url 'send' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="exampleInputPassword1">Token : </label> <label for="exampleInputPassword1" name="res12">{{res}}</label> </div> <button type="submit" class="btn btn-primary">Send</button> </form> {% endblock content %} Can anybody Help me. -
Social-auth-django with custom uer model use OneToOneField link to auth.User
I have a customer model extends django auth.User like: class CustomerUser(models.Model): user = models.OneToOneField(User, related_name='customeruser', on_delete=models.CASCADE) secondary_email = models.EmailField(blank=True, unique=True, null=True) created_time = models.DateTimeField( auto_now_add=True, db_index=True ) In my setting.py: SOCIAL_AUTH_USER_MODEL = 'account.models.CustomerUser' and err msg look like: ValueError: Invalid model reference 'account.models.CustomerUser'. String model references must be of the form 'app_label.ModelName'. What should I do that I can craete a customeruser and make it references to auth.User? -
Auto increment with Trigger in oracle 11g : ORA-00900: invalid SQL statement [Script position: 363 - 367] END
I wanna create a Table with auto increment the id in oracle 11g in dbvisualizer, I know that in oracle 12c Identity is there for this but in 11g I followed the below scenario and facing issue. CREATE TABLE sample ( id NUMBER NOT NULL, price number ); ALTER TABLE sample ADD ( CONSTRAINT sample_pk PRIMARY KEY (id) ); CREATE SEQUENCE sample_sequence START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE; But when I execute this below trigger getting the following error. CREATE OR REPLACE TRIGGER sample_on_insert BEFORE INSERT ON sample FOR EACH ROW BEGIN select sample.nextval into :new.id from dual; END; Error: 20:16:19 SUCCESS [CREATE - 0 rows, 0.339 secs] OK. No rows were affected CREATE OR REPLACE TRIGGER sample_on_insert BEFORE INSERT ON sample FOR EACH ROW BEGIN select sample.nextval into :new.id from dual; 20:16:19 FAILED [END - 0 rows, 0.830 secs] [Code: 900, SQL State: 42000] ORA-00900: invalid SQL statement [Script position: 363 - 367] END; 20:16:20 END Execution 2 statement(s) executed, 0 row(s) affected, exec/fetch time: 1.169/0.000 secs [1 successful, 1 errors] And When I execute only below content in trigger: select sample.nextval into :new.id from dual; Error: 20:31:07 FAILED [SELECT - 0 rows, 0.956 secs] [Code: 1008, … -
How to prevent database to search for old objects?
I have a Django app which uses Postgresql as the database. I store some objects that have a datetime field. In my queries I usually want to fetch the objects that are stored in last day or last week, so older objects are of no importance for me. I cannot delete the older objects because I sometimes want to fetch all the data. I want to optimize the app. Is there any way to just search the data stored in the last day and not search for the other data? -
Reverse for 'process_data' with arguments '('11.5.1.18900-95',)' not found
I am new to Django and hence not able to figure out what is going wrong. I am trying to direct the option selected from the dropdown in the index.html along with the value to the process_data method in the views.py. But now I am getting the following error when I am trying to load my index.html page: NoReverseMatch at /index/ Reverse for 'process_data' with arguments '('11.5.1.18900-95',)' not found. 1 pattern(s) tried: ['process_data\/$'] The contents of the index.html file is as follows: <html lang="en"> <head> <meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"> <title>Home</title> </head> <body> <center> <h3>Index page</h3> <table align='center'> <tr><td>Select the version to compare with</td><td> <select name="version" id="version" onchange="location = this.value;"> <option>Select version to compare with</option> {%for ver in version_list%} <option value={{ver}} href="{% url 'process_data' ver %}">{{ver}}</option> {% endfor %} </select> </td></tr> <tr><td>The current version</td><td>{{version}}</td> </tr> </table> <br><br><br> </body> </html> My view file contents are as follows: def index(request): #query_results = QRC_DB.objects.all() global percentage_variation percentage_variation = 0 global version version = None context = RequestContext(request) response_context = get_result(request) #print("The response_context values = \n %s" %response_context.get("get_result")) cursor = connection.cursor() cursor.execute("select version from fusioncharts_qrc_db group by version") rows = cursor.fetchall() #print("The fetched rows =\n") #print(rows) version_list = [] #print(version_list) for ver in rows: version … -
__init__() got an unexpected keyword argument 'user_id' in django
i have a form for update view like this: class editpost(forms.ModelForm): class Meta: model = Posts fields = ['body'] and a view like this: @login_required def post_edit(request, user_id, post_id): if request.user.id == user_id: post = get_object_or_404(Post, pk=post_id) if request.method == 'POST': form = editpost(request.POST, instance=post) if form.is_valid(): ep = form.save(commit=False) ep.slug = slugify(form.cleaned_data['body'][:30]) ep.save() messages.success(request, 'your post edited successfully', 'success') return redirect('account:dashboard', user_id) else: form = EditPostForm(instance=post) return render(request, 'editpost.html', {'form':form}) else: return redirect('Posts:index') and url.py like this: from django.urls import path from . import views app_name = 'Posts' urlpatterns = [ path('', views.index.as_view(),name='index'), path('<int:year>/<int:month>/<int:day>/<slug:slug>', views.detailPost,name='detail'), path('addpost/<int:user_id>', views.addpost,name='addpost'), path('delpost/<int:user_id>/<int:post_id>', views.delpost,name='delpost'), path('editpost/<int:user_id>/<int:post_id>', views.editpost,name='editpost'), ] when i open editpost url i got this error,what should i do to fix it? -
403 Forbidden CSRF cookie not set even when it is in the form
When I attempt to log in to my django website, I always get a 403 Forbidden CSRF cookie not set error. When viewed via developer tools, the CSRF token was in the form response, but there were no cookies. I have django.middleware.csrf.CsrfViewMiddleware in my middleware, and I am using the standard django.contrib.auth.views.LoginView. Here is my template: {% extends 'base/formbase.html' %} {% block title %}Login{% endblock title %} {% block menuid %}menu-login{% endblock menuid %} {% block submitname %}Login{% endblock submitname %} {% block extra %} <div class="alert alert-danger"> <a href="{% url 'password_reset' %}"> Forgot Your Password? </a> </div> <div class="alert alert-secondary"> Don't have an account? <a href="{% url 'signup' %}"> Sign Up! </a> </div> {% endblock extra %} base/formbase.html: {% extends 'base/base.html' %} {% load crispy_forms_tags %} {% block body %} <div class="row justify-content-center"> <div class="col-6"> <div class="card"> <div class="card-body"> {% block form %} <h2>{% block title %}{% endblock title %}</h2> <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">{% block submitname %}{% endblock submitname %} </button> </form> {% endblock form %} </div> {% block extra %}{% endblock extra %} </div> </div> </div> {% endblock body %} base/base.html: <!DOCTYPE html> {% load base_extra %} <html lang="en"> … -
django: Problem Relation problem with postgres
I wrote a command manage its ran but now it can not fine relation with models and save instance! this is my models: from django.db import models from django.contrib.postgres import fields as pgfields class Merge(models.Model): merge_id = models.IntegerField() issue_id = models.ForeignKey('Issue', on_delete=models.CASCADE) the_json = pgfields.JSONField(default='SOME STRING') class Issue(models.Model): issue_id = models.IntegerField(primary_key=True) this is my code : from django.core.management.base import BaseCommand import gitlab import json from call.models import Merge class Command(BaseCommand): help = 'Getting issue and merge request' def handle(self, *args, **kwargs): project = gitlab.Gitlab( 'https://git.teamapp.ir', private_token='k_swy9NFpB7RWRxQRKDp' ) issues = project.issues.list(state='opened') merges = project.mergerequests.list(state='opened') issueIds = [] mergeIds = [] for issue in issues: issueIds.append(issue.id) for merge in merges: mergeIds.append(merge.id) json_dic = { "issues": issueIds, "merges": mergeIds } data = json.dumps(json_dic) Merge.objects.create(the_json=data) a = Merge.objects.all() for merge in a: print(merge.the_json) this is Error : System check identified some issues: WARNINGS: call.Merge.the_json: (postgres.E003) JSONField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `dict` instead of `{}`. Traceback (most recent call last): File "/home/amir/PycharmProjects/gitlabP/virtualenvironment/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "issue_id_id" of relation "call_merge" does not exist LINE 1: INSERT INTO "call_merge" ("merge_id", … -
User role based view in django CBV
I am using django class based view for my web application. I using django auth class for user sign up and login. In my app, users can be off more than 3 types. Every type of user will have more or less different privilege in the type. I dont know how can I manage different type of users. So I need advice how can I implement this. -
Select auto-completion data using keyboard down-arrow key-Django
I am newbie in python-Django want to select auto-completion data using keyboard down-arrow key on (already done by AJAX call) text-box field.Kindly have a look on my code on Django app. **html** <input placeholder="Select Your Party" id="party" required type="text"> <script> $(function() { $("#party").autocomplete({ source: function (request, response) { $.ajax({ url: "/purchase/SuggestPartysel/?ps="+request.term, dataType: "json", type: "get", success: function(data) { // console.log(data) response(data) } }) }, minLength: 1, }); }); </script> **urls.py** urlpatterns=[ path('',views.purchase,name='purchase'), path('SuggestPartysel/', views.load_partysel, name='load_partysel'), ] **view.py** def load_partysel(request): if request.is_ajax(): qs = request.GET.get('ps', '') parsel = Party.objects.filter(parname__istartswith=qs)[:5] results = [par.parname for par in parsel] else: results = [] return JsonResponse(results, safe=False) Kindly please help me out from this -
Add namespace or XML element prefix
I need to add the following to my WS body <ns1:Body> <ns0:ExecTR xmlns="http://www.btsincusa.com/gp/" > <ns0:REQUEST> <AGENT_TRANS_TYPE_CODE>ASDF</AGENT_TRANS_TYPE_CODE><AGENT_CD>ASD</AGENT_CD> </ns0:REQUEST> </ns0:ExecTR> </ns1:Body> suds generates the following <ns1:Body> <ns0:ExecTR> <ns0:REQUEST> <AGENT_TRANS_TYPE_CODE>ASDF</AGENT_TRANS_TYPE_CODE><AGENT_CD>ASD</AGENT_CD> </ns0:REQUEST> </ns0:ExecTR> </ns1:Body> Is there a way to add the xmlns = "" namespace? -
The current path, search_shop/5ka/, didn't match any of these. Django
I have an error: The current path, search_shop/5ka/, didn't match any of these. Reason of the problem is name of the slug field 5ka. When I changed name from 5ka to pka it works fine. How can I use 5ka without errors? models.py class Shop(models.Model): title = models.CharField(max_length=200) image = models.ImageField(blank=True) slug = models.SlugField(null=False, default="Shop") # I mean this field def get_search_url(self): return reverse('search_shop', kwargs={'slug': self.slug}) urls.py urlpatterns = [ path('', HomePageView.as_view(), name='main_list'), path('search/', SearchResultsView.as_view(), name='search_results'), path('search_shop/<slug:slug>', ProductListView.as_view(), name='search_shop'), path('search_shop_results/<slug:slug>/', ProductSearchResultsView.as_view(), name='search_shop_results'), path('<slug:slug>/<int:pk>/', views.product_detail, name='product_detail'), path('shops/', ShopListView.as_view(), name='shop_list'), ] shop_list.html {% for shop in shops %} <a href="{{ shop.get_search_url }}" -
Django static template tag keep the file red even it is working how to fix this should i download some extension
[1]: https://i.stack.imgur.com/YA89d.png [][1] [][1] [][1] [][1] [][1] -
Djongo EmbeddedField is not working for FK fields
Djongo EmbeddedField is not working for FK fields. class RegistationPractDetailsPoc(models.Model): pract_regis_body = models.CharField(max_length=10, blank=True, null=True, verbose_name=_("Registration Body")) pract_reg_no = models.CharField(max_length=50, blank=True, null=True, verbose_name=_("Registration Number")) pract_state = models.ForeignKey(State, blank=True, null=True, on_delete=models.CASCADE, verbose_name=_("State")) def __str__(self): return self.pract_reg_no class Meta: abstract = True class PractDetailsEmbedded(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("User")) registaration_details = models.EmbeddedField( model_container=RegistationPractDetailsPoc, ) tnc = models.BooleanField(default=False, verbose_name=_("Terms And Conditions")) objects = models.DjongoManager() def __str__(self): return self.user.first_name+' '+self.user.last_name class Meta: verbose_name = "Pract Details Embedded" verbose_name_plural = "Pract Details Embedde" db_table = 'PractDetailsEmbedded' when trying to save using django admin - State values are not getting saved becuase of FK. -
django inlineformset_factory add field dynamically while using CreateView
I am trying to make a dynamic form using Django inlineformset_factory. How do I make that instead of delete box I would have a button "Delete"? How do I add/remove the fields dynamically? To create a view I am using CreateView class. I am adding a picture for reference Am I using a good approach for this kind of problem? Thanks in advance, Ted The code I am using: Models.py from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.forms import inlineformset_factory class Post(models.Model): title_choices = [ ('Mr', 'Mister'), ('Ms.', 'Miss'), ] title = models.CharField(max_length=100) first_name = models.CharField(max_length=100, default = '') last_name = models.CharField(max_length=100, default = '') date_posted = models.DateTimeField(default=timezone.now) titles = models.CharField( max_length = 3, choices = title_choices, default= 'Mr', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Debt(models.Model): Money = models.ForeignKey(Post, on_delete=models.CASCADE) CurrentDebt = models.CharField(max_length=100, default = '') Period = models.CharField(max_length=100, default = '') views.py from django.shortcuts import render from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView, TemplateView ) from .models import Post, Debt from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .latex import tex from django.http import FileResponse, Http404 from django.urls import reverse from django.forms import inlineformset_factory, BaseInlineFormSet FullForm = … -
How to get uid number of all accounts in views.py with django-allauth api
I want uid numbers of all gmail accounts, in views.py I use django-allauth for gmail authentication. I know how to do it in templates {{ user.socialaccount_set.all.0.uid}} I want the equivalent one which can be used in function based view. -
Adding two parameters cause a NoReverseMatch
I have created a model for a logbook : class LogBook(models.Model): token = models.CharField(max_length=500, blank=True, null=True) class LogMessage(models.Model): logbook = models.ForeignKey( LogBook, on_delete=models.CASCADE, related_name="logmessages") message = models.CharField() My view def logmessage_delete(request, logmessage_id, log_id, token): log = get_object_or_404(LogBook, token=token, pk=log_id) logmessages = LogMessage.objects.filter(logbook=log, message=logmessage_id) logmessages.delete() Url delete/<int:logmessage_id>/<int:log_id>/<str:token> In my template I tried : {% url 'log-delete' logmessage_id log_id token %} I get a no reverse match but if I tried for example : http://localhost:8000/log/delete/15/9/1 it working just fine. Any idea ? -
I get err 500 when modifing template on django
I've a deployed Django project link here, every time i try to mod the template server give 500 error while it doesn't have any bugs. some times the error vanishes by itself and some times i should reset the template to the previous version. my back is written with python-Django and front is written with jquery, bootstrap, django-template. -
How to set urlpatterns between two app in a project in python?
I'm creating a project which has two apps for now. the url patterns of the project and two apps are: camroid/urls.py urlpatterns = [ path('', include('camroidapp.urls')), path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), ] camroidapp/urls.py urlpatterns = [ path('', views.index, name='index'), ] accounts/urls.py urlpatterns = [ path('login', views.login, name='login'), path('register',views.register, name='register'), path('logout', views.logout, name='logout') ] so when i run the server it uses 'http://127.1.1.1:8880/' and when i click on login it uses 'http://127.1.1.1:8880/accounts/login' but when i click on register from login page it calls 'http://127.1.1.1:8880/accounts/accounts/register' which is an invalid url so what can i do so that when i shift from login page to register it calls 'http://127.1.1.1:8880/accounts/register' and when i shift from register to login page it calls 'http://127.1.1.1:8880/accounts/login' -
How to index in Django Templates
Im trying to index a 2D list, whenever i do members.0 for example the positioning works just fine. However I need this to change with the loop so I made a variable but if I was to do members.counter this wouldn't do anything. Is there another way of doing this or is it not possible? <tbody> {% for item in projects %} {% with counter=forloop.counter0 %} <tr> <td>{{ item }}</td> <td>{{ members.counter }}</td> </tr> {% endwith %} {% endfor %} </tbody> -
AttributeError: 'ModelFormOptions' object has no attribute 'get_parent_list'
i want to make a field choice able , the choices are objects of another model , there is not any relations between them for example i have to models class ModelOne(models.Model): field_1 = models.CharField(max_length=20) #other field def __str__(self): return self.field_1 class ModelTwo(models.Model): one= models.CharField(max_length=20) two= models.CharField(max_length=20) #other field my forms.py class ModelTwoForm(forms.ModelForm): one = forms.ModelChoiceField(queryset=ModelOne.objects.all(),required=True) class Meta: model = ModelTwo fields = '__all__' but i get this error AttributeError: 'ModelFormOptions' object has no attribute 'get_parent_list' how to call exist objects of ModelOne to ModelTwo without any relations between the two models ?! thanks .. -
How can I call a python fuction with parameter in form using Django
I'm new to Django and I'm currently trying to get text from an input type text and set this text to a txt file. Without using Django, I created a function that works to set the text in file from parameter. Function to set the text in file I want to create an interface and to set the call this function when you click on the button submit. The form I did All of this is in the views.py file and I can access to the form. The entire file I there a simple way to do this ? Thanks for your answers!