Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
DJANGO: request.COOKIES['sessionid'] does not exist on Firefox browser
I'm writing a module to store comments for specific article. My model contains a column unique_session which is intended to store the commenter's browsing session id. Within my view function, I'm trying to initialize a variable bearing the value of request.COOKIES['sessionid'] which I later assign to unique_session column of the model. So far, I'm doing good with Chrome. I'm able to get it as the key exists when I inspect it, and obviously it stores to db just fine. But when I go to Firefox, the sessionid cookie does not exist and Django throws in a KeyError. Anyone have any idea what could be missing? -
A future-oriented code upgrade. Avoid exiting the function if an error occurs
I've to pass some data from incoming object, but I cannot be sure about the values that this object contains. Some(or each) of the object value may be defined or not. I'll not end the function with a lot of try: except: code. So here is my function that exports the data as csv file. And in case that one of the value of the incoming object undefined this code fails. def export_data(output, queryset, dialect=csv.excel): writer = csv.writer(output, dialect=dialect) writer.writerow(['Name', 'Email', 'Tool', 'Location', 'Box', 'Booking timestamp', 'Checkout timestamp', 'Return timestamp', 'Loan costs incl. VAT', 'Loan costs excl. VAT', 'VAT percentage', 'Feedback overall rating', 'Feedback remarks']) for event in events: row = ["{} {}".format(event.userprofile.firstname, event.userprofile.lastname), event.userprofile.user.email, event.toolitem.tool.name, event.toolitem.box.location.name, event.toolitem.box.number, event.booking_ts, event.checkout_ts, event.return_ts] if event.state in (event.RETURNED, event.PAYED): row += [event.loan_costs, (event.loan_costs / (event.vat_percentage / Decimal(100) + Decimal(1)) ).quantize(Decimal('.01')), event.vat_percentage] else: row += ['', '', ''] try: row += [event.feedback.get_overall_rating_display(), event.feedback.remarks] except: row += ['', ''] writer.writerow(row) return output This function should be more flexible and if a value does not exist, replace it with an empty string. -
filtering data from db by logged in user
I'm writing a queryset for data and result needs to be list of objects of that particular user. (logged in user) This is what I've got so far: class List(ListView): def get_queryset(self): qry = House.objects.filter(user__user_id=self.request.user).all() return qry models.py: from django.contrib.auth.models import User class House(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) ... ... I suspect that the very filtering condition is wrong because the traceback says no such field user What can I try to solve this ? -
How to create a webhook in python to store data in db?
I am unable to understand on how to create a webhook python. Can't find suitable examples too. I want to create a webhook to store the data in my db whenever the event is triggered. Also, the url for webhook has to be generated because i have to integrate it in some webiste. Just found this example but how to proceed further? from webhooks import webhook >>> from webhooks.senders import targeted >>> @webhook(sender_callable=targeted.sender) >>> def basic(url, wife, husband): >>> return {"husband": husband, "wife": wife} >>> r = basic(url="http://httpbin.org/post", husband="Danny", wife="Audrey") >>> import pprint >>> pprint.pprint(r)