Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding conditions to <script src=..> in html using django
html: <body> <script> var participants =[]; </script> {% for player in playerList %} ........... {% empty %} <div style="text-align: center; color: Black; margin-bottom: 90%"> <h2>empty</h2> </div> {% endfor %} <script type="text/javascript" src="{% static 'event-management-system/js/index.js' %}"></script> </body> I want want to stop the execution of <script type="text/javascript" src="{% static 'event-management-system/js/index.js' %}"> part when participants =[] is empty. How to do that?. -
how to use persistance DB connection in django?
For each request, django is creating a new DB connection even after setting CONN_MAX_AGE variable in my Django DB configuration My configurations - python3.5/Django2.05/mysql-5.6 This is my DB configurations - {'default': { 'CONN_MAX_AGE': 500, 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'NAME': DB_NAME, 'OPTIONS': {}, 'PASSWORD': 'root', 'PORT': '3306', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': 'root'}} According to the doc: Django Documentation, it should not create a new connection till the CONN_MAX_AGE expires. I am checking by hitting a get request to custom view and checking connection object by adding this statement - from django.db import connections print (connections.all()) Log shows a new connection object, like this - [INFO 2018-12-04 23:00:08,472 basehttp] "GET /gsat/health_check/ HTTP/1.1" 200 96 [<django.db.backends.mysql.base.DatabaseWrapper object at 0x7f2c5fb1a0b8>] [INFO 2018-12-04 23:00:09,017 basehttp] "GET /health_check/ HTTP/1.1" 200 96 [<django.db.backends.mysql.base.DatabaseWrapper object at 0x7f2c5fa88d30>] Another observation is - By logging inside - local/lib/python3.5/site-packages/django/db/backends/mysql/base.py get_new_connection() is being called for every request, which according to me should not happen. If this interpretation of logging/debugging by object name is wrong, then suggest how should I ensure that the DB conncetion doesn't get created on each request. PS, I am new to django -
Adding choices from a file in django
I'm in with my final project and I need your help! I need to extract some data from a file and add them as choices in a django form. These are MIDI notes. I need to go through the file that contains the notes (a csv that I have created), extract them and convert them into choices for my form, so I can only choose the ones that exist, because each song has different notes. Could someone give me some notions about how to do it? Any doubt that you have, or if you need more information, do not hesitate to ask! -
Logging in django usig a custom formatter
I'm using the following logging configurations in my code. LOGGING = { 'version': 1, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'stream': sys.stdout, } }, 'formatters': { 'simple': { 'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)s- %(message)s' }, }, 'root': { 'handlers': ['console'], 'level': 'INFO' } } This is how I log. logging.config.dictConfig(LOGGING) logging.info('Hello World!') The issue is that the format string is not being respected. How can I get the formatter to work? -
How to make admin change_view with a field clickable link to object
How to make admin change_view with a field clickable link to the object of User or any other? Like: /admin/user/<id>/change Currently there only simple text with id. from django.contrib import admin from django.contrib.auth.models import User from django.db import models class Car(models.Model): owner = models.ForeignKey(User, related_name="cars", null=True, blank=True) class CarAdmin(admin.ModelAdmin): pass -
How to setup development / production build setup in Vuejs + DRF
Image of vuejs error 401 Unatuthorized access - link below Image of vuejs error 401 Unatuthorized access Software Used- DRF Vuejs while calling DRF api in Vue js (using axios) unbale to get data. below code in App.vue App.Vue -
Why is this dict not iterable in python code but iterable in a django template?
First I must admit that I'm not an expert in either python or in the django template (jinja) language so if I missed something Im sorry about that. I wrote a simple python dict to hold additional data which has the following code: all_dividend_tx_additional_info[company] = {'date': dividend.time_of_payment, 'shares': dividend.shares_owned, 'amount': dividend.amount, 'currency': dividend.currency, 'total_amount': total_amount, 'tax': tax, 'payout': payout } The company in the index for the dict will be filled out by the real company name in a for loop, but basically this is how it looks: {u'BAKKA': {u'amount': Decimal('15.00'), u'currency': u'NOK', u'date': datetime.datetime(2018, 12, 4, 16, 0, 22, tzinfo=<UTC>), u'payout': 180.0, u'shares': 12, u'tax': 55.080000000000005, u'total_amount': Decimal('180.00')}} However when I try to iterate over this like so: for key, value in all_dividend_tx_additional_info.iteritems: print key, value I get the following error: 'builtin_function_or_method' object is not iterable However, when I try to use this dictionary and send it off to a template it works nicely with the following syntax: {% for key, value in all_dividend_tx_additional_info.items %} {{ key }} - {{ value }} Can someone explain why its iterable in a django template compared to python code ? Clearly there are differences here which I have probably missed, but I … -
Left Join using 3 different tables - django
I have to show all articles from a law. Besides that, if the article is setted as marked in database (is_marked), I have to underline this article. For that, I need to do a left join, I mean, I have to show all articles, and if the article is marked I need to know that to underline it on the view. This marked must be specifc for each user. my view: def details(request, pk): law = get_object_or_404(Law, pk=pk) articles = Article.objects.filter(law=pk) context = { 'articles': articles, } template_name = 'leis/details.html' return render(request, template_name, context) My detail.html: <div class="article-post"> {% for article in articles %} {{article}} {% endfor %} </div> That's my model: class Law(models.Model): name = models.CharField('Name', max_length=100) description = models.TextField('Description', blank = True, null=True) class Article(models.Model): article = models.TextField('Artigo/Inciso') number = models.IntegerField('Number', blank=True, null=True) law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Law', related_name='articles') This class is saved with highlights made by a specif user in a specific article in a specif law: class Highlight(models.Model): law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Law', related_name='highlightArticles') article = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Artigo', related_name='highlightLaw') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='highlightUsers', related_name='highlightUsers') is_marked = models.BooleanField('Is it marked?', blank=True, default=False) description = models.TextField('Description', blank = True, null=True) How can I join the tables … -
Storing Django's FileField contents in more than one column
I'm using Django Admin as a admin panel for a service. One part of the service refers to files in AWS S3, and I'm somewhat successfully using a module called django-s3-storages and Django's own FileField. However I have another table, and a related model (not yet registered to the Admin site), which have separate columns and fields for S3 bucket and S3 key. So it seems I can't just start using FileField with the model, since it would store the S3 URL in a single text column, and my table has two columns for virtually the same purpose. Is there a way to keep using the old schema even with Admin and FileField by slicing whatever FileField is holding before saving the model? What would be the appropriate location to place my code to do the slicing? Or would the appropriate solution actually be migrating away from separate bucket and key columns by generating an S3 URL for all the old rows, to a new column that is automatically compatible with FileField? -
I needed that whenever the SAIDA_CHOICES is Sim it does not
I needed that whenever the SAIDA_CHOICES is Sim it does not do anything, but when it is Não, that gives yes it imp'lemente in the database Checkout with datatimenow however when I execute the code below being in Sim or Não it implements the chackout always SAIDA_CHOICES = ( ('Não', 'Não Pago'), ('Sim', 'Pago') ) class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=True, blank=False, null=False,) checkout = models.DateTimeField(auto_now=True, null=True, blank=True) email = models.EmailField(blank=False) placa = models.CharField(max_length=7, blank=False) modelo = models.CharField(max_length=15, blank=False) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) chk = models.CharField(max_length=15, choices=SAIDA_CHOICES) def saida(self): if self.chk == 'sim': return self.chk else: self.checkout = models.DateTimeField(auto_now=True) return self.checkout -
Django - Player URL not found depite being in urls.py
over the last few days I have been working on building a Django web application for allowing users to make queries on a MLB Statistics database. I have some of the web app working fine, however I tried to implement a search function and ran into problems with the URL mapping. I tried to move on from this and instead work on getting the database to display information based on the link to the player that they click on, but I am running into the same issue with the URL's being dynamic based on the player's player_id. This portion only uses the People model which has player_id as its primary key. Currently, I have an 'allPlayers.html' that lists every player in the database along with a link sending the player's player_id to the url as so: allPlayers.html {% extends "base_template.html" %} {% block content %} <h1>MLB Stats All Players</h1> <p>Currently, there are : {{ num_players }} players listed in the database.</p> <table style="width:100%"> <tr> <th>First Name</th> <th>Last Name</th> <th></th> </tr> {% for player in players %} <tr> <td>{{ player.name_first }}</td> <td>{{ player.name_last }}</td> <td>More on <a href="player/{{ player.player_id }}/">{{ player.name_first }} {{ player.name_last }}</a></td> </tr> {% endfor %} </table> {% … -
get a List of List object and how to handle it in html with django
index.html {% block content %} {{playerList}} {% for player in playerList %} {{player.value.indexOf(0)}} {% empty %} <tr> <td class="bg-light text-center font-italic" colspan="3">You haven't registered any players yet.</td> </tr> {% endfor %} {% endblock %} playerList is a list of lists, which is returned from views.py file. i.e playerList=[["chamo",'1'],["gir",'2'],["frt",'2']] if I want to get the "chamo" from playerList, how should I write it in html file? -
Passing stdout kwarg in subprocess.check_call method returns Apache/mod_wsgi error in python 3
I'm redirecting stdout to a file when unit testing in Django, to not display the output on the screen. I'm saving sys.stdout in a variable and make an if to call subprocess.check_call # if testing or running jenkins, redirects stdout to a temp file if 'test' in sys.argv or 'jenkins' in sys.argv or 'runserver' in sys.argv: outfile = tempfile.NamedTemporaryFile(suffix='.txt') else: outfile = sys.stdout try: subprocess.check_call(cmd, stdout=outfile) except subprocess.CalledProcessError: messages.error(request, DOWNLOAD_ERROR_MESSAGE) return HttpResponseRedirect( reverse('experiment-detail', kwargs={'slug': experiment.slug}) ) When running in localhost with Django runserver manage.py command, making outfile = sys.stdout and then, subprocess.check_call(cmd, stdout= outfile) correctly display stdout output on the screen, but somehow when Django is running upon Apache/mod_wsgi, Apache refuses to accept sys.outfile as value for stdout argument. The error presented is: Internal Server Error: /downloads/163/ Traceback (most recent call last): File "/var/lib/nep-system/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/var/lib/nep-system/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _getresponse response = self.process_exception_by_middleware(e, request) File "/var/lib/nep-system/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _geresponse response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/lib/nep-system/portal/downloads/views.py", line 180, in download_view compressed_file = remove_files(compressed_file, request, experiment) File "/var/lib/nep-system/portal/downloads/views.py", line 155, in remove_files subprocess.check_call(cmd, stdout=sys.stdout) File "/usr/lib/python3.5/subprocess.py", line 266, in check_call retcode = call(*popenargs, **kwargs) File "/usr/lib/python3.5/subprocess.py", line 247, in call with Popen(*popenargs, **kwargs) … -
django :signals is not working pre_save()
I have user app. In signals.py I have from django.db.models.signals import pre_save from user.models import User from django.dispatch import receiver import random import string @receiver(pre_save,sender=User) def create_hash_for_user(sender,instance,**kwargs): allowed_chars = ''.join((string.ascii_letters, string.digits)) unique_id = ''.join(random.choice(allowed_chars) for _ in range(32)) print("Request finished!") instance.user_hash = unique_id instance.save() In apps.py from django.apps import AppConfig class UserConfig(AppConfig): name = 'user' def ready(self): import user.signals In models.py I have extended the abstractbaseuser class User(AbstractBaseUser): But signal function is not called, and Request finished! is not printed and user_hash is not created. -
How to add custom action button in Django admin form and post the information
enter image description here I am new to Django! I am using Django Admin. How can I make a new button(near save,...) and post the information and use it in a python script(I am using Django version 2). admin.py admin.site.register(Router) admin.site.register(Peer, PeerModelAdmin) admin.site.register(Prefixe, PrefixModelAdmin) -
No env variables in bash after exported with command in docker-compose
I have a serverless.yml file, that defines environment variables. In order to use the ones for my local stage in a docker container I use the serverless dotenv plugin in order to export them to an .env file. I do this in my docker-compose.yml where I also export the variables from this file. It works as my django settings have access to them. command: > bash -c "sls dotenv -s local && export $$(grep -v '^#' .serverless/.env | xargs -d '\n') && python manage.py makemigrations ingredients" However, if I bash into the container or run a command, the environment variables are not available anymore: docker-compose exec flask-dynamodb-serverless python manage.py createsuperuser What am I missing? -
Executing a script on background while the website browsing is ongoing on Django
I am using Django and would like to background execute a long script at a certain stage while browsing the website pages. For example, for a user calculating the shortest distance and save in the database by comparing with available i.e. 5000 locations. At present, when the script execution starts then the page got frozen and couldn't allow clicking on the links or buttons. I have tried using Django Background Tasks but that needs manually executing through command. Also, looked at Celery with Redis but I found Celery could be huge for this and due to that looking for an easy way. Could you please share your advise to achieve my goal? Thank you! -
How can I build that specific SQL sentence, if I have a simple one-to-many relation
I have two tables. CUSTOMER, ITEMS. CUSTOMER has many fields name, address ..bla. ITEMS contains the bill content. (and CUSTOMER_ID as foreign key naturely).. so wich item and how many pieces saled to customers. How can I buld that SQL query wich get, all customer who bought same products with same amounts of them? If someone can reperesent that, in Django ORM filter, Extra Respect! :) -
How to add social sharing buttons in django blog
am using the django_social_share module and i cant figure out how to pass the sharing url for a particular blog post on social media here is the post_detail.html <article> <div class="embed-responsive embed-responsive-16by9"> <img src="{{post.thumb.url}}" alt="" /> </div> <div class="post-content"> <h2>{{post.title}}</h2> <div> {{post.created}} Author {{post.user}} <hr/> <p>{{post.body}}</p> <hr> <div id="subheader" class="blog"> <div class="subheader-text"> <h1>Did you like this Post ?</h1> <h4>Consider sharing Most readers like to share our Posts </h4> <a href="#" rel="shared-popover" data-popover-content="#shared-btn-Popover" title="Share" data-placement="bottom" class="mtr-btn button-circle button-fab ripple"><i class="fa fa-share-alt"></i></a> <div id="shared-btn-Popover" class="hide"> <ul class="blog-share-buttons"> <li><a href="{% post_to_twitter object.title %}" title="Twitter"><i class="fa fa-twitter"></i></a></li> <li><a href="{% post_to_facebook object.title %}" title="Facebook"><i class="fa fa-facebook"></i></a></li> <li><a href="#" title="Linkedin"><i class="fa fa-linkedin"></i></a></li> </ul> </div> </article> </div> help out please all the setting are okay -
django login via existing login credential
I am working with a django project 'appointment reservation system for student and teacher'. Here teacher can create their free appointment shcedule and student can book that appointment. Pretty simple. However, I'm stuck. I have to made the login system such that they can use their existing login credential from their school management application. So the login system would have modularity. Its should work like login via facebook, instead, it would be login via their existing login access. Looking for gudance. Thanks in advanced. -
PermissionDenied after upgrade to restframework 3.7.0
I have a django 1.11 project running with restframework 3.6.4. After upgrading the restframework to 3.7.0, I'm getting a strange exception while running one of my unit tests: Traceback (most recent call last): File "/Users/alex/.Envs/autodesk/lib/python3.5/site-packages/rest_framework/views.py", line 482, in dispatch self.initial(request, *args, **kwargs) File "/Users/alex/.Envs/autodesk/lib/python3.5/site-packages/rest_framework/views.py", line 400, in initial self.check_permissions(request) File "/Users/alex/.Envs/autodesk/lib/python3.5/site-packages/rest_framework/views.py", line 335, in check_permissions request, message=getattr(permission, 'message', None) File "/Users/alex/.Envs/autodesk/lib/python3.5/site-packages/rest_framework/views.py", line 176, in permission_denied raise exceptions.PermissionDenied(detail=message) rest_framework.exceptions.PermissionDenied: You do not have permission to perform this action. Maybe someone has an idea what the problem is or at least how can I understand where the problem is? -
NOT NULL constraint failed: portal_visitrequests.visitor_id
I am very new to django and I've been battling with this particular project for a while now. I get a not null constraint error every time I try and submit my form(which ultimately creates Visitor and VisitRequests objects). The error comes from this line of code...visit_request = VisitRequests(staff=staff, visitor=visitor, comment=comment, token=token, status=None).save()... Please view the code below. views.py def formpage(request): if request.method=='POST': token=secrets.token_urlsafe(20) visitor_name=request.POST.get('visitorsname') comment=request.POST.get('comment') visit_type=request.POST.get('visit_type') visit_content='You have a waiting visitor'+'\n'+'Name:'+visitor_name+'\n'+'Purpose Of Visit:'+visit_type+'\n'+'Additional Comment:'+comment+'\n'+token staff_id=request.POST.get('staff') staff=Staff.objects.get(id=staff_id) staff_email=staff.staff_email req_comment = request.POST.get('req_comment') request_id = (request.POST.get('request_id')) visitor=Visitor(visitor_name=visitor_name).save() visit_request = VisitRequests(staff=staff, visitor=visitor, comment=comment, token=token, status=None).save() models.py class Staff(models.Model): staff_name = models.CharField(max_length=250) staff_email = models.CharField(max_length=250, default="") def __str__(self): return self.staff_name class Visitor(models.Model): visitor_name = models.CharField(max_length=250) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return '{}'.format(self.visitor_name) class VisitRequests(models.Model): staff=models.ForeignKey(Staff, on_delete=models.CASCADE) visitor = models.ForeignKey(Visitor, on_delete=models.CASCADE) comment= models.TextField(default='') status= models.NullBooleanField() token=models.CharField(max_length=20) -
Django RawSql Annotate
I'm new to Django so I will have ask some help. I have a table with records representing Transit. When transit arrives to depot, I need to find how many Resources are that time in depot. Resource has start time and end time. What I need to do, is annotate Resources count to Transit using Transit depot arrival time. There is now any relation between models. I think I might need RawSql for this but I'm still little short of knowledge to do this. -
Django template and loop over list of elements
I would like to loop over some objects placed into a list and get statistics on each one. I'm using Django 1.11.16 User can select one or multiple publication(s) and I display some statistics over each publication in the list. I have a view part which looks like this : def get_context_data(self, **kwargs): publication_list = self.request.GET.getlist('publication_list') publication_selected = Publication.objects.filter(id__in=publication_list) download_all_period = Download.objects.values('usage', 'doc__publication__pub_id') \ .filter( doc__publication__id__in=publication_list) \ .filter( Q(creation_date__gte=start_date) & Q(creation_date__lte=end_date))\ .aggregate( nusage=Sum('usage')) request_all_period = Download.objects.values('doc__publication__pub_id')\ .filter( doc__publication__id__in=publication_list)\ .filter( Q(creation_date__gte=start_date) & Q(creation_date__lte=end_date)) all_period_list = zip(publication_selected, download_all_period, request_all_period) context_data['publication_list'] = publication_list context_data['publication_selected'] = publication_selected context_data['download_all_period'] = download_all_period context_data['request_all_period'] = request_all_period context_data['all_period_list'] = all_period_list return context_data Then I have a template, with a table. So I would like to loop over each element in my list in order to create one row per element : {% for publication_selected, download_all_period, request_all_period in all_period_list %} {% if download_all_period.nusage %} <tr> <td>{{ start_date|date:"Y/m/d" }} to {{ end_date|date:"Y/m/d" }}</td> <td>{{ publication_selected }}</td> <td><span class="badge alert-danger">{{ download_all_period.nusage }}</span> / <span class="badge alert-info">{{ request_all_period.count }}</span></td> </tr> {% else %} <tr> <td>{{ start_date|date:"d/m/Y" }} to {{ end_date|date:"d/m/Y" }}</td> <td>{{ publication_selected }}</td> <td>{% trans 'No downloads/No requests' %}</td> </tr> {% endif %} {% endfor %} It displays only the last … -
button that refresh data
I'm Brazilian then: I'm setting up a parking system for hours, and I was able to do the part of updating a record that is already saved and I configured the automatic checkin at the time of the registration and left the checkout to do with DateTimeNow. What I need is that at the time that all the registrations are listed in the table, that I click on the Checkout button and it redirects to the update of the register by passing the time by datetimenow, so when the page that it redirected is loaded, open with the schedule checkout, in order to make the payment Model.py class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=True, blank=False, null=False,) checkout = models.DateTimeField(auto_now=True, null=True, blank=True) email = models.EmailField(blank=False) placa = models.CharField(max_length=7, blank=False) modelo = models.CharField(max_length=15, blank=False) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) forms.py class MovRotativoForm(forms.ModelForm): class Meta: model = MovRotativo fields = '__all__' widgets = { 'checkin': DateTimeInput(), 'checkout': DateTimeInput(), } views.py @login_required def movrotativos_update(request, id): data = {} mov_rotativo = MovRotativo.objects.get(id=id) form = MovRotativoForm(request.POST or None, instance=mov_rotativo) data['mov_rotativo'] = mov_rotativo data['form'] = form if request.method == 'POST': if form.is_valid(): form.save() return redirect('core_lista_movrotativos') else: return render(request, 'core/update_movrotativos.html', data) table <table class="table …