Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error on getting request param from Django Rest Framework and Datatables
I am trying to use DRF and Datatables to populate a table with a large amount of data, with server-side processing. Below is my view: class ProductsListAPIView(LoginRequiredMixin, ListAPIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) serializer_class = ProductSerializer def get_queryset(self): qs = Product.objects.filter(user=self.request.user).order_by("-timestamp") return qs def list(self, request, *args, **kwargs): draw = int(self.request.GET["draw"]) start = int(self.request.GET["start"]) length = int(self.request.GET["length"]) queryset = self.get_queryset() queryset = queryset[start:start+length] serializer = ProductSerializer(queryset, many=True) result = {"draw": draw, "recordsTotal": queryset.count(), "recordsFiltered":queryset.count(), "data": serializer.data} return Response(result) This the script for the Datatables and Ajax: $(document).ready(function() { $('#exampleAjax2').dataTable( { "autoWidth": true, "displayLength": 10, "lengthChange": false, "ordering": false, "processing": true, "searching": false, "serverSide": true, "language": { "zeroRecords": "Nothing to display", "info": "Showing _START_ to _END_ of _TOTAL_ records", "infoEmpty": "" }, "ajax": { "processing": true, "url": "/my-products/", "dataSrc": "" }, "columns": [....], }); }); I get the following error: KeyError: 'draw' Probably it means that I don't use the proper way to get the parameter. Although, that's my first attempt at DRF and Datatables with server-side processing, so it's possible there are other mistakes too. -
PasswordResetForm trans tag in email_template_name
How could I translate a key in PasswordResetForm class ? <p>{% trans "reset_password_follow_link" %}</p> When I send the params in the save method, the trans tag doesn't work. This only shows something like this... -
How to integrate Django based website with iOS app?
I have a website with Django backend and I want to create an IOS App for it. I read that django rest APi will be used but Im not sure how it is going to be integrated the App. Do I need to learn swift, and do I need to do the frontend of the App using swift and Xcode? -
How to filter input data into database in Django models
I have a model like the below. No matter which url is input, I wanna remove protocols in each url such as http:// or https:// before it is stored into database. Is there any filtering feature for that? class Store(models.Model): url = models.CharField(max_length=100) ... -
The 'profile_picture' attribute has no file associated with it
I am trying to create access my profile but one of my models attributes (profile_picture) is empty and it's causing my profile page to crash. I have set blank=True, and it was working earlier but it has stopped working since and i can't figure out why. If I go to the django admin and manually add a profile then I can visit my profile again and everything works. I guess my question is why can't I view my profile even if the profile_pic attribute is empty? Shouldn't blank=True take care of that? models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) profile_picture = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return self.user.username views.py def edit_user_profile(request): if request.method == 'POST': form = EditUserProfileForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() return redirect('/accounts/profile') else: form = EditUserProfileForm(instance=request.user) args = {'form': form} return render(request, 'accounts/edit_user_profile.html', args) Profile.html <div class="container"> <br> <h2>{{ user }}</h2> <br> <p>Name: {{ user.first_name }} {{ user.last_name }}</p> <img src="{{ user.userprofile.profile_picture.url }}" width="240px"> <p></p> <p>Motto: {{ user.userprofile.description }}</p> <p>Youtube: <a href="{{ user.userprofile.website }}">{{ user.userprofile.website … -
django, flask, react, beginner web developer
i want to be a full stack web developer. Should I start from learning react javascript library or flask/ django python library. And any best database language to start with ? -
Getting items from an api using django
I am trying to get the amount value from the available field when I retrieve a blance from Stripe. I have the following response: { "available": [ { "amount": 10302, "currency": "cad", "source_types": { "card": 10302 } } ], "livemode": false, "object": "balance", "pending": [ { "amount": 0, "currency": "cad", "source_types": { "card": 0 } } ] } I am trying to get the available amount, so I wrote the following: available = balance['available'] as a response I am getting the following: [<StripeObject at 0x110d45a98> JSON: { "amount": 10302, "currency": "cad", "source_types": { "card": 10302 } }] But how can I get access to the 'amount' part? I tried: amount = available['amount'] but I got an error stating that I am trying to get a string instead of a dictionary. I know I have a syntax error, I am not really familiar with all these [ and {: . -
lack of data while serialization model with manytomanyfield
here's examples I have: models.py: class Example(models.Model): title = models.CharField(...) description = models.CharField(...) class Foo(models.Model): example = models.ManyToManyField(Example) serializers.py: class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = '__all__' views.py: ... serialized_data = [FooSerializer(foo).data for foo in Foo.objects.all().get] In output I receive only Example's IDs, but is there any way I could get title and description fields also (details of m2mfield)? As I understand Foo.objects.all().get simply doesn't contain this data, but may be I could somehow get it and use? I could also rebuild models if needed, but currently I use m2mf because of needs to contain multiple objects as related to this model data -
I have product Variation in django that uses ManyToMany Field... How do use django-import-export to show this?
I want to export this into excel and then into selenium. How do I write code for this? -
How use Celery on appengine flexible with a django app?
i have a django app on App engine flexible y need to implement Tasks with Celery but i don't know how start Celery process. -
how to move a foreign key from one model to another without breaking data in django?
previous model hierarchy: class A(models.Model): name = models.CharField(max_length=150) B = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): name = models.CharField(max_length=150) C = models.ForeignKey(C, on_delete=models.CASCADE) new model hierarchy: class A(models.Model): name = models.CharField(max_length=150) B = models.ForeignKey(B, on_delete=models.CASCADE, null=True) C = models.ForeignKey(C, on_delete=models.CASCADE, null=True) class B(models.Model): name = models.CharField(max_length=150) Just moving the foreign key from model B to Model A I have already made the change to the model and adjusted all the relevant queries in my django app, but I have no strategy right now as far as how to deploy these changes without breaking data, let alone a rollback plan.. Can these changes be made with migrations alone, or will I be forced to touch sql? -
Include wildcard (%) in Django 'contains' query
According to Django docs Entry.objects.get(headline__contains='Lennon') Roughly translates to this SQL: SELECT ... WHERE headline LIKE '%Lennon%'; But if I want to do somethng like this (removing a wildcard): SELECT ... WHERE headline LIKE '%Lennon'; What would the Django query be? -
Which python web framework suits better to this architecture?
I have already used Django and Flask and I know that Django can work with JSON responses, but instead of using Jinja directly on the HTML I want to send the data as JSON in order to handle it on the client side, and also to allow other people to work on the front end independently. The web app will have a few pages (max 3) including a blog section. Flask seems to give more freedom but I think Django would ease things up with the blog (using Django models). Simplified diagram: I would like to know if this is a good (in terms of efficiency) way to reach my goal, and if so which framework suit better. If not, how could I do it properly with one of these frameworks? (Or another python web framework recommendation) -
error when installing xadmin UnicodeDecodeError
when I installed xadmin through Pycharm setting, there was an error: UnicodeDecodeError: 'gbk' codec can't decode byte 0xa4 in position 3444: illegal multibyte sequence. enter image description here How to fix this error? -
can get the cookies set by django in the response of ajax request
cors-headers to enable the cors on my django server. my setting.py is like this. CORS_ORIGIN_ALLOW_ALL= True CORS_ALLOW_CREDENTIALS = True also i have added corsheaders to the INSTALLED_APPS and my MIDDLEWARE is like this MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ]. i have set a very simple view that looks like this. def get(self, request): response = HttpResponse("hi") response['Set-Cookie'] = ('food=bread; Path=/; max_age=10000') print(response._headers) return response on the console the headers is like this. {'set-cookie': ('Set-Cookie', 'food=bread; drink=water; Path=/; max_age=10000'), 'content-type': ('Content-Type', 'text/html; charset=utf-8')} when i call my api in browser cookie is set and everything is ok but when i use axios for ajax in the body of response there is nothing that is similar to my cookie. my javasctipt code i like this. axios.get('http://37.130.202.188:13434/users/test/', {withCredentials: true, }) .then(function (response) { console.log(response); }); and i run my server with this command python manage.py runserver every response to this headache would be very appreciated. -
Saving form info to a file in Django
I want to create an small app to configure a third party sw using Django. The idea is to read this config file and show the values in the web page. Then we modify the values and the info is saved directly into the file, with no need to store the data in the db and read from there. So far I have just created a Django form that asks you via web for the field values and stores them in the db, but I want to save directly the values in the config file. So question is, what will be the steps to create a Django program that will: read a config file from disk and show the values via web allows you to modify the field values, when clicking on save it modifies directly the config file you loaded initially. I know it is not too many info, I just need some guidance on the steps. Thanks :) -
No module named django ImportError with Apache wgsi and Django
I have spent two days on stackoverflow and other forums to solve my error that seems quite common but no solution I've mined has worked to solve my problem. My apache server raise an error 500 and the apache log says that there is an ImportError with wsgi here is an extract of the apache log: [Thu Jul 12 22:42:31.354853 2018] [wsgi:error] [pid 26147:tid 140360491362048] [remote 127.0.0.1:46897] Traceback (most recent call last): [Thu Jul 12 22:42:31.354916 2018] [wsgi:error] [pid 26147:tid 140360491362048] [remote 127.0.0.1:46897] File "/home/david/DjangoProjects/unflat/unflat/wsgi.py", line 29, in <module> [Thu Jul 12 22:42:31.380265 2018] [wsgi:error] [pid 26147:tid 140360373733120] [remote 127.0.0.1:46641] mod_wsgi (pid=26147): Target WSGI script '/home/david/DjangoProjects/unflat/unflat/wsgi.py' cannot be loaded as Python module. [Thu Jul 12 22:42:31.380351 2018] [wsgi:error] [pid 26147:tid 140360373733120] [remote 127.0.0.1:46641] mod_wsgi (pid=26147): Exception occurred processing WSGI script '/home/david/DjangoProjects/unflat/unflat/wsgi.py'. [Thu Jul 12 22:42:31.380514 2018] [wsgi:error] [pid 26147:tid 140360373733120] [remote 127.0.0.1:46641] Traceback (most recent call last): [Thu Jul 12 22:42:31.380570 2018] [wsgi:error] [pid 26147:tid 140360373733120] [remote 127.0.0.1:46641] File "/home/david/DjangoProjects/unflat/unflat/wsgi.py", line 29, in <module> [Thu Jul 12 22:42:31.380587 2018] [wsgi:error] [pid 26147:tid 140360373733120] [remote 127.0.0.1:46641] from django.core.wsgi import get_wsgi_application [Thu Jul 12 22:42:31.3 80634 2018] [wsgi:error] [pid 26147:tid 140360373733120] [remote 127.0.0.1:46641] ImportError: No module named 'django' I have installed Django … -
How to add product options to Django Oscar?
For example, same t-shirt of different size has a different price. Thanks for your help. -
UnboundLocalError-local variable 'app' referenced before assignment
this is my appname.urls codes [appname:atolye(it is a Turkish word)] from django.conf.urls import url from .views import * urlpatterns = [ url(r'^index/$', atolye_index), url(r'^(?P<id>\d+)/$', atolye_detail), ] and this is my atolye.views from django.shortcuts import render, get_object_or_404 from .models import atolye def atolye_index(request): atolyes=atolye.objects.all() return render(request, 'atolye_index.html', {'atolyes':atolyes}) def atolye_detail(request, id): atolye = get_object_or_404(atolye, id=id) context = { 'atolye': atolye, } return render(request, 'atolye_detail.html', context) I want to use this code but its is not work. What should i do? python:3.5.3 django:1.10 win7 I am a new user. Sorry for my bad English. -
Scheduling based on pre-specified availability in Django Rest Framework
(Django 2.0, Python 3.6, Django Rest Framework 3.8) I found a few posts regarding setting up an appointment in DRF, but I'm unsure of how to do this when the appointment is based on a schedule. I'm wondering what I can do to model this. Here's the logic I've been able to develop so far: I have a table which has availability for every hour of every day that a user TrainerProfile can choose days & times from. Availability would look like this: Availability: Sunday 12am - 1am Sunday 1am - 2am Sunday 2am - 3am ... Saturday 11pm - 12am Now, TrainerProfile has a ManyToManyField linked to Availability which they can select their availability for. The availability schedule TrainerProfile chooses is always the same from week to week. A table Bookings has the fields: client: A foreign key linked to user profile ClientProfile trainer: A foreign key linked to TrainerProfile status: A selection field which has the choices pending and confirmed with pending as the default trainer_availability: A OneToOneField liked to TrainerProfile's availability When a ClientProfile chooses one of the trainer_availability times inside Bookings, the field status is defaulted to pending which the Trainer would then need to change … -
SummernoteInplaceWidget Not Working Properly - summernote-lite
I have recently discovered Summernote and love it. I have run into a problem where when I am using it in my django installation, the SummernoteWidget is working but the SummernoteInplaceWidget is not. When I use the SummernoteWidget, the data appears in my editor as I would expect, but when I use the SummernoteInplaceWidget, I get a blank screen. Thanks for any thoughts. My code... I am using Summernote-Lite without bootstrap and I am using the most recent version 0.8.9 <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-lite.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote-lite.js"></script> My Summernote_Config in settings.py SUMMERNOTE_CONFIG = { 'summernote': { 'toolbar': [ ['undo', ['undo',]], ['redo', ['redo',]], ['style', ['bold', 'italic', 'underline',]], ['font', ['strikethrough',]], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ], 'width': 760, 'height': 300, 'focus': True, 'fontSizes': ['8', '9', '10', '11', '12', '14', '18', '22','24', '36', '48' , '64', '82', '150'], }, } My widget refernce in forms.py.. widgets = { 'procedure': SummernoteInplaceWidget(), } The editor renders, but I just get a blank screen... If I use the SummernoteWidget instead, I get the data on the screen that I'm expecting, but the resize bar is not present and the font size setting is not honored as shown below. Any ideas on if this … -
Add property in Django many to many relation
I have the following Django models: class Lesson(models.Model): title = models.TextField() class Course(models.Model): lessons = models.ManyToManyField(Lesson) class User(AbstractUser): favorites = models.ManyToManyField(Lesson) I have a route /courses/course_id that returns a course details including an array of lessons (using Django Rest Framework) How can i return in the lessons object an additional attribute favorite based on my users favorites. I attempted the following: course = self.get_object(course_id) favorites = request.user.favorites for lesson in course.lessons.all(): if lesson in favorites.all(): lesson.favorite = True serializer = CourseDetailSerializer(course, context=serializer_context) return Response(serializer.data) But when returning it doesn't work: (django.core.exceptions.ImproperlyConfigured: Field name favorite is not valid for model Lesson. My serializers: class CourseDetailSerializer(serializers.HyperlinkedModelSerializer): lessons = LessonListSerializer(many=True, read_only=True) class Meta: model = Course fields = ('id', 'lessons', 'name', 'title') class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'title', 'duration', 'favorite') -
error uninstalling django-tables2
Recently i installed the library django-tables2 using pip in win 10. Now when i try to uninstall using the command pip uninstall django-tables2 i get an error that's seems to be in python libraries. Here is the stack trace i'm getting: Exception: Traceback (most recent call last): File "c:\users\usuario\appdata\local\programs\python\python35\lib\site- packages\pip\_internal\basecommand.py", line 228, in main status = self.run(options, args) File "c:\users\usuario\appdata\local\programs\python\python35\lib\site- packages\pip\_internal\commands\uninstall.py", line 68, in run auto_confirm=options.yes, verbose=self.verbosity > 0, File "c:\users\usuario\appdata\local\programs\python\python35\lib\site- packages\pip\_internal\req\req_install.py", line 660, in uninstall uninstalled_pathset = UninstallPathSet.from_dist(dist) File "c:\users\usuario\appdata\local\programs\python\python35\lib\site- packages\pip\_internal\req\req_uninstall.py", line 316, in from_dist paths_to_remove.add(path) File "c:\users\usuario\appdata\local\programs\python\python35\lib\site- packages\pip\_internal\req\req_uninstall.py", line 169, in add if not os.path.exists(path): File "c:\users\usuario\appdata\local\programs\python\python35\lib\genericpath.py", line 19, in exists os.stat(path) ValueError: stat: embedded null character -
How to redirect to a page after deleting in django?
I am trying to redirect to a page after deleting an object I don't know but it's not working. The object gets deleted but it doesn't redirect to any page can someone please help me ? If you need more code you can ask me. Thank you ! Views of deleting product @login_required() def delete_product(request, product_id): delete = get_object_or_404(Product, pk=product_id) form = NewPro(instance=delete) if request.method == 'POST': form = NewPro(request.POST, request.FILES, instance=delete) if form.is_valid(): delete.delete() return redirect('store_details') else: form = NewPro(instance=delete) return render(request, "default/product_delete.html", {'form': form, 'delete': delete}) url pattern path('/delete_product', views.delete_product, name='delete_product') -
Work leave planner WEB APPLICATION
Recently I've been assigned a task to develop a web app to plan leaves at our company. The main functionality is selecting days that given employee wants to reserve and then accepting/declining by those dates by his manager. Also, employees will be paired, so one of pair has to always be at work. I have zero experience in developing web applications, so I need some help. Do you have any tips? Or maybe do you know of any existing project that are similar? I wanted to use Django, but any technology will do. Thanks for your help!