Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to hide form and show successful message on button click
I have a Django template. The template contains a table with multiple rows with each row having two columns. One column consists of videos and the other consists of a feedback form with a submit button. I wish to write a feedback and then submit it. If the feedback gets saved into the database I would like to hide the form and replace it with a successful notification. My html looks as follows: <form method="POST"> {% csrf_token %} <div class="form-group purple-border shadow-textarea" id="divFeedback"> <input type="hidden" id="spotId{{ forloop.counter }}" name="spotId{{ forloop.counter }}", value="{{ spot.id }}"> <label for="feedbackTextarea{{ forloop.counter }}">Rückmeldung</label> <textarea class="form-control z-depth-1" name="feedback{{ forloop.counter }}" rows="5" placeholder="Ihre Rückmeldung!"> </textarea> </div> <input class="btn btn-primary btn-success" type="submit" value="Abschicken" name="submit{{ forloop.counter }}"> </form> The corresponding view would be: if request.method == 'POST': if request.POST.get('submit1'): # hide the divFeedback and show 'client/success.html' return render(request, 'client/success.html') else: return render(request, 'client/spotpreview_2.html', { 'tvspots': tvspots, 'token': token }) I have already tried many answers but due to my low level understanding of HTML, I cannot do anything. Would anyone be able to help me out with this issue? -
Why my Django-Rest-Framework post method do not have the fields?
In the Django-Rest-Framework API, I can not use post for testing, I don't know why there is no the post fields. My View: class WHMCSPhysicalServerIPMIManagementAPIView(APIView): serializer_class = WHMCSPhysicalServerIPMIManageSerializer permission_classes = [IsAdminUser] def post(self, request): """ :param request: action: physical_server_name: :return: """ try: physical_server_name = request.query_params.get('physical_server_name') action = request.query_params.get('action') if not physical_server_name or not action: return Response(data="invalid request data", status=HTTP_400_BAD_REQUEST) physical_server = PhysicalServer.objects.get(name=physical_server_name) msg = ipmi_management_handler({'action': action, 'physical_server_id': physical_server.id}) return Response(data=msg, status=HTTP_200_OK) except Exception as e: return_data = "fail" if e.args == () else e.args[0] return Response(data=return_data, status=HTTP_200_OK) My serializers: class WHMCSPhysicalServerIPMIManageSerializer(Serializer): physical_server_name = serializers.IntegerField(write_only=True) action = serializers.CharField(write_only=True) whmcs_user_id = serializers.IntegerField(write_only=True) My url: urlpatterns = [ url(r'^whmcs/physicalserver/ipmi_management/$', WHMCSPhysicalServerIPMIManagementAPIView.as_view(), name='whmcs-physicalserver-ipmi_management'), ] -
Adding JS function with django? Javascript functions only works from console?
I have an app made with Django as backend so i have a base.html where I inherit from ( things like the sidebars and navbars and stuff ) Whenever I try to add a JS function in a certain page it doesn't work so I add it to the index but now I have a function that only works when I run it in the console of the browser. $("#q12").click(function() { $("#q11").show(); }); and I tried $(document).ready(function() { $('#q12').click(function() { $('#q11').show(); }); }); I know that jquery is loaded as this works from the console but what's I'm missing here? -
Large File in /tmp folder with "request_body-" in title
This might be a very basic question but I have around 30GB disk space in my server running django code and every now and then my server have full disk space because of a file in /tmp directory having "request_body-" in title like this "20190823-015137-asdsadsadsadasdsa-request_body-Tpoyyyyyyy110". I checked and apache sub process is creating this file but I could not figure out how this file is getting created and what could be the reason. strace shows that apache sub process is stuck in read 5 (Pipe FIFO) -
How to work with the legacy database and integrate the django models with them?
I'am working on one of the legacy database, ran inspectdb command and got the respective models from the command. The models which are generated from django does not show-up any foreign key for the models. The db which I'am using is sqlite3. I have copied the models which was generated from inspectdb command and I tried modifying the models as per the tables in sqlite3 db. I have tried giving the 'REFERENCES' as foreign key but in migrations does not show any foreign key. I'am confused whether this REFERENCES is foreign key are not. Please help me out in identifying foreign key for the given tables and alter the models accordingly. The 4 tables which I have in sqlite3 db are test, suite_status, test_status and suites. 1.For suite_status table:- id INTEGER PRIMARY KEY, status TEXT NOT NULL, failed INTEGER NOT NULL, elapsed INTEGER NOT NULL, test_run_id INTEGER NOT NULL REFERENCES test_runs, suite_id INTEGER NOT NULL REFERENCES suites, passed INTEGER NOT NULL, CONSTRAINT unique_suite_status UNIQUE (test_run_id, suite_id For test table:- id INTEGER PRIMARY KEY, doc TEXT, xml_id TEXT NOT NULL, suite_id INTEGER NOT NULL REFERENCES suites, name TEXT NOT NULL, timeout TEXT, CONSTRAINT unique_tests UNIQUE (suite_id, name) For suites table:- id … -
Run a function the same time that django runs
I want to make a function in django that deletes accounts that dosen't have enough points.This function is call every 24 hours.Where I can write this function ? -
Django model method being called twice on production, but not on staging or local dev server
My stack: Ubuntu 18 Postgres 10 Gunicorn NGINX Django 2.1 I have a Django model method that sends an email to users if a form is submitted in a view. After deploying an update lastnight that didn't touch any of the code in the app described below, as of this morning when that form is submitted the method that sends the email is being called twice, leading to two duplicate emails being sent each time. I've started logging the tracebacks of the calls that lead to this method being called using stack_info=True and they are identical for both calls of this method (i.e. it's the method is not being called by rogue code in different places each time) a couple of hundred milliseconds apart. The logged calls are both like: File "/home/[path]/views.py", line 292, in my_view foo': _foo}) File "/home/[path]/views.py", line 231, in _process_view_helper_func thing.send_email() File "/home/[path]/models.py", line 351, in send_email stack_info=True, The confusing thing is that when I submit the form locally (Django dev server) and on my staging server (same stack and configuration as production server) the method is only called once and no duplicate emails are sent. What could be causing my Production server to be calling … -
Defined optional form field not being so optional
I looked over this topic Django: Optional model form field but didn't help solve my problem. I need the field timeout to be optional, meaning when user leaves it blank it will default to 10 This is what I've got so far: models: class MyModel(models.Model): timeout = models.IntegerField(default=10) ... ... modelform: class MyModelForm(forms.ModelForm): timeout = forms.IntegerField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Timeout (optional)'}), required=False, label='') ... ... class Meta: ... ... view: class CreateTestSuite(FormView): template_name = 'create_test_suite.html' form_class = MyModelForm success_url = '/list' context_object_name = 'user_id' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user_id'] = self.request.user.id return context def form_valid(self, form): form.save() # this is where form submission throws an error return HttpResponseRedirect(self.success_url) The traceback says NOT NULL constraint failed: timeout So where else do I need to specify that the form field is optional and defaults to 10 in the database if left blank ? -
Error 403: Forbidden You don't have permission to access / on this server with apache, mod-wsgi and django
I am new in django and apache. I want to publish my django website by apache and mod-wsgi. when I start httpd.exe, I recieve 403 forbidden error in my browser. my apache config is here LoadFile "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django/python36.dll" LoadModule wsgi_module "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIPythonHome "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django" Alias /static/ /D:/user/JarfaSys/static/ <Directory D:/user/JarfaSys/static/> AllowOverride none Require all granted </Directory> WSGIScriptAlias / /D:/user/JarfaSys/JarfaSys/wsgi.py WSGIPythonPath /D:/user/JarfaSys/ WSGIPassAuthorization On <VirtualHost 127.0.0.1:443> DocumentRoot D:/user/JarfaSys Alias /favicon.ico D:/user/JarfaSys/JarfaSys/favicon.ico Alias / /D:/user/JarfaSys/JarfaSys/wsgi.py ServerName 127.0.0.1 SSLEngine on SSLCertificateKeyFile C:/Users/zharf/TibiFiles/host.key SSLCertificateFile C:/Users/zharf/TibiFiles/host.cert SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown <Directory D:/user/JarfaSys/JarfaSys/> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> WSGIScriptAlias / /D:/user/JarfaSys/JarfaSys/wsgi.py WSGIPythonPath /D:/user/JarfaSys/ WSGIPassAuthorization On <Directory D:/user/JarfaSys/JarfaSys/> <Files wsgi.py> Require all granted </Files> </Directory> wsgi.py is : import os import sys path = "D:/Ghanbari/JarfaSys/JarfaSys" if path not in sys.path: sys.path.append(path) os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "JarfaSys.settings") #print os.getenv("DJANGO_SETTINGS_MODULE") #print os.getenv("PYTHON_EGG_CACHE") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() error log file is here [Fri Aug 23 16:29:26.827875 2019] [core:error] [pid 10784:tid 1092] (20024)The given path is misformatted or contained invalid characters: [client ::1:50025] AH00036: access to / failed (filesystem path 'C:/D:') [Fri Aug 23 16:29:26.848875 2019] [core:error] [pid 10784:tid 1092] (20024)The given path is misformatted or contained invalid characters: [client ::1:50025] AH00036: access to /favicon.ico failed (filesystem … -
How to add Dynamic URL part that contains a slash
I'm using a dynamic part in the URL in my Django project, as <str:item_code>, some times the str contains a slash / which causes an error not found. here is how my URL pattern looks like : path('find/the/item/<str:item_description>/', views.find_the_item, name="find_the_item"), is there anyway to force the url to ignore all slashes inside this ` part ? -
Django tinyMC failed to load in admin panel
I have problem with django-tinymce. This module doesnt load properly in admin panel and probably in normal form too. I used python manage.py collectstatic to collect static files. I'm running application with debug = False. I have 2 errors: Failed to load resource: the server responded with a status of 404 (Not Found) Uncaught ReferenceError: tinyMCE is not defined You can see errors in screenshoot. Settings: INSTALLED_APPS = [ 'tinymce', ... ] ... STATIC_URL = '/static/' MEDIA_URL = '/media/' ENV_PATH = os.path.abspath(os.path.dirname(__file__)) STATIC_ROOT = os.path.join(ENV_PATH, '../public/static/') MEDIA_ROOT = os.path.join(ENV_PATH, '../public/media/') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, "tiny_mce") TINYMCE_JS_URL = os.path.join(TINYMCE_JS_ROOT, "tiny_mce.js") TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats … -
Images uploaded with ImageField doesn't show
I have such problem: From django admin I'm trying to upload a cover image for my article, but image doesn't show on template, and its name is written in red in PyCharm. Here are my codes: settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' models.py: class Article(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=200) content = HTMLField() # image = models.CharField(max_length=2000) image = models.ImageField(upload_to='static/img') category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) post_date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, null=True, editable=False) def __str__(self): return self.title article.html: <div class="blog-item wide-blog-item"> <a href="/"><img src="/{{ article.image }}" class="image"/></a> <h3 class="font-reg"><a href="">{{ article.title }}</a></h3> <div class="blog-item-meta"> <span>{{ article.post_date }}</span> </div> <div class="blog-item-meta"> <span style="text-transform: capitalize;">{{ article.category }} . </span> </div> </div> -
Django Admin Dependant Combos Population
I want to populate dependent combos based on selection of parent combos. my code is as follow: class Species(models.Model): name = models.CharField(max_length=120, blank=False, null=False) description = models.TextField(max_length=300, blank=False, null=False) class SpeciesDetail(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) picture = models.ImageField(upload_to='pics') gender = models.CharField(max_length=1) health = models.CharField(max_length=120) class Pair(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) male = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='male_set') female = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='female_set') from django.contrib import admin from .models import Species, SpeciesDetail, Pair, class PairAdmin(admin.ModelAdmin): list_display = ('species', 'male', 'female',) search_fields = ('male', 'female', ) filter_horizontal = () list_filter = () ordering = ['species'] fieldsets = () -
How to provide different actions within just one form?
Here I have 3 different views for deleting,making active/inactive and featured/unfeatured for the selected articles and the views are working fine but the problem I encountered is how can I process these 3 different views within just one form and I want to keep this form within my table.Is there any solutions for this? <form action ="{% url '????' %}" method="post"> {% csrf_token %} <table> <thead> <tr> <th>SN</th> <th>Title</th> <th>Body</th> <th>Active</th> <th>Featured</th> </thead> <tbody> {% for article in articles %} <tr> <td> <input name ="articles" type="checkbox" id="article-{{article.pk}}" value="{{article.pk}}" > <label for="article-{{article.pk}}">{{ forloop.counter }}</label> </td> <td>{{article.title}}</td> .......... {% endfor %} </tbody> <button type="submit"> Delete Selected Articles </button> <button type="submit"> Enable/Disable featured for selected </button> <button type="submit"> Enable/Disable active for selected </button> </form> views.py def delete_selected_articles(request): articles = Article.objects.filter(id__in=request.POST.getlist('articles')) articles.delete() messages.success(request, '{} articles deleted.'.format(articles.count)) return redirect('view') def feature_selected_articles(request): articles = Article.objects.filter(id__in=request.POST.getlist('articles')) for article in articles: if not article.featured: article.featured = True article.save() return redirect('.view') else: article.featured = False article.save() return redirect('view') def active_deactive_selected_articles(request): articles = Article.objects.filter(id__in=request.POST.getlist('articles')) for article in articles: if not article.active: article.active = True article.save() return redirect('view') else: article.active = False article.save() return redirect('view') -
How to Access and use Token Authentication and show API result at the front end in Django-REST-Framework with Ajax/jQuery/Javascript
I had been using Django and it's powerful templates for quite some time but suddenly I had to Switch to the Front End languages and technology (completely different and new) that includes JavaScript, jQuery and AJAX. I want to access my API data at the front end using HTML,CSS,Javascript,Ajax,jQuery (whichever combination is suitable) I am able to get my data and manipulate it easily without any difficulties using jquery and Ajax by using simple $.ajax() method but the problem is that I do not have any clue about how to get the data that requires permissions? { "detail": "Authentication credentials were not provided." } What is the procedure to access this data? I am using Token Authentication provided to each user. How can I access the Token if I am not using Python and Django views at the front End? DO I have to login with every request? What is the actual Procedure? Can Someone Guide me through it? According to Documentations, I am supposed to put the token in header. but How would I get the Token from DB and access it for every user and with every request? -
How to get the list of task already send to celery?
I'm unable to get the list of the tasks (actives, scheduled ..) in Celery. With django, my web application send a task with celery each time the url is asked with : tasksend = calcul.delay() I don't want to launch this calcul if it is already in progress in celery. So, I want to list the tasks Received by Celery and not yet finished : if my 'calcul' task is already in progress, i will then be able not to ask again for calcul.delay() I already search a lot and the responses in Retrieve list of tasks in a queue in Celery are not good for my celery version. I use : - django 2.0.13 - python 3.4.2 - celery v4.3.0 with redis I already tried : def inspect(method): app = Celery('app', broker='redis://localhost:6379') inspect_result = getattr(app.control.inspect(), method)() app.close() return inspect_result and print( inspect('active') ) always return None (the same result is achieved with 'registered') I would like to be able to get the name of the task in progress and scheduled in celery, any idea ? -
How to add user in admin page after verification of an account?
I am trying to add user in admin page after verification of an account. But whenever I register, the new user adds itself in admin page, although I didn't verify email address. How to do it? views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your Account.' message = render_to_string('users/active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return render(request, 'users/confirm_email.html') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return render(request, 'users/confirmed_email.html') else: return HttpResponse('Activation link is invalid!') tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() -
How can i receive errors having status code 500 only on self hosted sentry
I have hosted sentry, now i want to receive only those errors which have status code in 5xx(500) and not in 4xx(400,404,...). I am unable to find any option to do it. Just for reference, i am using sentry to track issue in Pyramid(python) project. -
Returning JSON reponse in Django from a specific function
I just started with Django today, I'm trying to get a JSON response from a certain function I have and save it all into database This is my function code: import nmap def nm_scan(ip): nm = nmap.PortScanner() nm.scan(ip, '0-65535') for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname()), 'State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): lport = sorted(nm[host][proto].keys()) for port in lport: print('port : %s\tservice : %s' % (port, nm[host][proto][port]['product'])) I have my urls.py ready like so. urlpatterns = [ path('scan/', views.nm_scan), ] So I'm trying to understand how I would pass the parameter which would come in /scan/:ip and pass it to my function as parameter, then return the JSON data I have tried looking at some sample codes but I'm still stuck with just nonsense such as def nm_scan(request, ip): if request.method == 'POST': data = JSONParser().parse(request) # rest of the function here If someone could help me it would be great. Thanks. -
Decimal(0.19) results in very long number?
class Product(models.Model): VAT_CHOICES = [ (Decimal(0.19), Decimal(0.19)), (Decimal(0.07), Decimal(0.07)), ] vat = models.DecimalField(choices=VAT_CHOICES, max_digits=12, decimal_places=2, default=Decimal(0.19)) If have the Django model above. Parsing 0.19 to a decimal number yields a to a very long number with about 20 decimal places. What am I donig wrong, and what is the best way to avoid this? Do I always have to write e. g. round(Decimal(0.19), 2) to get the desired number? I also want the precise number 0.19. -
use csrf_token in javascript created element forom
Well i have created form element using javascript. The reason is, i am updating user page using ajax. I have the created form element bellow var tagform =document.createElemenet('form') var tagbutton =document.createElemenet('button') tagform.setAttribute('method','post'); tagform.setAttribute('action','/businesshub/comment_delete/'); tagbutton.setAttribute('type','submit'); tagform.appendChild(tagbutton ); The only problem i face when submitting the created form is, i get the error Forbidden (403) CSRF verification failed. Request aborted. I am using django . How can i implemented {% csrf_token %} to my created Element form using javascript. Thanks -
When I update record is throwing an end row in Django
I am getting an error when I try to update a record in Django using a form. I get an error that a record is updating but drop the end rows. How to fix this problem ? from django.shortcuts import render,redirect,get_object_or_404 from Table_definition.forms import TableDefinitionsForms from Table_definition.models import sysTables def update_table(request,id): proccess_type = "update" table_data = get_object_or_404(sysTables, id = id) table_form = TableDefinitionsForms(request.POST or None, request.FILES or None, instance = table_data) if table_form.is_valid(): table_form.save() return redirect("Table_definition:table") context = { "table_form":table_form, "proccess_type":proccess_type } return render(request, 'tableCreate.html', context) -
When a QuerySet call annotate after union, it will raise error, why, how can I solve it?
When call annotate after union will raise error. I don't know, it seems strange.The follow is example code, I think the error will raise when you try on any models. cards = card10.union(SCPSimcard.objects.all()) from django.db.models import F c = cards.annotate(n=F('id')) print(c) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\hasee\Envs\tb_simcard\lib\site-packages\django\db\models\query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\hasee\Envs\tb_simcard\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "C:\Users\hasee\Envs\tb_simcard\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\hasee\Envs\tb_simcard\lib\site-packages\django\db\models\query.py", line 78, in __iter__ setattr(obj, attr_name, row[col_pos]) IndexError: list index out of range -
Design flat url in django rest framework
I have a list view in which I have a url in which by clicking on it, it directs me to detail view. I want this url to be a flat urls in this manner 127.0.0.1:8000/?id=4 and id is the id of the object how could I do that? I wondered I could do by having a serializer.SerializerMethodField and implement a get_url function. Is there a better approach? -
Average of date difference of datetime field (timezone) and date field in python django
I want to get the average of date difference of datetime field (timezone) and date field in python django This is the code I have is object.aggregate(average_difference=Avg(F('completed_date') - F('assigned_at'), output_field=models.DateTimeField()))['average_difference'] the issue is completed date is date field and assigned_at is a datetime field date time field value is 2019-08-22 03:26:40 and date field value is 2019-08-21, so the output is wrong