Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make hvad to "autodetect" and use correct language like in modeltranslation?
I have a legacy project in django that uses hvad for translation. However I don't want to write the code that activates current language or make queries after finding out what language should I use. So, I need help to make hvad a little bit like model translation. Do someone has experience about this issue? -
Django 1.11 + SSL certificate authentication + CURL
Premise: I have a very basic notion of the technologies (python, django, curl, ssl authentication, etc.) I'm mentioning and using. All I managed to do so far is based on some reading and trial&error. And it's the first time I write in here. On my django server (without django restful framework) I defined an API that returns a json file with the list of books per library, in a given university with several departmental libraries. The API is associated to this URL: https://myuniversity/api/department-A/query/?json&preset=books If I view the API URL on a browser or via curl I can see the json file. Now let's say that to view this json I want users to be SSL authenticated, where the authentication is done SSL Authentication Backend I have implemented myself via "https://myuniversity/accounts/ssl/login". So every time one access that API it should get redirected to the ssl login URL and then back to the json. Now if I view the API URL on a browser, with a valid certificate, indeed I can see the json file. But if I curl it like this: curl -k --cert usercert.pem --key userkey.pem "https://myuniversity/api/department-A/query/?json&preset=books" I can't see the json b/c I get a "302 Found" message [1] … -
Django - Models does not call content of database
I have created a class in the models.py containing the information of articles I want to insert in a website from django.db import models from django.urls import reverse class Article(models.Model): """ Model representing an article. """ title = models.CharField(max_length=200) authors = models.CharField(max_length=200) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the article') content = models.TextField(max_length=100000) def __str__(self): """ String for representing the Model object. """ return self.title def get_absolute_url(self): """ Returns the url to access a detail record for this article. """ return reverse('article-detail', args=[str(self.id)]) After that, I have inserted an article using the admin panel of Django and saved it. Then, I have created the index.html shown below calling the articles in the database <!DOCTYPE html> <html lang="en"> <head> {% block title %}{% endblock %} </head> <body> {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %} {% block content %}<!-- default content text (typically empty) --> <!-- Articles --> <div class="articles"> <h1>Titolo: {{ article.title }}</h1> <p><strong>Autori:</strong> {{ article.authors }}</p> <p><strong>Riepilogo:</strong> {{ article.summary }}</p> <p><strong>Testo:</strong> {{ article.content }}</p> </div> {% endblock %} </body> </html> But the article is not shown despite being in the database (see prints below) -
Django ORM , Doubts regarding normalization
I have a table in which data gets written in a very fast rate (around 40000 writes per minute) class dummyclass(): field1 = models.CharField() field2 = models.IntegerField() ... field6 = models.DecimalField() There are about 6 to 8 fields in it which is constantly changing So i decided to split this class into six different classes like this class dummyclass(): field1 = models.CharField() field2 = modles.CharField() class subdummyclass(): dummy = models.ForiegnKeyField(dummyclass) field3 = models.CharField() class subdummyclass1(): dummy = models.ForiegnKeyField(dummyclass) field4 = models.CharField() class subdummyclass2(): dummy = models.ForiegnKeyField(dummyclass) field5 = models.CharField() class subdummyclass3(): dummy = models.ForiegnKeyField(dummyclass) field6 = models.CharField() is there any advantage in splitting data to different tables like this or am i overdoing this (overnormalization) . Any help is appreciated Thanks and regards -
Django Localhost Issue
I'm new on Django web framework and when I run my app with simple start setup, trying to connect localhost server http://127.0.0.1:8000/ through PyCharm. However I get this error with that output: System check identified no issues (0 silenced). You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 14, 2018 - 13:56:59 Django version 2.0.3, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 1: invalid start byte Also I tried to connect over cmd with 0.0.0.0:8000 definition and with my current ip. Even so I couldn't reach interface. Could you help or tell me how can I overcome that issue ? Any help is appreciated. -
Unable to implement print preview in javascript?
I am trying to implement the print preview on a page that opens as pdf format.However, when the page opens , the print function is not executed and nothing happens. What could I be doing wrong? I am using Python with Django and I want to implement the print function using javascript. <!DOCTYPE html> {#{% load humanize %}#} {#{% load lpo_tags %}#} {% load static %} <html> <head> <title>Admission Authorisation</title> <style type="text/css"> body{ font-size: 14px; font-family: Verdana; } h1{ font-family: Verdana; } table { border-collapse: collapse; border-spacing: 0; } table { max-width: 100%; background-color: transparent; } th { text-align: left; font-weight: 700; color: #303641; padding: 3px; } .table { width: 100%; background-color: #ffffff; margin-bottom: 15px; } tr{ padding: 2.5px; text-align: left; } .table > thead > tr > th { vertical-align: bottom; border-bottom: 2px solid #ebebeb; } .table > tbody + tbody { border-top: 2px solid #ebebeb; } .table-bordered { border: 1px solid #ebebeb; } .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11 { float: left; } .col-md-3 { width: 25%; } .col-md-2 { width: 16.66666667%; } .col-md-1 { width: 8.33333333%; } .table-point { background-color: #bdc2c9; padding-top:5px; border-bottom: 2px solid #FFFFFF; } @page { size: {{ pagesize … -
why connection.timezone is None for postgres db connection in django?
I am exploring django with postgres. I have encountered a strange thing. TIMEZONE setting for my postgres connection(I am not talking about TIME_ZONE in settings.py) is surprisingly set to None. I have set timezone to 'Asia/Kolkata' and USE_TZ is also True. As per django docs, when USE_TZ is True, the connection timezone 'UTC' by default, while it'll be equal to the value of TIME_ZONE in settings.py, when USE_TZ is False. But, for me in both the cases, the value of connection.timezone is empty. I have tried with sqlite3 backend, where I am getting expected results. I don't know, why I am not getting expected behaviour with postgres. I am using django==1.10.5 and postgres is 9.5 on 64 bit machine. I am using following command to get connection's timezone. from django.db import connection print (connection.timezone) Thanks in advance. -
How get Time picker django form (Template)
How get Time picker django form. Here is my code. Thank you My model: class activite(models.Model): jour = models.ForeignKey('jour',on_delete=models.CASCADE, related_name='jour' ) debut = models.TimeField(blank=True, null=True) fin = models.TimeField(blank=True, null=True) My form: class activiteForm(forms.ModelForm): class Meta: model = fdt_activite fields = ('jour','debut','fin') My template: <form method="POST" class="post-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="save btn btn-default">Création activité</button> </form> <script> $('#debut').datetimepicker({ showSecond: true, showMillisec: true, timeFormat: 'hh:mm:ss' }); </script> -
Django admin edit integer field
I have a model with two integer fields which are supposed to be foreign keys. In my admin view, those two fields are editable but I would like to display a search icon next to the field, so I can retrieve the id of another model and append to the field. Does django have this feature? class Linkage(models.Model): user_id = models.IntegerField(default=1) parent_id = models.IntegerField(default=0) -
readthedocs: Connecting to private gitlab instance
I have set up a local (via vagrant) readthedocs instance. I want to be able to import documentation from projects build on a privately hosted gitlab instance. I am selecting Manual Import and when clicling on Connect to Gitlab, the following Django error appears: DoesNotExist at /accounts/gitlab/login/ SocialApp matching query does not exist. Request Method: GET Request URL: http://192.168.33.10:8080/accounts/gitlab/login/?process=connect&next=%2Fdashboard%2Fimport%2F Django Version: 1.9.12 Exception Type: DoesNotExist Exception Value: SocialApp matching query does not exist. Exception Location: /home/vagrant/rtd/local/lib/python2.7/site-packages/django/db/models/query.py in get, line 387 Python Executable: /home/vagrant/rtd/bin/python Python Version: 2.7.12 Python Path: ['/home/vagrant/rtd/checkouts/readthedocs.org', '/home/vagrant/rtd/lib/python2.7', '/home/vagrant/rtd/lib/python2.7/plat-x86_64-linux-gnu', '/home/vagrant/rtd/lib/python2.7/lib-tk', '/home/vagrant/rtd/lib/python2.7/lib-old', '/home/vagrant/rtd/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/vagrant/rtd/local/lib/python2.7/site-packages', '/home/vagrant/rtd/lib/python2.7/site-packages', '/home/vagrant/rtd/checkouts/readthedocs.org', '/home/vagrant/rtd/checkouts/readthedocs.org'] Server time: Wed, 14 Mar 2018 06:17:46 -0500 Is there somewhere a documentation on how to connect a local readthedocs server to a local gitlab repo? -
"Got KeyError when attempting to get a value for field `username` on serializer `UserCreateSerializer`
I have a user register APIView. view: class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer permission_classes = [AllowAny] queryset = User.objects.all() serializer: class UserCreateSerializer(ModelSerializer): """ User register """ class Meta: model = User fields = [ 'username', 'wechat_num', 'password', ] extra_kwargs = { "password":{"write_only":True} } def create(self, validated_data): username=validated_data.pop('username') wechat_num = validated_data.pop('wechat_num') password=validated_data.pop('password') user_obj = User( username=username, wechat_num=wechat_num, ) user_obj.set_password(password) user_obj.save() group=getOrCreateGroupByName(USER_GROUP_CHOICES.User) user_obj.groups.add(group) return validated_data when I access this APIView, I will get the error: KeyError at /api/users/register/ "Got KeyError when attempting to get a value for field username on serializer UserCreateSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'username'." but the database it will create the user success. all test success: -
Exclude objects whose date time field values are greater than the current date and time
I have a class To Do and it has a dead line property. class ToDo(models.Model): ... ... dead_line = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) I would like to get all the to-do's except for the to-do's whose dead line value has crossed current date and time. I tried this way: to_do_list = user.todo_set.all().exclude(dead_line__lte=datetime.now(pytz.timezone('Asia/Kolkata'))) But, this gives me all the to-dos. Again, this works just fine and excludes the to-do's which are of current day: to_do_list = user.todo_set.all().exclude(dead_line__day=datetime.now(pytz.timezone('Asia/Kolkata')).day) What am I doing wrong? How can I get all the to-do's whose dead line is greater that current date and time? -
How to filter JSON Array in Django JSONField
i am getting crazy with filtering a (postgres) JSONField in Django 2.0.3. The json is stored as an array. E.g. tasks = [{"task":"test","level":"10"},{"task":"test 123","level":"20"}] What i've tried: myModel.objects.filter("tasks__task__contains"="test") myModel.objects.filter("tasks_task__0__contains"="test") myModel.objects.filter("tasks__0__task__contains"="test") myModel.objects.filter("tasks_task__0_x__contains"="test") myModel.objects.filter("tasks__0_x__task__contains"="test") What goes wrong? What i want to do is a icontains - but as i already read there is not support for icontains on jsonfields in Django right now... -
Making default Django login form to look good with help of CSS
I am developing an app for which I need to create Login page.I followed Mozilla Developer Network Tutorial for login page. I am using very bascic django login page and it is working fine.But the page looks very dull.I just need to make it beautiful with help of css. How can I do that in the same template itself(I just dont want to make any functional change in the operation of process) My Login Page {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <div> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </div> <div> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </div> <div> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </div> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> I tried with downloading this login template and then making necessary changes … -
Django DetailView show last if no pk in url
With a class based DetailView is there a way to say "if no pk is specified" when the url is called, just use MyModel.object.last() as object reference? url(r'^(?:(?P<pk>\d+)/)?detail/$', views.MydetailView.as_view()), class MydetailView(DetailView): model = Mymodel if self.kwargs['pk'] == False: self.object = Mymodel.object.last() I'm running Django 1.11 -
Django Rest Framework - updating a field in django
I am new to django and trying to update some data in my model using by using the PUT methed in the views.py. Here is what I've done. @api_view(['PUT']) def check_coupon(request): global kid_id, code, serializer try: code = request.POST['code'] kid_id = request.POST['kid_id'] except KeyError: x = None if request.method == 'PUT': if services.check_coupon(code) == 1: services.update_coupon(code, kid_id) # this updates the data serializer = serializers.CouponSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This creates a new coupon object instead of updating the existing one. How can I update a specific field.My input field in the body are the user id and the code. -
Vagrant port not exposed
I am using an ubuntu/xenial64 vagrant box and following the instructions indicated here to set up a readthedocs server. I am also hard coding a static private net IP in Vagrantfile: config.vm.network "private_network", ip: "192.168.33.10" However, after starting the Django server: (rtd) vagrant@ubuntu-xenial:~/rtd/checkouts/readthedocs.org$ python manage.py runserver [14/Mar/2018 05:22:40] root:120[1581]: INFO Generating grammar tables from /usr/lib/python2.7/lib2to3/Grammar.txt [14/Mar/2018 05:22:40] root:120[1581]: INFO Generating grammar tables from /usr/lib/python2.7/lib2to3/PatternGrammar.txt [14/Mar/2018 05:22:41] root:120[1585]: INFO Generating grammar tables from /usr/lib/python2.7/lib2to3/Grammar.txt [14/Mar/2018 05:22:41] root:120[1585]: INFO Generating grammar tables from /usr/lib/python2.7/lib2to3/PatternGrammar.txt Performing system checks... System check identified some issues: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DEBUG. ?: (guardian.W001) Guardian authentication backend is not hooked. You can add this in settings as eg: `AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend', 'guardian.backends.ObjectPermissionBackend')`. System check identified 2 issues (1 silenced). March 14, 2018 - 05:22:42 Django version 1.9.12, using settings 'readthedocs.settings.dev' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. I am unable to access http://192.168.33.10:8000/ Within the vagrant machine: vagrant@ubuntu-xenial:~$ netstat -ta Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 … -
why am i getting "response code (0) with no response from the server if i try to call riot api?
where as the api url i requested for is (https://matrix.org:8448/_matrix/client/r0/createRoom) -
only one form's submit button working
I have two include statements in my html- {% include "abc_bs3.html" with form=form form_title="Edit" form_btn="Save" form_id="edit" ajax="True" %} {% include "abc_bs3.html" with form=form2 form_title="Add" form_btn="Add" form_id="add" ajax="True" %} So, essentially- two forms on one page. The submit button for only one of the forms is works i.e. either 'Add' works or 'Edit' based on which is first. Not sure why this is happening. Any clues will be helpful. -
CSRF is only checked when authenticated in DRF?
I'm starting to build a django rest framework API for a react application, and we want everything, including the authentication, to be handled via API. We are using SessionAuthentication. If I have an authenticated session, then CSRF works entirely as expected (when auth'd the client should have a CSRF cookie set, and this needs to be paired with the csrfmiddlewaretoken in the POST data). However, when not authenticated, no POSTs seem to be subject to CSRF checks. Including the (basic) login APIView that has been created. This leaves the site vulnerable to login CSRF exploits. Does anyone know how to enforce CSRF checks even on unathenticated sessions? and/or how DRF seems to bypass CSRF checks for login? settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } views.py: class Login(APIView): permission_classes = (permissions.AllowAny,) @method_decorator(csrf_protect) # shouldn't be needed def post(self, request, format=None): user = authenticate( request, username=request.POST['username'], password=request.POST['password'] ) # ... perform login logic ... def get(self, request, format=None): """ Client must GET the login to obtain CSRF token """ # Force generation of CSRF token so that it's set in the client get_token(request) return Response(None) urls.py: urlpatterns = [ url(r'^login/$', views.Login.as_view(), name='login'), ] expected behaviour: login_url … -
ImportError: No module named core django framework
Screenshot of the codeI have virtual environment sample_project and in that i have project mysite App name-core When I run this cmd-./manage.py makemigrations its throwing the above error -
Django Python Requests - Parse text/plain payload
This seems like a stupid question, and probably is. Say that I'm making a request to an API as follows: r = requests.post("http://EXAMPLE.COM/api/randomstring") ## I've blocked out the real URL so false requests aren't made as it's publicly available The specification for this API is that on every request, it generates a random string of 10 letters. If the request is processed successfully, the server should respond with 201 CREATED and a text/plain payload giving the random string from the API database. I have previously tried the following to parse the request, and add it to a locally stored database model: new_word = r.text() Words.objects.create(word=new_word) But this gave the error: TypeError: 'str' object is not callable I then tried simply: Words.objects.create(word=r) When I run this from a client, and then check the local database, it only shows as: word: <Response [201]> This means that obviously the request was successful, and a word is in the text/plain payload. But how do I parse only the word from the payload, so that I am able to save it as (for example): word: hskcudyhft I know how to parse a JSON payload which is probably much trickier than this - which is probably … -
Creating a User Account While Registring
I'll like that everytime an hospital is created, A corresponding User account is created likewise, allowing the newly created account to login.... models.py class Hospital(models.Model): """ Model representing individual Hospitals """ id = models.UUIDField(primary_key=True, unique=True, db_index=True, default=uuid.uuid4, editable=False) hospital_name = models.CharField(help_text="full name of hospital", max_length=200) slug = models.SlugField(max_length=200) hospital_logo = models.ImageField(upload_to='hospital_logo',) hospital_address = models.CharField(max_length=500) hospital_email = models.EmailField(max_length=254) hospital_website = models.CharField(max_length=200) hospital_rc_number = models.PositiveSmallIntegerField() date_added = models.DateField(auto_now=True) forms.py class HospitalForm(forms.ModelForm): """ Forms for Hospital creation """ class Meta: model = Hospital fields = ('hospital_name', 'hospital_address', 'hospital_email', 'hospital_website', 'hospital_rc_number','hospital_logo') widgets = { 'hospital_name': forms.TextInput(attrs={'class': 'form-control'}), 'hospital_address': forms.TextInput(attrs={'class': 'form-control'}), 'hospital_email': forms.TextInput(attrs={'class': 'form-control'}), 'hospital_website': forms.TextInput(attrs={'class': 'form-control'}), 'hospital_rc_number': forms.TextInput(attrs={'class': 'form-control'}), } def save(self): instance = super(HospitalForm, self).save(commit=False) instance.slug = slugify(instance.hospital_name) instance.save() return instance views.py class HospitalCreate(CreateView): model = Hospital form_class = HospitalForm template_name = 'hospital/hospital_add.html' pk_url_kwarg = 'hospital_id' success_url = reverse_lazy('hospital_list') user_form = UserForm -
Django change Model's field type from CharField to JSONField
I am using Django 1.11 , I have been using CharField in Models, and dumping data in it using json.dumps(). I am using mysql database. I want to change CharField to JSONField, according to this answer. Is there any way so that I can modify my field type without loosing the data? Please note that the data in CharField is json dumped. -
Fail sending mail with Django
I tried to send email using django.core.mail and I got the error: Request Method: POST Request URL: http://localhost:8000/accounts/signup/ Django Version: 1.11.10 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /usr/lib/python2.7/socket.py in create_connection, line 557 Python Executable: /home/lucas/Documentos/projetos/advogados/venv/bin/python Python Version: 2.7.12 After that I tried to send email using just python script like this and worked fine: import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("my@email.com", "mypassword") msg = "YOUR MESSAGE!" server.sendmail("my@email.com", "to@email.com", msg) server.quit() So I created my own Email sender to use with Django: import smtplib from django.conf import settings def send_custom_mail(msg, to, subject): message = 'Subject: {}\n\n{}'.format(subject, msg) server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT) server.starttls() server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) server.sendmail(settings.EMAIL_HOST_USER, to, message) server.quit() And it is still not working and I receive the same error. So I removed the settings vars and used the real values, and it WORKS!!! I realize that the problem was related with settings vars, and I logged them and theyre type, string for host, pass and user and int for port. OK ! I don't know how to check or fix that, other vars like ALLOWED_HOSTS and SECRET_KEY are working fine I'm using decouple lib to remove sensitive data from settings