Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Registering custom path converters globally in Django
I want to add a custom path converter to every app. The Django documentation show how to add the converter to one app: from django.urls import path, register_converter from . import converters, views register_converter(converters.FourDigitYearConverter, 'yyyy') urlpatterns = [ path('articles/2003/', views.special_case_2003), path('articles/<yyyy:year>/', views.year_archive), ... ] I've tried to add this to my "main" app. But I don't have access to this converter in my other apps without registering the converter again. How can I use the converter in any app without having to register it separately each time? -
How to fill an array with indexed values corresponding to a generic form of inputs with matrix structure?
I try to acquire the data entered by a user in a generic form with matrix structure. The view is as follows:enter image description here The resulting array of that view in position 0 must have (0, 0): u'winf 'and in position 5 (1, 0): u'winf'. But I can not make it look that way.I leave the code of the function and the html template in views.py def mtz_inter_chara(request): characteristic_list = list(Characteristic.objects.all()) characteristic_len = Characteristic.objects.count() matrix = [] for key, j in enumerate(characteristic_list): matrix.append((characteristic_list[key], [(j.id, i.id) for i in characteristic_list])) print(matrix) if request.method == 'POST': matrix_value = dict(((i, j), request.POST["{}-{}".format(i, j)]) for _, r in matrix for i, j in r) print(matrix_value) html {% extends "base.html" %} {% block title %}matriz_interdep{% endblock %} {% block content1 %} <h1 id="h1enc">Introducir los valores</h1>{% endblock %} {% block content %} <div id="dives"> <form action="" method="post">{% csrf_token %} <table id="tabes"> <br> <caption id="h1enc"> <h2>Matriz de interdependencia</h2> </caption> <tr> <th>Características</th> {% for dato in chara %} <td>{{ dato.name}}</td> {% endfor %} </tr> {% for object, row in matrix %} <tr> <td>{{object.name}}</td> {% for i,j in row%} <td> <input type="text" value="winf" name="{{i}}-{{j}}" size="10"> </td> {% endfor %} </tr> {% endfor %} <!-- {{ form.as_table }} --> … -
Get the latest value of a filed(Django Model.objects.filter())
I have models as below: class ProjectRecord(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, blank=True,related_name='user_projects') project = models.ForeignKey(Project,on_delete=models.CASCADE, null=True, blank=True, related_name='user_projects') project_type = models.CharField(max_length=30, choices=(("project_a","A"),("project_b","B")),null=True) version = models.FloatField(null=True, blank=True) I want to filter the latest value of version with this: project = list(ProjectRecord.objects.filter(user=self.request.user, project_type='project_a')) , but I don't know how to achieve it.the data in database is similar as below: id project_id version project_type 1 5 1.0 project_a 2 5 1.0 project_b 3 4 1.0 project_a 4 4 1.0 project_b 5 5 2.0 project_a 6 5 2.0 project_b 7 5 3.0 project_a 8 5 3.0 project_b For example, I want to get the latest value of project_id=5 to exact match other data and do not delete other project_id's value if their versions are not updated, the queryset should be display as below id project_id version project_type 1 4 1.0 project_a 2 4 1.0 project_b 3 5 3.0 project_a 4 5 3.0 project_b Thanks so much for any advice and assistance. -
Two Models Fields in one Form in Django 2.0?
`class Customer(models.Model): customer_id = models.AutoField( primary_key=True) customer_name = models.TextField() billing_address = models.ForeignKey(Address,on_delete=models.CASCADE,related_name='Billing') shipping_address=models.ForeignKey(Address,on_delete=models.CASCADE,related_name='Shipping')` `class Address(models.Model): address_id = models.AutoField(primary_key=True) address = models.CharField(max_length=200, blank=True) city= models.CharField(max_length=200, blank=True) ` now my problem is that i have customer model and address model, the customer have billing address and shipping address and customer have address foreign key. but the address model doesn't have customer foreign key(if address has customer foreign key i can do myself) while creating Customer, user has to enter billing address and shipping address, how can i do that? -
Django Multi value on ModelMultipleChoiceField
models.py class User(models.Model): id = models.CharField(max_length=255) name = models.CharField(max_length=255) desc = models.TextField() created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.user.name my forms.py class PostsForm(forms.ModelForm): user = forms.ModelMultipleChoiceField( queryset=User.objects.all() ) class Meta: model = Posts fields = '__all__' on my code above my form look like this +------------+ |Select + | +------------+ |John Doe | |Jessica | |Jessica | |Alex Joe | +------------+ hovewer that not what i want since possible multiple name, and i know that value come from def __str__ on my model. how to add another str so on my field will be +---------------------+ |Select + | +---------------------+ | 012931 - John Doe | | 012932 - Jessica | | 012933 - Jessica | | 012934 - Alex Joe | +---------------------+ its contain id + name on dropdown, or also other information. -
I can't show my checkbox results
I'm trying to make Club activity Registration Page. First I choose club, then page shows the list of involved students in checkbox. After I choose students and submit, I tried to show all student's list and their 'atclub'. But It only shows 'go to the home'. What's wrong with meㅠㅠㅠㅠ??? Please help me.. When I checked nothing and submit, I tried to show error message but it doesn't work. it makes error instead. How can I solve it? Please help me..!! in views.py def register(request, club_id): club = get_object_or_404(Club, pk=club_id) try: students = request.POST.getlist('students[]') except(KeyError, Student.DoesNotExist): return render(request, 'club/detail.html', { 'club':club, 'error_message':"You didn't choose any students.." }) else: for studentid in students: studentss = get_object_or_404(Student, pk=studentid) studentss.atclub = club return HttpResponseRedirect(reverse('club:results'), ) def results(request): a={'Name':'Club'} for students in Student.objects.all(): a.update({students.student:students.atclub}) return render(request, 'club/results.html', a) in results.html -- this shows just 'Go to the Home' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Results</title> </head> <body> <ul> {% for student in a %} <li>{{student.key}}--{{student.value}}</li> {% endfor %} </ul> <a href="{% url 'club:index'%}">Go to the Home</a> </body> </html> in detail.html -- for choosing students by using checkbox <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <title>Registration</title> </head> <body> <h1> {{club.club}}</h1> {% if error_message %}<p><strong>{{error_message}}</strong></p>{% … -
Django class based view giving error
I am creating a class based view to add a new record to the db. Below is how my view looks, class RecordCreateView(CreateView): fields = ['name','description'] model = models.Record success_url = reverse_lazy("index") This is how my form looks, <form action="{% url 'created' %}" method="post"> {% csrf_token %} <input type="text" id="name" name="fname" placeholder="Name"> <input type="textarea" id="description" name="fdescription" placeholder="Description"> <input type="button" class="add-row" value="Add Row"> </form> This is how my url.py file looks, urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.index,name='index'), url(r'^create/',views.RecordCreateView.as_view(),name='created'), ] Now when I go to the admin page of django(default admin GUI) and try to add a record, I am getting the below error, OperationalError at /admin/my_app/record/add/ no such table: abi_app_record Any leads here will be helpful. -
ModelSerializer: include all fields and all properties of a model
Using the following model that defines a property: class Invitation(models.Model): created = models.DateTimeField() to_email = models.EmailField() message = models.CharField(max_length=1000) @property def expiry_date(self): return self.created + datetime.timedelta(days=30) How I can specify in the model serializer that I want to include all fields and all properties? Do they have to all be listed in the fields option one by one or is there some magic way of combining '__all__' and expiry_date? -
Reactjs for django developer is good to start?
As i want to become full stack python developer is learning reactjs for front end is good idea !?.. I am aspiring data scientist..and currently learning web development with python (django ) -
Django form data access using jquery
I am working with Django forms. Django automatically renders the form for me. The template rendering code is as follows: <form method="POST" class="post-form" id="form1">{% csrf_token %} {% block content %} {{form.as_p}} <button type="button" class="btn btn-primary" id="mbutton" data-toggle="modal" data-target="#exampleModalCenter">Save</button> {% endblock %} </form> When I view my source in the browser, the following is the output: <form method="POST" class="post-form" id="form1"><input type='hidden' name='csrfmiddlewaretoken' value='iyBHA6drfJJ7s7eRmkKmsM6LyVpCGH1f7wQ65n78WkMpiQj8kuUUVlYrUFj06Nxh' /> <p><label for="id_device_type">Device type:</label> <select name="device_type" required id="id_device_type"> <option value="" selected>---------</option> <option value="Laptop-abcsderf-asdfghjkl12345-lenovo--">Laptop-abcsderf-asdfghjkl12345-lenovo--</option> <option value="Desktop-atu90667-RT56-HP--">Desktop-atu90667-RT56-HP--</option> </select></p> <button type="button" class="btn btn-primary" id="mbutton" data-toggle="modal" data-target="#exampleModalCenter">Save</button> </form> What I am trying to do is, as soon as the user clicks on Save button, a modal will pop up. Inside the modal, the contents of the form will be displayed. Will just using the form id as a jquery selector will do? or if not then how should I iterate the form fields using each() function? Requesting help at the earliest. -
Gitlab-CI: psql - Couldn't connect to server: No such file or directory
I'm new to CI in gitlab, I have an application with django-rest-framework, postgre, and postgis. When I try to setup gitlab-CI, I got the following problem Psql: Couldn't connect to server: No such file or directory The gitlab-ci.yml are the following image: python:3.5 before_script: - apt-get update - apt-get -y install binutils libproj-dev gdal-bin - apt-get -y install software-properties-common - add-apt-repository ppa:ubuntugis/ubuntugis-unstable - apt -y install postgis - apt-get -y install postgresql - systemctl start postgresql - systemctl enable postgresql test: services: - mdillon/postgis script: - psql -c "CREATE EXTENSION postgis; CREATE EXTENSION postgis_topology;" gisdata - export DATABASE_URL=postgis://$DATABASE_USERNAME:$DATABASE_PASSWORD@127.0.0.1:5432/$DATABASE_DBNAME - apt-get install -y python-dev python-pip - pip install -r requirements.txt - python manage.py test If i'm correct postgis is installed using - apt -y install postgis and the python module django.contrib.gis.db.backends.postgis is already with the django module, isn't it? Thanks for reading my question :) any help is appreciated -
'products' is not a registered namespace
I'm running into a problem. I'm getting the following error message in django: 'products' is not a registered namespace I've defined 'products' in the primary urls.py document: url(r'^products/', include('products.productsurls', namespace='products')), I've also specified the app name within producturls.py. app_name = 'websites' Can you think of any other way in which I can define the namespace? This really baffles me. Thanks! -
How can I get values in html checkbox?
I want to make a checkbox page for registering club activity students. After submitting checkbox, I want to put 'atclub' into selected student object's club(foreign key). And I want to show all students and their 'atclub' in the results.html. Plz help me!!! It makes me crazy. How can I do? If I don't choose any student, I want to print error message but It doesn't work. What's wrong?? please help meㅠㅠㅠ!!!!! This is part of models.py class Student(models.Model): student = models.CharField(max_length=30) clubs = models.ManyToManyField(Club, blank=True) class_s = models.ForeignKey(Class, on_delete=models.CASCADE) isfilled = models.BooleanField(default=False) atclub = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.student This is part of views.py def register(request, club_id): club = get_object_or_404(Club, pk=club_id) try: students = request.POST.getlist('students[]') except(KeyError, Student.DoesNotExist): return render(request, 'club/detail.html', { 'club':club, 'error_message':"학생을 선택하지 않았습니다." }) else: for studentid in students: studentss = Student.objects.filter(pk=studentid) studentst = AtClub.objects.create(students=studentss, club=club).save() studentset=[] studentset.append(studentst.id) return HttpResponseRedirect(reverse('club:results'), args=studentset,)) def results(request, string[] args): return render(request, 'club/results.html', {'studentset': studentset}) This is my detail.html <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <title>Registration</title> </head> <body> <h1> {{club.club}}</h1> {% if error_message %}<p><strong>{{error_message}}</strong></p>{% endif %} <form action="{% url 'club:register' club.id %}" method="post"> {%csrf_token%} {%for student in club.student_set.all%} <input type="checkbox" name="students[]" id="student{{ forloop.counter }}" value="{{ student.id }}"/> <label for="student{{ forloop.counter … -
How to show available slots of time in django?
I have car and time model and time is foreignkey in car model . Can anyone tell me how to show multiple available time for car ? -
How to generate feed from different models in django?
so i have two models called apartments and jobs. Its easy to display contents of both models seperately, but what i can't figure out is how to display the mix feed of both models based on date. jobs = Job.objects.all().order_by('-posted_on') apartments = Apartment.objects.all().order_by('-date') The posted date on job is represented by 'posted_by' and posted date on apartment is represented by 'date'. How can I combine both of these and sort them according to the date posted? I tried combining both of these models in a simpler way like new_feed = list(jobs) + list(apartments) This just creates the list of both of these models, but they are not arranged based on date. -
How to properly show list of forms(one type of form) using class based view in djagno 2.0
Objective Let's say I have a from named Ham and I need to display numbers of Ham forms in one view. All forms need to be submitted at once by tapping single submit button. Each form in the list also has to have different initial values. Question How do I achieve it in django 2.0 the correct way using class based views. I looked on internet but all the examples are old and could not figure out the latest way. -
Nginx+uwsgi+Django 504 Timeout and 502 Bad Gateway
I have a django interface it takes too long time for response.so I set manay params to wait response. server{ listen 8010; listen [::]:8010; location /static { root /var/www/TrafficPlatform_dev; } location / { proxy_send_timeout 600; proxy_connect_timeout 600; proxy_read_timeout 600; uwsgi_read_timeout 600; uwsgi_connect_timeout 600; uwsgi_send_timeout 600; proxy_pass http://127.0.0.1:8001; } } #nginx http http{ ... keepalive_timeout 65; types_hash_max_size 2048; client_header_timeout 800; client_body_timeout 800; send_timeout 800; fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; # server_tokens off; ... } #uwsgi.conf [program:uwsgi_dev] directory = /var/www/TrafficPlatform_dev command = uwsgi --http :8001 --module TrafficPlatform_dev.wsgi autostart = true startsecs = 5 autorestart = true startretries = 3 user = root redirect_stderr = true stdout_logfile_maxbytes = 20MB stdout_logfile_backups = 20 stdout_logfile = /var/log/supervisor/uwsgi_dev_stdout.log harakiri = 360 harakiri-verbose = true I set this params.It happened 502 Bad Gateway when more than 60s and I do not set time params,it happed 504 Timeout when more than 60s. keepalive_timeout it also can not woking. why and what i do? -
dyld: Library not loaded: @rpath/libpcre.1.dylib
I've plugged in wsgi to my Django application. I'm using macOS High Sierra - 10.13.3. Application runs fine with the below command. python manage.py runserver But when I use wsgi to start the server. It fails. uwsgi --ini uwsgi.ini uwsgi.ini [uwsgi] http-socket = :8000 chdir = /app module = app.wsgi:application master = 1 processes = 2 threads = 2 Can someone help me figure out what is wrong with the uwsgi configuration? -
Django 2.0 Operational Error: cursor "_django_curs_139683611834112_1" does not exist
the sub-header for the error is: "Error during template rendering In .../base.html error at line 0 cursor "_django_curs_139683611834112_1" does not exist Currently using Django 2.0 and Python 3.6 on a server running Ubuntu with docker. The error occurs when loading a blank URL through the stream below: urls.py: from dashboard2.account_views_new import AccountView '''urlpatterns = [ url(r'^$', AccountView.as_view(), name='home'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views: class AccountView(TemplateView): template_name = 'fv1/dash_nav.html' def get(self, request): this_form = forms.ThisForm() that_form = forms.ThatForm() forms = Form.objects.all() things = Things.objects.all() return render(request, self.template_name) def post(self, request): this = that1.objects.all() that = this1.objects.all() return render(request, self.template_name, {data}) base.html (error is thrown at line 0): <!-- update this to include headers and such in jynja --> <!DOCTYPE html> <html lang="en"> {% load static %} <head> what is producing this error? -
uWSGI - chdir(): No such file or directory [core/uwsgi.c line 2629]
I am unable to start a dockerized Django application using uWSGI. Below is the configuration being used. Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install -y swig libssl-dev dpkg-dev netcat unixodbc-dev python-dev libldap2-dev libsasl2-dev RUN mkdir /code WORKDIR /code COPY app/ /code/ RUN pip install -U pip ENV PIP_TRUSTED_HOST="pypi.python.org pypi.org files.pythonhosted.org" RUN apt-get install ca-certificates RUN pip install -Ur requirements.txt RUN chmod -R 777 /code CMD ["/code/run.sh"] run.sh #!/bin/bash ./manage.py migrate uwsgi --ini uwsgi.ini app/uwsgi.ini [uwsgi] http-socket = :8000 chdir = /opt/code/ module = app.wsgi:application master = 1 processes = 2 threads = 2 Error when starting the container Operations to perform: Apply all migrations: admin, api, auth, contenttypes, sessions Running migrations: No migrations to apply. [uWSGI] getting INI configuration from uwsgi.ini *** Starting uWSGI 2.0.17 (64bit) on [Wed May 30 05:35:23 2018] *** compiled with version: 6.3.0 20170516 on 30 May 2018 05:34:47 os: Linux-4.9.12-moby #1 SMP Tue Feb 28 12:11:36 UTC 2017 nodename: 0a9f49a479c7 machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 6 current working directory: /code detected binary path: /usr/local/bin/uwsgi uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! … -
Add CSS to Pdfkit in Django?
I am not able to add my css to my PdfKit code. The normal Static links in the HTML do not work. <link href="{% static 'css/print.css' %}" rel="stylesheet"> I see this approach in the View but can not find a way to link the css file in Django. css = 'print.css' pdfkit.from_file('file.html', css=css) Also found this answer for Flask - how to do the same for Django? How to link stylesheet files to pdfkit in Flask application? Thanks. -
Use MultipleChoiceField for Integerfield in form
Situation I have a model class with integer field(= scored_place_number). I want uses to choose either 1, 2 or 3 for the field that I set the form field as forms.MultipleChoiceField # set it to IntegerField in a form. Problem The form is displayed fine but when the form is submitted by tapping a submit button, django displays error. Enter a list of values It won's show when I did't specify forms.MultipleChoiceField so I'm guessing something is wrong with combining integer field with MultipleChoiceField. Question How can I use forms.MultipleChoiceField for IntegerField of Model? Code Model class ComparisonScore(models.Model): comparison = models.ForeignKey(Comparison, on_delete=models.CASCADE, null=True) first_place = models.ForeignKey(Place, related_name="scored_place", on_delete=models.CASCADE, null=True) second_place = models.ForeignKey(Place, related_name="unscored_place", on_delete=models.CASCADE, null=True) scored_place_number = models.IntegerField(null=True) Form class ComparisonScoreForm(forms.ModelForm): class Meta: model = ComparisonScore fields = '__all__' scored_place_number = forms.MultipleChoiceField( required=True, widget=forms.RadioSelect, choices=( ('neither', 0), ('first_place', 1), ('second_place', 2) ) ) View class CreateComparisonScoreView(CreateView): model = ComparisonScore form_class = ComparisonScoreForm success_url = reverse_lazy('comparison:index') -
Tryin to connect django with mysql and keep receiving the following error. 1045 Access denied for user 'nickkreissler'@'localhost'
enter image description here django.db.utils.OperationalError: (1045, "Access denied for user 'nickkreissler'@'localhost' (using password: YES)") -
Django Allauth Main Urls redirect
I'm using Allauth for login and signup things, and i'm working to put the two forms in one page this is not the problem it works pretty well but i want to disable or redirect (better) the user to /accounts/portal when the url is /accounts/(login||signup) Views: class CustomSignupView(SignupView): # here we add some context to the already existing context def get_context_data(self, **kwargs): # we get context data from original view context = super(CustomSignupView, self).get_context_data(**kwargs) context['login_form'] = LoginForm() # add form to context return context urls: url(r'^accounts/portal', CustomSignupView.as_view(template_name="account/portal.html"), name='portal'), url(r'accounts/', include('allauth.urls')), settings: LOGIN_REDIRECT_URL = '/blog' SOCIALACCOUNT_QUERY_EMAIL = True ACCOUNT_EMAIL_REQUIRED=True ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_AUTHENTICATION_METHOD = 'username' -
How to make this in Django or where I can read about it?
I have this fragment of code in Flask: from flask import Flask, request, jsonify @app.route('/pi', methods=['POST']) def pi(): pi_data = request.json print(f'Vaule on server {pi_data}') #--> Value on server {'temp': 100, 'temp_1': 150} return jsonify(pi_data) if __name__ == '__main__': app.run(debug=True) How to make this in Django or where I can read about it?