Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django "NoReverseMatch" Error
I'm working with django and there's the relevant code in my HTML file: <form action="{% url 'users: check' %}" method="post"> I'm hoping that the form's data be sent to the method "check" in a app named users. In /user folder there's urls.py with relevant code: app_name = users urlpatterns = [ path('check', views.check, name='check'), ] And there's indeed a method called check in my views.py. But when I tried to get to the website I got the ERROR: NoReverseMatch at /users/login Reverse for ' check' not found. ' check' is not a valid view function or pattern name. I can't figure out what's the problem. Everything seems to be set well. Django version is 2.0 and Python 3.4. -
How can I loop through all tags having different ids in jquery?
I want to iterate through my django formset which has ids using jquery. id="#id_lines-0-label" id="#id_lines-1-label" id="#id_lines-2-label" id="#id_lines-3-label" # and so on. There is an add button which adds forms to formset. so it should only iterate though the forms that are added. -
Remove fields(columns) in Django Models
I am trying to remove some fields(columns) from the Models.py file. So, i make changes to the Models.py and ran makemigrations. It shows django.core.exceptions.FieldError: Unknown field(s) (removed field names) specified for MODELNAME. I also tried running python manage.py dbshell and dropping the column from the table, made changes to remove the field from models.py and then running makemigrations. It still shows the same error. Thanks in advance for any help. -
Django: Storing db query variables over time and displaying them as graphs
I am building an application that will function as a dashboard. The user will be able to create, update, delete contracts. Part of the contract model looks like this: class Contract(models.Model): ... contract_date = models.DateField() contract_expires = models.DateField(null=True) contract_length = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.customer) def save(self, *args, **kwargs): self.contract_length = (self.contract_expires - self.contract_date).days return super(Contract, self).save(*args, **kwargs) I also display the following information about the contracts to each user: contracts_qty = Contract.objects.filter(customer__department__in=[selected_department]).count() contracts_sum_total = Contract.objects.filter(customer__department__in=[selected_department]).aggregate(Sum('contract_sum'))['contract_sum__sum'] contracts_sum_avg = Contract.objects.filter(customer__department__in=[selected_department]).aggregate(Avg('contract_sum'))['contract_sum__avg'] contract_length_avg = Contract.objects.filter(customer__department__in=[selected_department]).aggregate(Avg('contract_length'))['contract_length__avg'] I also want to display the development over time for each of these metrics and for example show the user a graph for each. How do I go about to do this? I was thinking that perhaps I can create a model with query variables (contracts_qty etc) and use Django Signals to store an instance every time a contract is created, updated or deleted or perhaps automatically save an instance once a month. Is this the right way to go about this, or am I way off?? Thank you.. -
Cant connect to MS SQL server from ubuntu server
I tried to connect MS SQL server on windows machine from ubuntu server. but i am getting the below error: 127Error 20009 (severity 9): Unable to connect: Adaptive Server is unavailable or does not exist OS error 110, "Connection timed out" There was a problem connecting to the server My purpose is to access a MS SQL database in Django project.. Anybody have any idea? please help... -
Create Nested Serialier Multi Objects in Django Rest Framework?
I'm finding a solution which create Nested Serialier Multi Objects in Django Rest Framework? I have 2 models: Product and Photo (Photo is a model which store all photos of Products). This serializer I created in order to create a Product & upload all image of this products: class PhotoUpdateSerializer(ModelSerializer): class Meta: model = Photo fields = [ 'image' ] class ProductCreateSerializer(ModelSerializer): photos = ProductPhotosSerializer(many=True, write_only=True, required=False) class Meta: model = Product fields = [ 'id', 'user', 'name', 'photos' ] My viewsets: class ProductCreateAPIView(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductCreateSerializer def create_product(self, request): newProduct = Product.objects.create( user = User.objects.get(id=request.POST.get('user')), name = request.POST.get('name', '') ) newPhotos = Photo.objects.create( product = newProduct.id, image = request.POST.get('image', '') ) serializer = ProductCreateSerializer(newProduct, context={"request": request}) return Response(serializer.data, status=200) Error: Request.POST has no image When I print(request.POST), use POSTMAN like this picture: It prints: {u'user': [u'2']}>. No photos POST? How can I fix this? Please help me cause I lost 2 days for it :( -
Creating a template for post model in Django
Is it possible to automaticly create an html template for a newly posted model in django? Or maybe there are some other options? -
Integrating Django rest User authentication Api with angular 4
I am working on a project which requires me to integrate django with angular 4. I have successfully done that by forming rest api and then calling it from angular 4 but now i am stuck as i am not able to do user authentication by forming the user api and integrating it. So can anyone please tell me how to create user api for authentication and then integrate it with angular 4. -
Django - after login using google, i tried to access a simple api view. gives Unauthorized error
my view class ldata(APIView): def get(self, request): data = "my name" return Response(data) i can confirm, every time i login using google, it successfully register the user to auth_user & social_auth_usersocialauth table. but i am getting this error when i access the view. { "detail": "Authentication credentials were not provided." } i have configured everything said here https://github.com/RealmTeam/django-rest-framework-social-oauth2 and added few code to settings for google login AUTHENTICATION_BACKENDS = ( # for Google authentication 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "***" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "***" my login call url: http://localhost:8000/auth/login/google-oauth2/ -
How to get static images from Django Backend to Angular JS
The project has two independent repositories, one for the backend, and other admin(front-end). I have a folder with images in the backend project (static image files). Each image is associated with a name. Now when I click on a particular name in my admin side, I want a popup of the linked image from the Django backend. Do I need to build some APIs in the backend to do this? Or Angular can load the static image files from the Django backend directly? What would be the optimal flow to build this functionality? -
Dynamic Menu in Django using database mysql
I have tables tbl_menu, tbl_role, tbl_role_menu_mapping in mysql Tbl_menu tbl_role_menu_mapping I am unable to make a dynamic menu in my Django project using mysql which could be applicable for whole application for all apps,All example are given for static menu for separate app. While we want to bind according to role. So how can bind dynamic according to role which will be applicable for all apps -
search database from multiple form fields
I have the following case. I have a form with 3 fields which are submitted with POST method. Then the fields are captured and a search using Q is made on the database: query = Model.objects.filter( Q(field1=field1) & Q(field2=field2) & Q(field3=field3)) The problem is that I would like to dynamically use the fields that are filled not the empty ones. That means that the query will contain one or two or three criteria depending on the user. I have managed to perform the search I describe with nested if but considering adding extra fields it gets bigger and bigger. thanks -
Is is possible to cherry-pick the db connection (persistent) django will use on each request on a per client/session basis?
I'd like to be able to tell someone (django, pgBouncer, or whoever can provide me with this service) to always hand me the same connection to the database (PostgreSQL in this case) on a per client/session basis, instead of getting a random one each time (or creating a new one for that matter). To my knowledge: Django's CONN_MAX_AGE can control the lifetime of connections, so far so good. This will also have a positive impact on performance (no connection setup penalties). Some pooling package (pgBouncer for example) can hold the connections and hand them to me as I need them. We're almost there. The only bit I'm missing is the possibility to ask pgBouncer (or any other similar tool for that matter) to give me a specific db connection, instead of "one from the pool". This is important because I want to have control over the lifetime of the transaction. I want to be able to open a transaction, then send a series of commands, and then manually commit all the work, or roll everything back should something fail. Many years ago, I've implemented something very similar to what I'm looking for now. It was a simple connection pool made … -
Django: please aid, i get "is_valid() missing 1 required positional argument:'self'"...below is the block of code...thanks
class ContentCreateUpdateView(TemplateResponseMixin, View): module = None model = None obj = None template_name = 'courses/manage/content/form.html def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) return None def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super(ContentCreateUpdateView, self).dispatch(request, module_id, model_name, id) def get(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj) return self.render_to_response({'form': form, 'object': self.obj}) def post(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() if not id: # new content Content.objects.create(module=self.module, item=obj) return redirect('module_content_list', self.module.id) return self.render_to_response({'form': form, 'object': self.obj}) please i use django version: 1.11.10 and python version: 3.6.2. Below is the traceback Traceback: File "C:\Users\TOCHIE\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\TOCHIE\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\TOCHIE\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TOCHIE\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\TOCHIE\PycharmProjects\virtual_django\env\e_learning\educa\courses\views.py" in dispatch 114. return super(ContentCreateUpdateView, self).dispatch(request, module_id, model_name, id) File "C:\Users\TOCHIE\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Users\TOCHIE\PycharmProjects\virtual_django\env\e_learning\educa\courses\views.py" in post 122. if … -
PermissionError at /myapp/download/ [Errno 13] Permission denied:
I'm very new to django as well as python and working on a simple upload/download web app using django. So far, I've managed to complete the upload function and it works but I have difficulties with downloading the files uploaded. The code seems to work yet I receive 'Permission Denied' error. These are the codes I used. (views.py) def list(request): #file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): doc_file = Document(docfile=request.FILES['docfile']) print(doc_file) print(doc_file.uploaded_at) doc_file.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form #Load documents for the list page documents = Document.objects.all() #Render list page with the documents and the form return render( request, 'list.html', {'documents': documents, 'form': form} ) def download(request): file_name = request.GET.get(' ') print(file_name) path_to_file = settings.MEDIA_ROOT + '/' + file_name print(path_to_file) with open(path_to_file, 'rb') as fh: response = HttpResponse(fh.read(), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) response['X-Sendfile'] = smart_str(path_to_file) return response models.py class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') uploaded_at = models.DateTimeField(default=datetime.now, blank=True) def size(self): filesize = self.docfile.size return filesize def filename(self): filename = self.docfile.name return filename.replace("documents/", "") list.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>File upload/download</title> <style> table { border-spacing: 5; width: 80%; … -
Django custom model field
I'm using Django 1.10 and Oracle 12c. Currently the Django Oracle backend (utilizing cx_oracle) doesn't support XMLType table columns. This means I've had to so far use work-arounds (annotations) to query my legacy tables that use XMLType fields. Now I'm adding unit tests and I need a better solution to handle these XML fields. I've created a custom field which follows. This successfully allows the migrations scripts to create the tables properly in my test database. However creating fixtures doesn't work because the model can't create the appropriate SQL on it's own. So my question is, how do I add to the custom field to call an Oracle function when the ORM generates a select query? from django.db import models class XmlField(models.TextField): def db_type(self, connection): return 'XMLType' def ???some_function_I_don't_know???(self, connection): #custom_sql_function being an oracle function we created to return #the value of an XMLType field return 'custom_sql_function(%s)' % self.db_column -
How do I use AJAX for pagination in Django-Tables2?
I am using django-tables2 and I am trying to display the data of the next page without loading another page. I think AJAX could be used. From what I have found, it seems that it might not be possible. Is there something that I should look at to figure it out ? -
templates urls in django
i have four templates with different links on my home.html but how can i make the links all functional with the correct url,here's my home.html code ` FAQs About Blog Home ` `urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', include('department.urls')), url(r'^blog/', include('blog.urls')), url(r'^about/', include('about.urls')), url(r'^faq/', include('faq.urls')), url(r'^blog/about', include('blog.urls')), ] ` -
Django channels RECEIVE not returning anything
So, I've been following the Django Channels Tutorial as given here. On the 2nd page of the tutorial there is an example for you to test to make sure that the channel can communicate with Redis. The code is the following. python3 manage.py shell >>> import channels.layers >>> channel_layer = channels.layers.get_channel_layer() >>> from asgiref.sync import async_to_sync >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) >>> async_to_sync(channel_layer.receive)('test_channel') {'type': 'hello'} When I run the last command nothing ever returns. When I run the chat server myself, python manage.py runserver and then open up two windows into room 1 http://127.0.0.1:8000/chat/room_1/ I can type a text and receive it. I'm not sure why it freezes before hand, but not the latter. I think this may be related. When I get to page 4 there is a test you can run python3 manage.py test chat.tests When I run it I get the following errors: ====================================================================== ERROR: test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Starlord\Dev\mysite\mysite\chat\tests.py", line 61, in test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room 'Message was not received by window 2 from window 2') File "C:\Users\Starlord\Dev\mysite\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: Message was not received by window 2 from window 2 ====================================================================== ERROR: test_when_chat_message_posted_then_seen_by_everyone_in_same_room (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most … -
django rest-auth social connect to Vkontakte (vk)
Please help me make REST social connect for provider Vkontakte. I'm using django-allauth library (https://github.com/pennersr/django-allauth). And django-rest-auth for REST auth (https://github.com/Tivix/django-rest-auth). I've already have VKOAuth2Serializer that works fine for login and register. But connect doesnt' work. Here is urls: url(r'^rest-auth/vk/connect/$', views.VkConnect.as_view(), name='vk_connect'), url(r'^rest-auth/vk/', views.VkLogin.as_view()), Views: from allauth.socialaccount.providers.oauth2.client import OAuth2Client from allauth.socialaccount.providers.vk.views import VKOAuth2Adapter class VkLogin(CustomSocialLoginView): adapter_class = VKOAuth2Adapter serializer_class = VKOAuth2Serializer client_class = OAuth2Client callback_url = 'http://localhost:3000' class VkConnect(SocialConnectView): adapter_class = VKOAuth2Adapter #May be here should be something else? Serializer: from allauth.socialaccount.helpers import complete_social_login from rest_auth.registration.serializers import SocialLoginSerializer from django.utils.translation import ugettext_lazy as _ from requests.exceptions import HTTPError from rest_framework import serializers class VKOAuth2Serializer(SocialLoginSerializer): email = serializers.CharField(required=False, allow_blank=True) user_id = serializers.CharField(required=False, allow_blank=True) def validate(self, attrs): view = self.context.get('view') request = self._get_request() if not view: raise serializers.ValidationError(_("View is not defined, pass it as a context variable")) adapter_class = getattr(view, 'adapter_class', None) if not adapter_class: raise serializers.ValidationError(_("Define adapter_class in view")) adapter = adapter_class(request) app = adapter.get_provider().get_app(request) # Case 1: We received the access_token if attrs.get('access_token'): if not attrs.get('user_id') or not attrs.get('email'): raise serializers.ValidationError(_("Incorrect input. email and user_id is required with access_token.")) access_data = { 'access_token': attrs.get('access_token'), 'user_id': attrs.get('user_id'), 'email': attrs.get('email'), } # Case 2: We received the authorization code elif attrs.get('code'): self.callback_url … -
Django migrations router databases
Migration creates the same auth structure for the two databases. On the default side is the default Django tables and on the other side are the same default django tables more the tables in the chosen template. Is this the trick? DATABASES = { 'default': {}, 'DB1': {} } Route doc link: https://docs.djangoproject.com/en/2.0/topics/db/multi-db/#topics-db-multi-db-routing After migration: manage.py migrate manage.py migrate --database=DB1 Default tables: - auth_group - auth_group_permissions - auth_permission - auth_user - auth_user_groups - auth_user_user_permissions - django_admin_log - django_content_type - django_migrations - django_session DB1 tables: - auth_group - auth_group_permissions - auth_permission - auth_user - auth_user_groups - auth_user_user_permissions - django_admin_log - django_content_type - django_migrations - django_session - custom_table1 - custom_table2 - custom_table3 -
how to update an array of objects in a single request - django rest framework
I have array objects: const ordsend = [{ order: 4, id: 1, }, { order: 2, id: 2, }] where id is the primary key, That for axios I am sending this by the post method: this.axios.post('route-dispatchs/order/', this.ordsend) .then((response) => { console.log(success); }); I was currently testing if I returned some value through the id class RouteDispatchViewSet(viewsets.ModelViewSet): queryset = RouteDispatch.objects.all() serializer_class = RouteDispatchSerializer @list_route(methods=['post'], url_path='order') def order_dispatch(self, request): id_param = request.data.get('route_dispatch_id', None) queryset = RouteDispatch.objects.all() if id_param: queryset = queryset.filter(id=id_param).order_by('order') print(queryset) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) and if it works correctly, but what I want is that not only send one, but all, the matrix and update the field order of their respective ID. How can I do a multiple update in a single request? -
Django-migrate-Error: `ValueError: invalid literal for int() with base 10: ''
I am a django-beginner and I don´t understand this error nor explanations from other posts: ValueError: invalid literal for int() with base 10: ''. How can I fix it? My Traceback: PS C:\Users\Tobi\Desktop\LeftLife\instapic> python manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, contenttypes, instapic, sessions Running migrations: Applying instapic.0012_auto_20180406_0115...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, … -
Webpack setup with Django
I working on a Vue app in Django via django-webpack-loader, running locally I'm able to get it to work by using the following in my base.html file: {% load render_bundle from webpack_loader %} ... ... {% render_bundle 'app' %} However, in production this doesn't work - I believe because the webpack production config uses the CommonChunksPlugin to split the bundles into app, manifest and vendor. There isn't much documentation online for merging Webpack with Django - I'm wondering if there is a way to include all chunks in the Django template. -
Python julian date format
I have a function in django that check for selected date and then convert that date to julian date then it extract data from the database based on the selected date. but i am getting an error: time data 'selected_date' does not match format '%Y-%M-%d' my view.py def sum_asset_fundmanager(request): if "selectdate" in request.POST: selected_date = request.POST["selectdate"] if selected_date==selected_date: convert=datetime.datetime.strptime("selected_date", "%Y-%M-%d").toordinal() #calculating date MID Rate engine=create_engine('mssql+pymssql://username:password1@hostname /db') connection=engine.connect() metadata=MetaData() rate=Table('mccurtdt',metadata,autoload=True,autoload_with=engine) statmt=select([rate]) statmt=statmt.where(and_(rate.columns.from_currency=='AUD', rate.columns.rate_type=='MID',rate.columns.convert_date==convert)) CORP101=connection.execute(statmt).fetchall() return render(request,'template.html',locals()) my template.html Select a Date: {% csrf_token %} my tem