Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GET request on input field return None in Django
I'm trying to retrieve the data from the input fields. I want to export a .xls file where data are chosen between two dates. The problem is that I am getting "None" as a value when I try to retrieve them. .html <form method="POST"> <div class="col-6"> <label class="form-control-label">Date de début</label> <input class="form-control" id="datepicker" type="text" name="date_deb"> </div> <div class="col-6"> <label class="form-control-label">Date de fin</label> <input class="form-control" id="datepicker-2" type="text" name="date_fin"> </div> <a type="submit" class="btn btn-primary" href="{% url 'export_users_xls' %}">Exporter sous le format excel</a> </form> views.py def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="contrats.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Contrats') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Référence', 'Date de régularisation', "Type d'apporteur", 'Frais de chargement', "Type d'encours", 'Montant Euros', 'Montant UC', 'Montant Prudente'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() date_deb = request.POST.get('date_deb') date_fin = request.POST.get('date_fin') rows = models.Acte.objects.all().filter(date__range=[date_deb, date_fin]).values_list('ref', 'date', 'apporteur', 'frais', 'type_enc', 'montant_euros', 'montant_uc', 'montant_prud') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response Do you have any idea where that problem could come from? Thank you for your answers! -
'str' object has no attribute 'get' with even with return HttpResponse()
I am currently porting a flask application over to Django. I have a URL that makes a Request to this function in views.py def run_by_marker(request, test_marker): # TODO: find a perm location for the report to live within the application file_path = '/json_test_results' # only allow specific strings to be passed in by the user if test_marker not in ['smoke', 'regression']: # update as more tages are introduced to the project return 'You have entered an invalid term. Please use either smoke of regression.' # run pytest command with self contained reporting pytest_command = pytest.main(['-v', '--json-report', '-m', test_marker]) report = send_from_directory(os.environ['PWD'], '.report.json') # convert report to json report_json = json_report('.report.json') # send report json to method insert_test_data(report_json) # return test report to user return HttpResponse(report) Here is the the url: urlpatterns = [ path('run_test_by_mark/<test_marker>/', views.run_by_marker, name='run_by_marker'), When I call that URL I get the following error: AttributeError at /run_test_by_mark/x/ 'str' object has no attribute 'get' Request Method: GET Request URL: http://0.0.0.0:8969/run_test_by_mark/x/ Django Version: 2.0.7 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'get' Another user here had a similar issue, and near as I can tell have things setup correctly This is the first time I have used … -
Intercept every request in my Django app
I want to count visits on my website. My idea is to use cookies and set time out on it. If there is no request during an hour (for example) and then there is a request I will count it as a new visit. Is there a way to intercept every request in Django without repeating my code in each view function? -
Setting Decimal options globally in Django
The default rounding method for a Decimal in Python is ROUND_HALF_EVEN. I have a Django 2.0 app that needs to use ROUND_HALF_UP in all model DecimalFields. I have tried all 3 answers given in this question: Global decimal rounding options in Django But none has worked. For example, using the apps.py method given in the second solution - I have confirmed that the context for Decimal has changed by calling decimal.getcontext() immediately after setting it with decimal.getcontext().rounding = decimal.ROUND_HALF_UP I can then confirm this by going into the Django shell and calling import decimal decimal.getcontext() which reports rounding=ROUND_HALF_UP However, if I again call decimal.getcontext() in the model's save method, the rounding option has reverted to ROUND_HALF_EVEN - which suggests to me that there is more than one context? I'd like to understand if it is possible to set decimal to ROUND_HALF_UP globally and if so, where I am going wrong with my code? I am running the app on the django development server currently. -
How to create two pagination in Django for the same page?
I have searching on the internet but I did not find a good answer, I would like to know if is possible to create multiple pagination with ListView, like I changed my context to return two list of different objects and then I will put each in a row and each row will have a paginatior for that list. How should I proceed to achieve this ? ListView class IndexView(TemplateView): template_name = "index.html" def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['oportunities_idea'] = Oportunity.objects.filter(goal_oportunity_idea=True) context['oportunities_project'] = Oportunity.objects.filter(goal_oportunity_project=True) return context index.html <div class="row mt15"><!--project--> <div id="home" class="tab-pane row fade in active"> <legend>Projects</legend> {% for project in oportunities_project %} <h2>{{project.title}}<h2> {% if forloop.counter|divisibleby:1 %} </li> <li> {% endif %} {% endfor %} </div> </div> <div class="row mt15"> <div id="home" class="tab-pane row fade in active"> <legend>Ideas</legend> {% for idea in oportunities_idea %} <h2>{{idea.title}}<h2> {% if forloop.counter|divisibleby:1 %} </li> <li> {% endif %} {% endfor %} </div> </div> -
What is the reason django.db.utils.Error
What is the reason for django.db.utils.Error, Tried to locate error however I cannot find correct reason. This error I got with Azure Cloud services connection with SQL service. Thanks in Advance. -
Django TypeError at /polls/1/vote/ _reverse_with_prefix() argument after * must be an iterable, not int
This is the polls app tutorial from the Django Docs. When I go to the first question http://127.0.0.1:8000/polls/1/, select an option and click 'Vote', I get the error message. error message views.py: from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: # request.POST['choice'] returns ID of the selected choice as a string selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return a HttpResponseRedirect after successfully dealing with POST data. # This prevents the data from being posted twice if a user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=question_id, )) polls/urls.py: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] polls/templates/polls/index.html: {% if latest_question_list … -
Get the Sum of all fields in a Django queryset
I'm trying to Sum fields across records in queryset. I basically want the sum of every field. I doing this as follows: field_names = MyModel._meta.get_fields() queryset = MyModel.objects.filter(some filter criteria) for fn in field_names: result = queryset.aggregate(Sum(fn.name)) actual = result[fn.name+'__sum'] This is obviously and outrageously inefficient. How do I do this efficiently? -
Django 2 How to use forign keys of one model in another model
I am new to django and I am building a cricket club management website in django. There are teams, players, grounds and match apps. In team apps. Players Model: class Players(models.Model): player_full_name = models.CharField(max_length=40) player_email = models.EmailField(unique=True) player_team = models.ManyToManyField(Teams) Teams Model: class Teams(models.Model): team_name = models.CharField(max_length=100) team_home_ground = models.ForeignKey(Grounds, on_delete=None, null=True, blank=True) Match Model: class AddMatch(models.Model): match_team_1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name='match_team1') match_team_2 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name='match_team2') match_ground = models.ForeignKey(Grounds, on_delete=None) match_date = models.DateField(default=timezone.now) Now I want to add another model AddMatchRecod to submit match record and I will make form based on that model. In AddMatchRecod I want to have a field winning_team field, a drop down list of two fields from AddMatch model match_team_1 and match_team_2 as choices. Teams table has many teams I only want to present two teams that are participating in the match. How would I get that. class MatchAddData(models.Model): team1 = ?? team2 = ?? Second question. There is a model PlayersRecords which stores players data. There are 100s of players how would I get the 11 or 12 players that are part of team1 and team2 and display separately PlayerRecord model fields in form for each player. Player Record Model: class PlayersRecords(models.Model): player_full_name … -
make array of object of online user
my code to get online users ips and agent is the following code: now result is like this it is comes from request.__class__.online_now_ips = res "ips": [ { "ip": "127.0.0.1" }, { "agent": "PostmanRuntime/7.1.5" } ] but i want get result like this? how can i do that ? thanls "ips": [ { "ip": "127.0.0.1","agent": "PostmanRuntime/7.1.5" }, { .... } ] main code (online user middleware): def process_request(self, request): # Check the IP address x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') the_agent = request.META['HTTP_USER_AGENT'] if x_forwarded_for: user_ip = x_forwarded_for.split(',')[0] else: user_ip = request.META.get('REMOTE_ADDR') # Get the list of the latest online users online = cache.get('online_now') online_age = cache.get('online_now_agent') res = [] # Check the active IP addresses if online: online = [ip for ip in online if cache.get(ip)] for ip in online: if cache.get(ip): res.append({"ip": user_ip}) else: online = [] if online_age: online_age = [ip for ip in online_age if cache.get(ip)] for ip in online_age: if cache.get(ip): res.append({"agent":the_agent}) else: online_age = [] # Add the new IP to cache cache.set(user_ip, user_ip, 600) cache.set(the_agent, the_agent, 600) # Add the new IP to list if doesn't exist if user_ip not in online: online.append(user_ip) if the_agent not in online_age: online_age.append(the_agent) # Set the new online list cache.set('online_now', … -
Django. Choosing a specific field - relation one-to-many
I have two table and want to releated these with one-to-many. One unity - many stat. I try to select field but it not working. Always my ForeignKey is Unit.name. I want to use Unit.id as ForeignKey !! I thought that the Unit.id can't be so for tests I tried another field Unit.name2, it also doesn't work. https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.to_field class Unit(models.Model) : id = models.AutoField(primary_key=True) name = models.CharField( max_length=20, unique=True) name2 = models.CharField( max_length=20, unique=True) rase = models.CharField( max_length=10 ) class Stat(models.Model) : id = models.AutoField(primary_key=True) unit_id = models.ForeignKey( Unit, to_field='name2', on_delete=models.CASCADE, verbose_name='unit_id',) attack_type = models.CharField( 'attack_type', max_length=10 ) attack_speed = models.DecimalField( 'attack_speed', max_digits=5, decimal_places=4 ) attack_number = models.IntegerField( 'attack_number' ) Additional question. If I left Unit.name as ForeignKey what happen when i change a Unit.name in the future? If name value will change in all related tables? That's why I want to use Unit.id as a ForeignKey because Unit.id will not change but the Unit.name can. -
Django admin filter - change list_display
Is it possible to dynamically change list_display based on filter applied in django admin? Let's say I have a model Sportsman class Sportsman(Model): name = ... height = ... weight = ... Now I want to create a filter which can filter sportsmen based on their null values. So I click on height_null option and I see only sportsmen with height = Null. I want to modify list_display based on this filter so if I filtered sportsmen with null height, I want to modify list_display = ['id','name','height'] so there will be no weight visible. -
imported UserFilter as urls.py in django
codes is : https://i.stack.imgur.com/MuRLU.png error is : https://i.stack.imgur.com/bfFsQ.png codes in filters : https://i.stack.imgur.com/sghIb.png -
How does interacting with the django rest api through the url work?
I get that the Django rest framework is for interacting with the Django server programmatically but one thing I still don't understand is how.what i want to do is have my client app (mobile app) send data (somehow) to the Django server in order to create/retrieve data based on variables and obviously this has to be done through the URL since there will be no direct GUI interaction with the API. (unless I'm mistaken, which I probably am) I have gone through the official documentation and followed the tutorial to the end and still don't understand how this is supposed to work.all I ask for is a quick and simple explanation because I have searched everywhere and haven't found a simple enough explanation to grasp the core concept of how this is all supposed to work. -
django filter from grouped list
I have a grouped lists where I am trying to write a query filter. Grouped list: (listname: group) [({'swtype': 1}, ['201', '203', '205']), ({'swtype': 2}, ['207', '208'])] I am trying to access 201,203,205 from the first group one by one.How can I do that ? f_list = FP.objects.filter(pk__in= group[0]) I am trying the above code without success.Should I loop over ? -
Is there a way to easily pass a JSON object to Django context for Chart.js?
I want to use Chart.js as the plotting tool and write a Django view that will run an ORM query, get some data, turn it into JSON, and then pass the JSON data to the Django context. I am hoping to do this as simply as possible. I was able to do something like this with Highcharts-django but it is prohibitively expensive. This is roughly what I'd like to do: (1) Get data loaded in 'get_context_data' via an ORM query in views.py and format the data into json using 'local_utils.py' method generate_chart(data) from local_utils import generate_chart class MyView(TemplateView): template_name = "template.html" def get_context_data(self, *args, **kwargs): data_source = MyModel.objects.fitler(start_date__gte=start_date).values() my_chart = generate_chart(data_source) context['my_chart'] = my_chart (2) Pass the data to the method generate_chart(data_source) and return a LineChartJSONView object (or something) from random import randint from django.views.generic import TemplateView from chartjs.views.lines import BaseLineChartView def generate_chart(data_source): class LineChartJSONView(BaseLineChartView): def get_labels(self): """Return labels for the x-axis.""" return data_source.values_list('x-data', flat=True) def get_providers(self): """Return names of datasets.""" return ['data'] def get_data(self): """Return datasets to plot on y-axis.""" return data_source.values_list('y-data', flat=True) line_chart = TemplateView.as_view(template_name='line_chart.html') line_chart_json = LineChartJSONView.as_view() return line_chart_json (3) Pass the context object my_chart to template.html <head> {{ my_chart|load_data_to:"container" }} </head> <body> {# Other stuff #} … -
How to count values across fields in Django?
MODELS class ModelA(models.Model): name = models.CharField() class ModelB(models.Model): MY_CHOICES = ( ('X', 'X'), ('Y', 'Y'), ('Z', 'Z'), ) modela = models.ForeignKey(ModelA, on_delete=models.CASCADE) txt_1 = models.CharField(choices=MY_CHOICES) txt_2 = models.CharField(choices=MY_CHOICES) Given the simplified example above, how could I count how many times each of the choices values has been recorded given that there are Two fields that need to be counted? Ideally the result would be something along the lines of: {'X': 15, 'Y': 27, 'Z': 89} I have tried the following, however in my real model, I have around 20 fields to count across and this is not giving the results I was hoping for: ModelA.objects.values('modelb__txt1', 'modelb__txt2').annotate(Count('modelb__txt1', 'modelb__txt2')) I have previously created huge dictionaries and manually sorted/counted the values, but this is now unmanageable and ugly. Thanks in advance. -
Django Nginx Docker Gunicorn cant reach
Sorry if it the answer seems obvious, but I've been bashing my head for the past couple of hours. I've been following multiple tutorials trying to dockerize my application. No matter what combination of url:port or just url I tried I can't access the pages. I have zero clue what am I doing wrong. I am assuming the following: NGINX config plain wrong. How can upstream web know what's web? I assume docker exposes it, but unsure whether this is correct. web container not exposing address and port properly? I tried multipled settings, but non work. I have the following: Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ ADD ./django.conf /etc/nginx/conf.d/default.conf #COPY ./django.conf /etc/nginx/sites-available/ #RUN ln -s /etc/nginx/sites-available/django.conf /etc/nginx/sites-enabled docker-compose.yml version: '3' services: db: image: postgres:9.6 ports: - "5432:5432" environment: - POSTGRES_USER=random_user - POSTGRES_PASSWORD=random_password redis: restart: always image: redis:4.0 expose: - "6379" nginx: image: nginx:1.14.0 container_name: nginx01 ports: - "8000:8000" volumes: - ./code depends_on: - web web: build: . container_name: backend-api command: bash -c "python manage.py migrate && python manage.py collectstatic --noinput && gunicorn ops4_backend.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./code expose: - "8000" … -
Generating a dynamic HTML table from django template language
I am trying to generate a dynamic html table using django template language and i've not been able to do it yet. Here is some info about my Views.py and table.html Views.py Class table(TemplateView): template_name = 'table.html' def get(self, request): header = {'header':['#', 'chemblID','Preferable Name']} rows = {'rows':{ 'id':[1,2,3], 'chemblid':[534988,31290, 98765], 'prefName':['A', 'B', 'C']}} return render(request,self.template_name, header,rows) (The data is hard-coded since i am still testing. However it's supposed to change according to the user input.) table.html <table class="table"> <thead> <tr> {% for k in header %} <th>{{k}}</th> {% endfor %} </tr> </thead> <tbody> {% for r in rows %} <tr> {% for e in r %} <td>{{e.id}}</td> <td>{{e.chemblid}}</td> <td>{{e.prefName}}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> I am trying to generate something like this: -------------------------------------------------------------- | # | chemblID | Preferable Name | -------------------------------------------------------------- | 1 | 534988 | A | -------------------------------------------------------------- | 2 | 31290 | B | -------------------------------------------------------------- | 3 | 98765 | C | -------------------------------------------------------------- | ... | ... | ... | -------------------------------------------------------------- Thank you in advance for spending your time -
form action and no reverse match for default auth views in django
It's not really a problem, I would just like to understand what's going on: When I override django's default view for password reset called: password_reset_confirm.html I get an error if I attempt to explicitly define form action="" paramter. This template is called from django.contrib.auth.views with URLs django.contrib.auth.urls: urlpatterns = [ .... path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] In my template if I do: action="{% url 'password_reset_complete' %}" I get POST /accounts/reset/done/ HTTP/1.1" 405 0 from the server. If I do: url 'password_reset_confirm' I get NoReverseMatch. If I remove action tag altogether it works, but I don't exactly get what's going on. So I guess my question is how to set action tag explicitly? -
Django: query filter for group in which user is part
I am trying to filter a view related to the group to which the logged in user belongs to. Lets say we have a user who belongs to a group DOGS. I figured out how to filter for a specific that means known group name = DOGS. Models.py from django.contrib.auth.models import Group class Customer(models.Model): customerName = models.CharField(max_length=50) accountOwner = models.ForeignKey(Group, null=True, related_name='usGroup', on_delete=models.SET_NULL ) How do I do that in views.py: from django.contrib.auth.models import User, Group @login_required def home(request): myData = Customer.objects.filter("Return only data of the group to which the user belongs".) Do you have a hint? I only found solutions for filtering a specific groupname but not the property of the logged in user. Thanks in advance! -
maintain focus in django form when displaying errors
I have a home view with a form as footer to contact. Everything works fine, except that when there is some error in the form and the view redisplays everything with the corresponding errors, it doesn't keep the focus in the form (it shows the view as though you were entering for the first time, and so users can't see their form wasn't correct unless they scroll down). I had thought of sending a message with JS, but it is really ugly. I have tried with all the ways I have found to display errors ( raising them from different functions) but the problem persists. Any idea? Besides, even though I set required = False, the form keeps showing a message ("Complete this field") which I think comes from html, how can I remove it? Thank you very much! Code: <form method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.message.errors }} <label for="{{ form.message.id_for_label }}">Your message:</label> {{ form.message }} </div> <div class="fieldWrapper"> <strong>{{ form.mail.errors }}</strong> <label for="{{ form.mail.id_for_label }}">Your email address:</label> {{ form.mail }} </div> <div class="fieldWrapper"> {{ form.number.errors }} <label for="{{ form.number.id_for_label }}">CC yourself?</label> {{ form.number }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> class ContactForm(forms.Form): mail = … -
Django-Python datetime localization issue
I am getting different results on console and in database. There are UTC differences. I see the correct result on console, however when I save it, I see the wrong timestamp in database. what could be the reason for that? -
How to record all tasks information with Django and Celery?
In my Django project I'm using Celery with a RabbitMQ broker for asynchronous tasks, how can I record the information of all of my tasks (e.g. created time (task appears in queue), worker consume task time, execution time, status, ...) to monitor how Celery is doing? I know there are solutions like Flower but that seems to much for what I need, django-celery-results looks like what I want but it's missing a few information I need like task created time. Thanks! -
DRF : ConnectionError, ProtocolError, Connection aborted, RemoteDisconnected and api calls in a loop
I'm using DRF (Django REST Framework) and I've, 2 issues. I'ma working on a Vagrant VM (Windows 10). I've configured some caching functionsn and "lazy" loading. For example : ... @method_decorator(vary_on_cookie) @method_decorator(cache_page(60*60*1)) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get_queryset(self): queryset = my_object.objects.all().order_by('begin') # Set up eager loading to avoid N+1 selects queryset = self.get_serializer_class().setup_eager_loading(self,queryset) return queryset ... 1- Randomly, I've some error message, like this : -----> calling API : http://localhost:8000/my_app/highway/2 ('Environment(Config) Error ! => ', ConnectionError(ProtocolError('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)),), <class 'requests.exceptions.ConnectionError'>) With some reseach, I've found nothing to help me :(. 2- Is a bad way to run api calls in a loop ? : # check if there's a 'xxxx' if len(prpk['zone']['com']) > 0: # get the zone of the 'com'(s) for com in prpk['zone']['com']: zones_by_com = tools_cronjob.getAPI(API_URL + actions_api['zones_by_com'] + "/%s" % com['id'], headers) # time.sleep(5) print (zones_by_com) ... def getAPI(url, header): datas = [] if len(url) >0 and len(header) > 0: print ('-----> calling API : %s' % url) response = requests.get(url, headers=header) if response.status_code == 200: datas = json.loads(response.content.decode('utf-8')) else: raise NotImplementedError('<!> (getAPI) API url (%s) failed ! (%s)' % (url,response.status_code)) else: raise NotImplementedError('<!> (getAPI) API url …