Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DateField formatting problems
Problem I have one DateField letzte_ausgabe with a calculated default value from function get_letzte_ausgabe_default. I want that the field value is formatted like %m/%Y. This must be done in the code, not in the template. Properties (e. g. help_text) must not be lost (see Django input_formats removes help_text? I want only to change the way one DateField is displayed). I tried to change input_formats and widget.format in forms.py. See the comments below for what I tried. The problem is, that a new empty form displays the calculated default value, that is displayed by the template with {{ form.letzte_ausgabe.value }}, as "Dez. 1, 2018" instead of "12/2018". If I submit the form with a valid date (forcing the form not be invalid at another place), suddenly the valid date is displayed in the correct format. I need help figuring that out what's the problem. Code models.py (shortened) from datetime import date from django.contrib.auth.models import User from django.db import models from django_countries.fields import CountryField null = {"null": True, "blank": True} def get_letzte_ausgabe_default(): return date(date.today().year, 12, 1) if date.today() > date(2017, 12, 26) else date(date.today().year + 1, 12, 1) class Abonnent(models.Model): letzte_ausgabe = models.DateField(default=get_letzte_ausgabe_default(), verbose_name="Letzte Ausgabe", help_text="Eingabe im Format MM/JJJJ. Zum Beispiel: {:%m/%Y}".format(get_letzte_ausgabe_default()), … -
python + SQL db runserver ERROR
Django runserver is not work python + SQL db. If I install sudo apt-get install python-mysqldb. Make migrate is okey, tables is create but runserver ERROR Failed to get real commands on module "mysite": python process died with code 1: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/mysql/base.py", line 25, in <module> import MySQLdb as Database ImportError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ivan/pycharm-2016.3.2/helpers/pycharm/_jb_manage_tasks_provider.py", line 25, in <module> django.setup() File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) -
Django REST Swagger: Some properties missing from swagger documentation
I have the following class in my serializers.py: class RecordSerializer(ModelSerializer): class Meta: model = Record fields = ('uuid', 'code', 'name', 'group_name', 'is_active') def to_representation(self, instance): # Get the original representation ret = super(RecordSerializer, self).to_representation(instance) request = self.context.get('request', {}) if request.query_params.get('show_group_name', 0) != '1': ret.pop('group_name') if request.query_params.get('show_is_active', 0) != '1': ret.pop('is_active') return ret def get_is_active(self, instance: Record): request = self.context.get('request', {}) if request.query_params.get('show_is_active', 0) == '1': try: user = request.query_params['user'] except KeyError: msg = "Missing parameter user while requesting extra data is_active" raise ParseError(msg) try: active_state = instance.active_states.get(user_id=user) except ActiveState.DoesNotExist: msg = 'No active state for record {} and user {}'.format(instance.uuid, user) raise ParseError(msg) if active_state.is_active: return True else: return False I was expecting to see the following properties in my swagger documentation: show_group_name show_is_active user But they are not presented. Should I specify somewhere else that I need these properties in order to presented in the swagger documentation? -
Django autoreload: add watched file
When source files in my project change, django server reloads. I want to extend this also on non-python-source files. I use native SQL queries, which are stored in SQL files (eg. big_select.sql), and I want the server to reload when these files change. I use django on Windows. I have tried adding .py extension, which didn't work. -
Invalid password format or unknown Hashing Algorithm Error in Django 1.10.5
As a new comer to the django REST community I've been trying all the known and suggested ways to save password using the in built user model systems. I've been using Coding Enterpreneur's Youtube tutorial "Advancing the Blog API" as a reference. It works for them but not myself. Would love a feedback. My files are down below. views.py: User = get_user_model() class UserCreateAPIView(ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer serializers.py: User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): username = validated_data['username'] email = validated_data['email'] user_obj = User( username = username, email = email ) user_obj.set_password(make_password(validated_data['password'])) user_obj.save() return validated_data system/urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/', include('people.urls')), url(r'^api/', include('people.api.urls')) ] api/urls.py: urlpatterns = [ url(r'^register/$',views.UserCreateAPIView.as_view(),name="register"), ] -
Unable redirect page on form submission in django
I am trying to implement a document search engine in django. The main page has a text box in which the user is supposed to enter a query. On entering the query, the user will be redirected to a page that will contain the titles of document relevant to their query. However, I'm unable to redirect to a new page on query submission. My app is named search and this is the page that loads on opening http://127.0.0.1:8000/search/ index.html {% load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'search/style.css' %}" /> <title>muGoogle</title> </head> <body> <div class = "container"> <h4 class = 'mugoogle'>muGoogle</h4> <form class="form-wrapper" method = "GET" action = "{% url 'doc_scorer'%}"> <input type="text" name = 'query' class="textbox rounded" placeholder="Search docs related to..." required> <input type="submit" class="button blue" value="Submit"> </form> </div> </body> </html> urls.py file: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^search$', views.search), url(r'^index$', views.index), url(r'', views.doc_scorer, name="doc_scorer"), ] the views.py file from django.template import Context, loader from django.shortcuts import render, render_to_response from django.http import Http404, HttpResponse, HttpResponseRedirect import os from other_code import some_function def index(request): template = loader.get_template("search/index.html") return HttpResponse(template.render()) def search(request): return HttpResponse("search is under construction") def doc_scorer(request): query … -
django class based views post method not reading from other methods
I am running a classed based view on django. It's very strange that my post method does not take on other methods in the class. My get_context_data works and could take in and print self.get_msg(), however, my post method when I run it, it takes me to a page not found 404 page, because of the self.get_msg() function that I included inside the post function. I need the post function to take in some parameters so I could save it in the model. Below is my code in a view.py Does anyone know why that might be the case and how do I get around it? Any advice would be welcome. Thank you class OpeningConfirmApp(LoginRequiredMixin, FormMixin, TemplateView): template_name = 'opening/opening_confirm_app.html' form_class = PriceForm def get_msg(self, *args, **kwargs): msg_id = self.request.GET.get("msg_id") msg = get_object_or_404(Message, pk=msg_id) parent_msg_id = msg.parent_id msg = get_object_or_404(Message, pk=parent_msg_id) return msg def get_context_data(self, *args, **kwargs): context = super(OpeningConfirmApp, self).get_context_data(*args, **kwargs) #working print self.get_msg() return context def post(self, request, *args, **kwargs): #not working print self.get_msg() form = self.get_form() if form.is_valid(): price = form.cleaned_data.get("price") return self.form_valid(form) def get_success_url(self): msg = self.get_msg() messages.success(self.request, "Your application has been sent.") return reverse('MessageDetail', kwargs={'pk': msg.id}) -
How to use a model in a Python Django project for multiple applications?
I have a Django project called myoffice. In this project I created an app proposals. Before creating this I had performed makemigrations and migrate creating auth_user table and other tables like auth_user_groups etc. After creating proposals app, it was working fine. Now I created a new app called expenses. I have written all models, views, templates and url files. In my models, a couple of models have foreign key reference to users like this: exch_usr = models.ForeignKey('User', on_delete=models.PROTECT) I have imported user model as below: from django.contrib.auth.models import User Yet, I am getting an error while running makemigrations: ValueError: Cannot create form field for 'txn_usr' yet, because its related model 'User' has not been loaded yet -
E-mail address verify status
I wanna check user's e-mail verify status for displaying a warning message. If e-mail address is not verified, i will show a message top of the page. Is there any template tag for checking user's e-mail address is confirmed? -
django: iregex is case sensitive
Hitting the db (MySQL) with these two queries one right after another I get different results: test1 = Agreement.objects.filter(pk=152, company__iregex='СитиСтро(и|й)') test2 = Agreement.objects.filter(pk=152, company__iregex='ситистро(и|й)') test1 <QuerySet [<Agreement: Agreement object>]> test2 <QuerySet []> with the actual value if the field ' "СитиСтрой" ' Now i'm pretty sure that is Cyrillics that is messing things up, because with records in Latin alphabet it works fine, but I have no idea how to go around that (bug?). Any advice here? PS I did double check, there is no confusion here with similar looking C letters of English and Russian, but with different letter codes. -
Formatting query outputs in Django
I am attempting to sum a list of entries. However, I can't seem to figure out how to extract the numbers I need. Whenever I run: Entry.objects.aggregate(Sum('euros_sum')) I get: {'euros_sum__sum': Decimal('5948.48')} Which is fine if I need to add the number to my template. However, I need the number (5948.48) by itself so that I may add it to a form field. How do I format the query to only output the total without the field details(euros_sum__sum: Decimal, etc)? What am I missing here? Thanks in advance for your help! -
Error with Boto S3 file usage with Django (x-amz-security-token)
I am using AWS Boto to handle file uploads and downloads in my Django app. The server on which the application is running has an attached role to it giving full s3 access and full access to that bucket as well. When I upload a file on my app, on the frontend it comes as {http://xyz.s3.amazonaws.com/content/8d632aa1e9e821cfb5648d198d02397c99ba1a47ac8810c2a.jpeg?x-amz-security-token=FQoDYXdzEF8aDN3BTE58ol4F0GNncyK5A%2BjnaijqccanrQK5Q/3qfurJtJOB4Pdm9A0P2ni0d5DfRTTLgmZR%2B5miwzO6nseZF4QUmOiiNfM3RVZmxr9vyEdqeVcPPtDFXnpUB%2BKOLTjsFvYoX68q7lNJ1sBIK3dZJeCVOa67H4keeTU3c2gC0s61wbjuZL38Ozbs242wEJ6PEf9T4dsg%2B2095C9s/qD6wgsdsdsdsdsds9zjGIexET1UsrBTb8HoNV0LN3oWL/h53bu72zBm78ywQC/hWPmGXw5qFfJXaZVWG8QK9pSfghHV9iJcxDbCbbsGqETmRGlQL05Ap2rU1tzN2hbrabYstVKmvSCHNNY7SpmIMqeklyhpHWvP7kZXJkVYIKQ/h3%2B3Zl53Snn%2BoOjb8PnJU1WNI4sOaslTUzeSPuttCRn0qUNxea0U5b//aE%2BcbQYv3OH5syZ%2BCCf3lFPuoO47SF6/W3ib/Uz7T9OnkwSheV6VR0ePF9omvtL2S9TixM/ZkXLhTahNtryUgWjrh3YA0EbPQe4Pn/IokyVaikISpgMqqAS/e/Juq3bwdvJNlw5/2WPOeuAbovfRX82Seqnetao0Ezkb5XSjFvr/GBQ%3D%3D?w=536&h=500} I want to remove this since when I click on it the browser, it does not open the file and says access Though the file is there in S3 and I can open it in the console. Please help me. Is it that AWS Boto 2 doesn't support AWS IAM roles? When I explicitly provide AWS access and secret keys in .boto file, this works perfectly fine. I read through this but did not help and we already have CUSTOM variable set in base.py. Using django-storages and the s3boto backend: x-amz-security-token is appended which I do not want -
Django QuerySets: optimizing multiple filters evaluation
I have a function that used to return a QuerySet after filtering several times, applying different chained Q objects, to simplify: def get_filtered_data(): query_set = ... a, b, c = Q(...), ... query_set = query_set.filter(a) query_set = query_set.filter(b) query_set = query_set.filter(c) return query_set I just wanted the filtered result after applying filters a, b and c, I did not really care about intermediate states. However, now I am in the need to perform a series of actions after applying each filter. I need to know how many items were left out every time each filter is applied: count = len(query_set) query_set = query_set.filter(a) update_something(count - len(query_set)) count = len(query_set) query_set = query_set.filter(b) update_something(count - len(query_set)) count = len(query_set) query_set = query_set.filter(c) update_something(count - len(query_set)) return query_set I am worried about the performance this function now may have. I know that calling len on a QuerySet evaluates it and returns all records, since I only want to calculate the difference I may use QuerySet.count() instead: count = query_set.count() query_set = query_set.filter(a) update_something(count - query_set.count()) count = query_set.count() query_set = query_set.filter(b) update_something(count - query_set.count()) count = query_set.count() query_set = query_set.filter(c) update_something(count - query_set.count()) return query_set However, I am still concerned about the … -
What's the difference between override_settings and modify_settings in Django?
Django's docs on testing tools mention both the @override_settings and the @modify_settings decorators for usage in tests, but it is unclear from the docs (at least to me) what is the difference between them. So, what is it? -
Django translations, APIs, and POST data
I'd like to add an application to my project that requires translations, but my project has other applications for APIs. Unfortunately, the translation redirects lose the POST parameters for my API applications. I have existing API users, and I'd rather not require them to add a locale code to their API calls (which would prevent the redirect). Is there a way I can turn off translations for my API applications? Or is there some other way this is commonly handled? -
Get the first element in the for loops in the Django template
Template: {% for code in group_codes %} *_{{ code.build }}_*<br /> {% if test_info.test_type = 0 %} {{ code.pre_testing_fail }}/{{ code.pre_testing_total }} failed pre-test<br /> {% else %} {% for shelf in final_shelf_info %} {{ shelf.build }} <br/> {% if shelf.build = code.build %} {{ mr_script_count_func }}/{{ code.script_total }} <span>MR</span> failed during script<br /> {{gw_script_count_func}}/{{ code.script_total }} <span>GW</span> failed during script<br /> {{ mr_post_count_func }}/{{ code.post_testing_total }} MR failed during post-test<br/> {{ gw_post_count_func }}/{{ code.post_testing_total }} GW failed during post-test<br/> {% endif %} {% endfor %} <br/> <br/> {% endif %} {% endfor %} View def final_shelf_info(self): shelves = self.bugs_stbs() shelfList = list() for shelf in shelves: shelfList.append(shelf.results_stb_id) final_info = ResultsStbs.objects.select_related( 'build', 'pre_testing_result', 'script_result', 'post_result', ).filter( results_stb_id__in=shelfList, tr_test_case_id=self.kwargs['trTestCaseID'], ).order_by( 'pair_no','shelf_no', ) for info in final_info: if info.stb_hw_info_ids: info.stb_type = info.stb_hw_info_ids.stb_hw_info.stb_type else: info.stb_type = None return final_info I would like to get the first element in the for loop {% for shelf in final_shelf_info %} and compare with another data. How can I get the first element in the first loop. First element : Q004.01.55.01.55.19_9423 {{ shelf[0].build }} I tried like that, it did not work. The output of the for loop: Q004.01.55.01.55.19_9423 ENG_01.55.19_1392_MNTEE Q004.01.55.01.55.19_9423 ENG_01.55.19_1392_MNTEE Q004.01.55.01.55.19_9423 Q004.01.55.01.55.19_9423 ENG_01.55.19_1392_MNTEE Q004.01.55.01.55.19_9423 ENG_01.55.19_1392_MNTEE … -
Why error occurred when using mod_wsgi on Linux?
I follow django tutorial and mod_wsgi installation guide to use Apache and mod_wsg on LinuxMint18.1, but I got an error when I run apache2ctl start. Current thread 0x00007f88c10c7780 (most recent call first): [Mon Mar 20 21:23:28.781270 2017] [core:notice] [pid 32458:tid 140225331099520] AH00052: child pid 7962 exit signal Aborted (6) Fatal Python error: Py_Initialize: can't initialize sys What's wrong with me? -
Jquery working only for one item in the list
In this piece of code data is being fetch from the backend that is in Django. I have list of products in Django some having variations and others don't have them by variation I mean like pizza that come in small, medium and large size each having there own price. Problem: I want that all the items with variation should have changing price but this is not happening on the front end at the backend the prices are changing. Only the first product in the list is changing the prices but not all. (backend is working completely fine I checked the source code ) productlist.html {% extends "base.html" %} <script> {% block jquery %} function setPrice(){ var price = $(".variation_select option:selected").attr("data-price") var sale_price = $(".variation_select option:selected").attr("data-sale-price") if (sale_price != "" && sale_price != "None" && sale_price != null ) { $("#price").html("<h4>" + sale_price + " <small class='og-price'>" + price + "</small></h4>"); } else { $("#price").html(price); } } setPrice() $(".variation_select").change(function(){ setPrice() }) {% endblock %} </script> {% block content %} <div class="row"> {% for object in object_list %} <div class="col-sm-6 col-md-4"> {% if object.productimage_set.count > 0 %} {% for img in object.productimage_set.all %} <div class="thumbnail"> <img class='img-responsive' src="{{ img.image.url }}" > … -
Unexpected response code: 404 error in javascript console while trying to connect Django channels
I'm trying to route websocket in following path. matrix.routing -> ws_consumer.routing -> chat.routing matrix is my application name and other two (ws_consumer, chat) are apps. Configurations in those files are as follows matrix.routing.py ws_consumer_regex = r'^/ws_consumer' channel_routing = [ include('ws_consumer.routing', path=ws_consumer_regex), ] ws_consumer.routing.py chat_regex = r'^/chat' notification_regex = r'^/notification' channel_routing = [ include('chat.routing', path=chat_regex), include('notification.routing', path=notification_regex), ] chat.routing.py group_chat_name_regex = r'^/(?P<group_name>[a-zA-Z0-9_]+)/$' group_chat_routing = [ route('websocket.connect', consumers.group_chat_connect, path=group_chat_name_regex), route('websocket.receive', consumers.group_chat_receive, path=group_chat_name_regex), route('websocket.disconnect', consumers.group_chat_disconnect, path=group_chat_name_regex), ] group_chat_global_regex = r'^/group' channel_routing = [ include(group_chat_routing, path=group_chat_global_regex), ] client.html var socket = new WebSocket('ws://' + window.location.host + '/ws_consumer/chat/group/test/'); socket.onopen = function open() {...}; socket.onmessage = function (event) {...}; if (socket.readyState == WebSocket.OPEN) { socket.onopen(); } Server is starting without any issue under these configuration. But in console I'm getting below error. javascript console VM2306:35 WebSocket connection to 'ws://localhost:8000/ws_consumer/chat/group/test/' failed: Error during WebSocket handshake: Unexpected response code: 404 python console Not Found: /ws_consumer/chat/group/test/ [19/Mar/2017 23:42:39] "GET /ws_consumer/chat/group/test/ HTTP/1.1" 404 2202 I also tried routing directly to the consumer in matrix.routing.py which takes me to the same error. matrix.routing.py from chat.consumers import group_chat_connect #consumer method channel_routing = [ route('websocket.connect', group_chat_connect) ] What am i doing wrong here? -
How to read a text file using Django and perform operations?
I want to read a text file in Django the text file will consist of some lines having words Red and green and say line starting with line1 line 2 etc . If the line consist red or green then the html page should show line1 in red color line 2 in green color. I'm fairly new to Django hope someone will help me out -
How to optimize this
I would like to know if their would be a better way to do this .. be more pythonic. The main goal is clear a list of field containing timestamp in a model while state changes so higher state must have their timestamp cleared since state can have a setback. def clear_and_set_state_timestamp(self, state): timestamp_field = ({ 'item1': 'entered_item1_at', 'item2': 'entered_item2_at', 'item3': 'entered_item3_at', 'item4': 'entered_item4_at', 'item5': 'entered_item5_at', 'item6': 'entered_item6_at', }).get(state) fields = ['entered_item1_at', 'entered_item2_at', 'entered_item3_at', 'entered_item4_at', 'entered_item5_at', 'entered_item6_at'] fields = [fields.index(timestamp_field):] -
Django rest framework: 'create( )' NotImplementedError when making Http POST request
When making a post request in Django I get the error that 'create()' has not been implemented when I did indeed implement it in my serializer file from rest_framework import serializers from people.models import People class PeopleSerializer(serializers.Serializer): pk = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=200) favoriteCity = serializers.CharField(max_length=200) def create(self, validated_data): return People.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.favoriteCity = validated_data.get( 'favoriteCity',instance.favoriteCity) instance.save() return instance() Clearly the create method has been implemented and I don't understand why i'm getting a NotImplementedError -
Clear DB after a test - pytest django
I have a test (django pytest) that needs to manipulate objects in DB. The thing is that after the test, the DB is "dirty" and other tests fail. I saw something about TransactionTestCase but I can't understand how it works with django test. Here is a simple exmaple of my current code: @pytest.mark.django_db def test_something(mock_my_obj): mock_my_obj.save() # test test test ... # I don't want to delete the obj here... -
AttributeError at /
'int' object has no attribute 'update' Hello! I have this error, why is it prduce? If you could help me please views.py: def Completar(request, id_especialidad): if request.method == 'GET': especialidad = Especialidad.objects.get(id=id_especialidad) pedido = Pedido.objects.filter(especialidad=especialidad).update(cantidad=0).update(estado="").update(fecha_pedido="").update(fecha_entrega="") articulo = Articulo.objects.all() especialidad.estadistica = 0 especialidad.estado = "" especialidad.save() articulo.total_pedido = 0 articulo.save() return HttpResponseRedirect('/solicitar/home/') models.py: class Pedido(models.Model): especialidad = models.ForeignKey('Especialidad') articulo = models.ForeignKey('Articulo') fecha_entrega = models.DateTimeField(auto_now_add=False) fecha_pedido = models.DateTimeField(auto_now_add=True,null=True, blank=True) cantidad = models.IntegerField(blank=True) estado = models.CharField(max_length=20, blank=True, default='pendiente') -
Django - sending email with StringIO attachment raises 'utf8' codec can't decode
I'm trying to generate and send xlsx file using xlsxwriter and Django. When I create the file, save it to media files and then send, it works correctly. Now I want not to save file, instead I want to send it directly from memory. So I use StringIO. The problem is that message.send() returns Exception Value: 'utf8' codec can't decode byte 0x93 in position 18: invalid start byte This is the function (added message.encoding = 'utf-8' but did not help): def generate_xlsx_file(self): import StringIO f = StringIO.StringIO() workbook = xlsxwriter.Workbook(f) ... ... workbook.close() message = EmailMessage(subject="Subject", body="body", from_email="my@gmail.com", to=["my@gmail.com"]) message.encoding = 'utf-8' message.attach('filename.xlsx', f.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",) message.send() Do you know where is the problem?