Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ajax get request - load model instance into a form
I have a table in a HTML template that displays all instances of a django model. on each row of the template I have an edit button that looks up the primary key of each instance, and by clicking that button I want all the fields in the model instance to be populated in a modal by using ajax. After that I want to be able to edit the data and use ajax to send the edited data back to the database. I have been searching all over the web and found this post that is exactly what I need, but I still can't get it to work. Any help would be greatly appreciated. jQuery code var modalDiv = $("#modal-div"); $(".open-modal").on("click", function() { console.log("button clicked"); var url = $(this).attr('data-url').replace('/', ''); console.log("url:",url); // this returns my customer number but is not used in the code below $.ajax({ url: $(this).attr("data-url"), type: 'get', success: function(data) { console.log("success"); modalDiv.html(data); $("#myEdit").modal(); //#myEdit is the ID of the modal }, error : function() { console.log("Error: this did not work"); // provide a bit more info about the error to the console } }); }); a tag in form <a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a> … -
How can i fix this when CSS not work in Django Framework?
This is how my Django admin panel appears -
raise RuntimeError('You need to use the eventlet server. '
In my project, I created a app: the website_chat/views.py code: async_mode = 'eventlet' import os from django.http import HttpResponse import socketio basedir = os.path.dirname(os.path.realpath(__file__)) sio = socketio.Server(async_mode=async_mode) thread = None the website_chat/management/commands/runserver.py: from django.core.management.commands.runserver import Command as RunCommand from xxx/website_chat.views import sio class Command(RunCommand): help = 'Run the Socket.IO server' def handle(self, *args, **options): if sio.async_mode == 'threading': super(Command, self).handle(*args, **options) elif sio.async_mode == 'eventlet': # deploy with eventlet import eventlet import eventlet.wsgi from Qiyun02.wsgi import application eventlet.wsgi.server(eventlet.listen(('', 8002)), application) elif sio.async_mode == 'gevent': # deploy with gevent from gevent import pywsgi from Qiyun02.wsgi import application try: from geventwebsocket.handler import WebSocketHandler websocket = True except ImportError: websocket = False if websocket: pywsgi.WSGIServer( ('', 8000), application, handler_class=WebSocketHandler).serve_forever() else: pywsgi.WSGIServer(('', 8000), application).serve_forever() elif sio.async_mode == 'gevent_uwsgi': print('Start the application through the uwsgi server. Example:') print('uwsgi --http :5000 --gevent 1000 --http-websockets ' '--master --wsgi-file django_example/wsgi.py --callable ' 'application') else: print('Unknown async_mode: ' + sio.async_mode) In my wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Qiyun02.settings") from socketio import Middleware from website_chat.views import sio django_app = get_wsgi_application() application = Middleware(sio, django_app) But when I runserver I get the bellow error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, … -
D3, Django, and hierarchical many-to-many relationships
I started a project in Django with most of the front-end rendering being done in D3.js. This stems from an old database project I had that was built in MySQL, but I'm just now getting around to building an interface for it. My biggest issue at the moment is handling a self-join many-to-many relationship. In MySQL, I used an adjacency table off the main table. For example: |ParentID | ChildID | "Extra data" | |[ItemID1]|[ItemID2] | "Some comment" | |[ItemID1]|[ItemID3] | "Some comment" | |[ItemID2]|[ItemID4] | "Something " | |[ItemID3]|[ItemID4] | "Somethingelse"| Without going into details about the data itself, there is a lot of hierarchy that needs to be preserved. Parent items have multiple children; children can have multiple parents. I need recursion both ways from top-to-bottom. A nested approach doesn't seem appropriate, as the data in the Items fields are the focus of what I'm building; the relationships between Items are a more of a bonus feature. Ideally, it would be nice if that could be passed to D3 in a JSON format that could make nodes or trees to visualize the data (serialize didn't seem to work as intended, and I'm not sure if it's the appropriate … -
Permissions django in template
How to make certain groups of users set in the admin panel can access only certain content on the site. Maybe you have examples of works in which it is implemented. -
django-import-export exporting files without id and user but importing with user and header
I want to export csv files without id and user but when I import, I want it to have an autoincrementing id based on the number of contacts and the user be the request.user. Here is my model: class Contact(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) contact_number = PhoneNumberField(help_text="Please put country code at start of number. eg: +639171231234") address = models.CharField(max_length=255) def __str__(self): return self.first_name + " " + self.last_name and here is my resources.py from import_export import resources from .models import Contact class ContactResource(resources.ModelResource): class Meta: model = Contact exclude = ('id', 'user') Here is my views for import and export def export_csv(request): queryset = Contact.objects.filter(user=request.user) contact_resource = ContactResource() dataset = contact_resource.export(queryset) response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="contacts.csv"' return response def import_csv(request): if request.method == 'POST': contact = Contact.objects.filter(user=request.user) contacts_resource = ContactResource() dataset = Dataset() new_contacts = request.FILES['import-csv'] imported_data = dataset.load(new_contacts.read().decode('utf-8'),format='csv') for header in dataset.rows: dataset.id = request.user.id dataset.user = request.user dataset.id =+ 1 contacts_resource.import_data(dataset, dry_run=False) return render(request, 'addressbook/import.html', {}) I think I know the logic, I just don't know what attribute to use. -
Django F-object works wrong?
I have Django-model class QuestDocument(Model): document = models.ForeignKey(Document, on_delete=models.PROTECT) quest = models.ForeignKey(Quest, on_delete=models.PROTECT) is_actual = models.BooleanField() And I try update is_actual field according to condition "if document_id in doc_ids then is_actual should be True, else - False". I tried this: QuestDocument.objects.filter(quest_id=q.id).update(is_actual=F('document_id') in doc_ids) But got following generated SQL: UPDATE "quest_document" SET "is_actual" = false WHERE "quest_document"."quest_id" = 1; I expected SQL case using. And now don't understand why getting such SQL. P.S. problem is solved with QuestDocument.objects.filter(quest_id=q.id).update(is_actual=Case(When(document_id__in=doc_ids, then=True), default=False)) but now I want to understand, what is happening when I use update(is_actual=F('document_id') in doc_ids) -
Heroku python 3.6.3 & django app deployment error: The requested API endpoint was not found
I have the worked app (Availible here tandtpartners.herokuapp.com) But I've got the remote: ! The requested API endpoint was not found. Are you using the right HTTP verb (i.e. GET vs. POST), and did you specify your intended version with the Accept header? error while trying to deploy the app again. Even when I cloned this app to another folder and added some ! to index.html, I received the same error. C:\heroku\2\tandtpartners>git status On branch master Your branch is up-to-date with 'heroku/master'. Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: hello/templates/index.html C:\heroku\2\tandtpartners>git commit -m "Changed only index html" [master 8a56e0d] Changed only index html 1 file changed, 1 insertion(+), 1 deletion(-) C:\heroku\2\tandtpartners>git commit -m "Changed only index html" [master 8a56e0d] Changed only index html 1 file changed, 1 insertion(+), 1 deletion(-) C:\VS\heroku\2\tandtpartners>git push heroku master Counting objects: 5, done. Delta compression using up to 4 threads. Compressing objects: 100% (5/5), done. Writing objects: 100% (5/5), 432 bytes | 432.00 KiB/s, done. Total 5 (delta 4), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: ! The requested API endpoint was not found. Are you using the right HTTP verb (i.e. `GET` … -
Django class-based views vs function views performance
Is there performance difference between class-based and function views? Is instance created every time there's request to class based view, or not? What about memory? Should I use function views or class views to achieve best performance under high load? -
Details from the db not passed on to html Django template
I am creating a blog site. The DB do have blog posts which is verified from the blog list page and also from the admin section. On clicking on the heading on the blog list page, the actual blog post page should load, which does, however the blog details like the title and content doesn't appear on the blog post page. models.py from django.db import models class ModelBlog(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=100) body = models.TextField() slug = models.SlugField() author = models.CharField(max_length=50) pub_date = models.DateTimeField(auto_now_add=True) mod_date = models.DateTimeField(auto_now_add=True) thumb = models.ImageField() def __str__(self): return self.title def snippet(self): return self.body[:270] + '...' views.py (the second function is associated with the blog post page) from django.shortcuts import render from .models import ModelBlog from django.http import HttpResponse def function_blog_list(request): var_blog = ModelBlog.objects.all().order_by('pub_date') return render(request, 'blog/blog-list.html', { 'prop_blog':var_blog }) def function_blog_post(request, slug): inst_post = ModelBlog.objects.get(slug=slug) return render(request, 'blog/blog-post.html', { 'prop_blogpost':inst_post }) HTML template (blog/blog-post.html) {% load static from staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{ inst_post.title }}</title> <meta name="description" content=""> <link rel="stylesheet" href="{% static 'css/blog-post.css' %}"> </head> <body> <div class="wrapper"> <h1>{{ inst_post.title }}</h1> <p>Published on: {{ inst_post.pub_date }}</p> <p>Written by: {{ inst_post.author }}</p> <p>{{ inst_post.body }}</p> </div> </body> </html> The page … -
Do not understand the custom `runserver.py` function in this project
I am read a python-socketio django example project: You see, in it there is a socketio_app/management/commands/runserver.py: from django.core.management.commands.runserver import Command as RunCommand from socketio_app.views import sio class Command(RunCommand): help = 'Run the Socket.IO server' def handle(self, *args, **options): if sio.async_mode == 'threading': super(Command, self).handle(*args, **options) elif sio.async_mode == 'eventlet': # deploy with eventlet import eventlet import eventlet.wsgi from django_example.wsgi import application eventlet.wsgi.server(eventlet.listen(('', 8002)), application) elif sio.async_mode == 'gevent': # deploy with gevent from gevent import pywsgi from django_example.wsgi import application try: from geventwebsocket.handler import WebSocketHandler websocket = True except ImportError: websocket = False if websocket: pywsgi.WSGIServer( ('', 8000), application, handler_class=WebSocketHandler).serve_forever() else: pywsgi.WSGIServer(('', 8000), application).serve_forever() elif sio.async_mode == 'gevent_uwsgi': print('Start the application through the uwsgi server. Example:') print('uwsgi --http :5000 --gevent 1000 --http-websockets ' '--master --wsgi-file django_example/wsgi.py --callable ' 'application') else: print('Unknown async_mode: ' + sio.async_mode) I am not understand the function of the file there, normally in my Django project I do not need it, what does it do there? -
Is there an existing form field that allows adding an arbitrary sequence of elements without re-rendering?
Well, the title speaks for itself. I'm looking for a Django form field that cleanly replicates this behavior without resorting to custom/external Javascript: Say you have a form for creating an Item. An Item has, for example, a Title, Description, and Date. You fill those out, and click on, say, "Add another Item". Then a new "line" of fields appears, with its own new Title, Description and Date fields under the previous one, and you can fill those out, and so on. When you're done adding "lines", you press send and the POST data contains all the "lines" you filled. Is there a way to do this without, like I said, resorting to custom Javascript or re-rendering the form? I've checked the documentation but haven't found any, and I know the default admin forms do this, but I'm not sure how. -
Django csv export deleting carriage return
I have a csv export in my Model Admin. This work fine but one a textfield 'comment' contain carriage return. Is there any possibility to get rid of it a it produces problem when I do an Excel import. Here an example of a comment: "This is a comment which contains carriage return." The import in Excel gives: Name | Country |Comment Matt Computer| US| This is a | | comment which contains | | carriage return.| | Here my code in admin.py def export_campaign(modeladmin, request, queryset): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="campaign.csv"' writer = csv.writer(response) writer.writerow(['Name', 'Country', 'Comment']) lastComment = Comment.objects.filter(commentSub=OuterRef('pk')).order_by('-created_at') #writing a subquery to get only the recent comment and not all myList = queryset.annotate(LastComment=Subquery(lastComment.values('commentText')[:1])) myList = myList.values_list('UserName', 'UserCountry','LastComment') for cust in myList: writer.writerow(cust) return response export_campaign.short_description = 'Campaign-Export to csv' I would be very thankful for a hint. -
How to register the wsgi if the python-socketio is a part of my project
I am reading the python-socketio example. in its wsgi.py: import os from django.core.wsgi import get_wsgi_application from socketio import Middleware from socketio_app.views import sio os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_example.settings") django_app = get_wsgi_application() application = Middleware(sio, django_app) in the views.py: async_mode = None import os from django.http import HttpResponse import socketio basedir = os.path.dirname(os.path.realpath(__file__)) sio = socketio.Server(async_mode=async_mode) thread = None I want to know, the GitHub example shows use this method to register wsgi application: django_app = get_wsgi_application() application = Middleware(sio, django_app) But in my project, the python-socketio is a part of it, how can I register the wsgi in this scenario? EDIT-01 My project wsgi.py current code is bellow: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Qiyun02.settings") application = get_wsgi_application() -
django complains date value is invalid
In my settings, I use USE_L10N = True. I have a model that has this field: class MyModel(models.Model): date = models.DateField(null=False, blank=False) I use a generic CreateView for the above model. In my html form, I use it like so: <input required value="{{ form.date.value }}" id="{{ form.date.id_for_label }}" name="{{ form.date.html_name }}" type="text" class="form-control" data-provide="datepicker" data-date-format="M. dd, yyyy"> (I use bootstrap-datepicker). When a date is selected for the field, It shows up in this format: Feb. 08, 2018. (This is the exact format that any date field appears, and I simply adhere to that by using data-date-format="M. dd, yyyy") However, when I submit the form, I get this error: Enter a valid date. I don't understand why django cannot convert the text value even though it itself presents the value that exact way. For example, if I supply an initial value for the field by overriding get_initial like so: def get_initial(self): initial = super(MyModelForm, self).get_initial() initial['date'] = datetime.date.today() return initial Now, when the form is loaded, what I see for it's value is this: Feb. 22, 2018 (Which is the exact format I am using). And submitting without changing this value again results in the same error. It's as if django … -
How to convince my boss to use Django python3 over PHP?
I am not sure if this is a good question to ask here but... Could the cost differ running the applications based on the different languages? I am not a sys-admin, but is it possible that Django(over PHP) could some how save a company money when it comes to he servers? Or an I wrong in that thinking? -
Django: How to save 3 ModelForms in 1 view
How can I save the input from 3 FormModels from one view? Hi Stackoverflow, this is my first post here. I've just started learning to code in Python/Django, so my code might be incorrect at all, sorry for that. After three days of searching and trying a lot of code, my hope is on someone with knowledge :) What I'm trying to do: One big form: User fills in personal fields, dossiers fields and the information about a second person. (part not being saved correctly right now) Views.py one view for 2 ModelForms and reusing one again for c_person. Models.py 2 models (one dossier and one person data model). Forms.py 2 ModelForms (one from dossier and one from person, reusing the person form withing the view). The dossier.html data to give an idea of the form (removed alot of code). <div class="column is-one-fifth"> <label class="label is-small">Firstname</label> {{ person_form.first_name }} </div> <div class="column is-one-fifth"> <label class="label is-small">Preposition</label> {{ person_form.preposition }} </div> <div class="column is-one-fifth"> <label class="label is-small">Lastname</label> {{ person_form.last_name }} </div> <div class="column is-one-fifth"> <label class="label is-small">Address</label> {{ person_form.address }} </div> <div class="column is-one-fifth"> <label class="label is-small">Firstname</label> {{ cperson_form.first_name }} </div> <div class="column is-one-fifth"> <label class="label is-small">Lastname</label> {{ cperson_form.last_name }} </div> … -
Django Cached template loader OfflineGenerationError
We are using Django 1.10 and enabled Cached template loader. 'loaders': [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'core.base.loaders.Loader', ]), ], After this every page I visit gives this error: compressor.exceptions.OfflineGenerationError: You have offline compression enabled but key "xxxxxxxxxxxxxxxxx" is missing from offline manifest. You may need to run "python manage.py compress". I don't get this, cached.Loader should just work as it is enabled by default with 1.11, why is it causing problems? It should cache/compress HTMLs on the fly. Can it be interfering with the following configuration? STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ] COMPRESS_ENABLED = True COMPRESS_OUTPUT_DIR = '.' COMPRESS_ROOT = STATIC_ROOT COMPRESS_STORAGE = 'core.base.storages.LocalCompressorStorage' COMPRESS_CACHE_BACKEND = 'compressor' COMPRESS_PRECOMPILERS = [ ('text/x-scss', 'core.base.precompilers.ScssFilter'), ('text/es6+javascript', 'core.base.precompilers.BabelFilter'), ('text/jsx+javascript', 'core.base.precompilers.BabelJsxFilter'), ] COMPRESS_CSS_FILTERS = [ # 'compressor.filters.cssmin.rCSSMinFilter', 'core.base.precompilers.PostCssFilter', ] COMPRESS_JS_FILTERS = [ 'compressor.filters.jsmin.JSMinFilter', ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } -
creating new record with post give error: Got a `TypeError` when calling `Product.objects.create()
this is django-rest-framwork and i have the folowing view class to view or create product . now im trying to add new record with post but i get this error: can anyone tell me why and how can i fix this ?.. thankyou TypeError at /store/view/ Got a `TypeError` when calling `Product.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Product.objects.create()`. You may need to make the field read-only, or override the ProductSerializer.create() method to handle this correctly. view class: class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = ProductSerializer permission_classes = [IsAuthenticatedOrReadOnly] def get_queryset(self): qs = Product.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) ).distinct() return qs def perform_create(self, serializer): serializer.save(author=self.request.user, context={'request': self.request}) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) and related serilizer class: class ProductSerializer(ModelSerializer): product_ratings = ProductRatingSerializer(many=True, read_only=True) product_badges_set = ProductBadgesSerializer(many=True, read_only=True) author = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name + ' ' + obj.author.last_name def get_category(self, obj): return obj.category.title class Meta: model = Product fields = [ 'product_id', 'author', 'title', 'mini_description', 'you_learn', 'you_need', 'full_description', 'price', 'video_level', 'video_length', 'created_date', 'updated_date', 'product_ratings', 'product_badges_set', ] read_only_fields = ['product_id', 'created_date', … -
Getting complex query set with a many to many relationship in django
I am trying to get all article objects that are part of a section in an edition that is in an issue. I am stumped, even after looking at the documentation for django 2.x I can get all editions with all of their sections that are part of an issue, but I cannot figure out how to get articles that are related to a section per edition. For context, here is my working query inside a django view without getting articles: def issue_edit_form(request, iid=0): latest = utils.get_latest() issue = Issue.objects.get(pk=iid) editions = issue.edition_set.all() sections = [] for i in editions: sections.append(i.section_set.all().order_by("order")) return render(request, 'issue_editor.html', {'latest': latest, 'issue': issue, 'editions': editions, 'sections': sections, 'article_form': ArticleForm}) Here is my models.py class Issue(models.Model): volume = models.SmallIntegerField(default=0) issue = models.SmallIntegerField(default=0) issue_date = models.DateField() published = models.BooleanField(default=False) class Meta: verbose_name = " Issue" def __str__(self): return "Vol. " + str(self.volume) + " Issue: " + str(self.issue) + ": " + str(self.issue_date) class Edition(models.Model): edition = models.CharField(max_length=100) issue = models.ForeignKey(Issue, on_delete=models.CASCADE, null=True) class Meta: verbose_name = " Edition" @property def issue__name(self): return self.issue.issue_date def __str__(self): return self.edition class Section(models.Model): section_name = models.CharField(max_length=100) section_image = models.ImageField(blank=True, null=True) order = models.SmallIntegerField(default=1) section_hidden = models.BooleanField(default=False); edition = models.ForeignKey(Edition, on_delete=models.CASCADE, … -
Django sort model objects by intersection count of a property with another QuerySet
I have a problem with Django querying. I searched through web but still couldn't find a solution to it. I have a model called Question: class Question(models.Model): ... tags = models.ManyToManyField(Tag, related_name='tagged_questions') ... And I need to write a method which is as below: def get_recommended_questions(request): ... interested_tags = user.interested_tags.all() recommended_questions_list = ... // I need help here I need to get a list of Question objects, which are sorted by the intersection count of their tags with interested_tags For example: interested_tags = [A, B, C] And I have following questions in the database: q1.tags = [A, B, C] // intersection count = 3 q2.tags = [D] // intersection count = 0 q3.tags = [A, B, D] // intersection count = 2 q4.tags = [A, D] // intersection count = 1 What I want to get is: recommended_questions_list = [q1, q3, q4] -
Django: detect the mouse click if session out
I have created a login page for my application and set the session out for 3 minutes and it is working fine, but the problem is when session out happened the user is still able to do many activities on the current page i.e the logout page do not show until unless user do a page refresh or redirect to the other page. So, how is it possible to do the logout once the session out and user do any of the activity on the current page? -
Jinja2 custom templatetag extension
I am switching an existing Django project's templates to jinja2. I use crispy forms to render all forms in the project but jinja2 does not understand the {% crispy form %} tag. I need help with an extension that registers the crispy form tags in jinja2 -
Is it possible to check the user whether is on-line or off-line in Django project?
Is it possible to check the user whether is on-line or off-line in Django project? There is a requirement of check the users whether is on-line. In my Django project, I have a after-sale group, in it there are several staff admin users. I want to list their information, I also want to check whether they are login. How to check it? I use django-rest-auth, there is a token to verify the users, I am not sure whether this helps. -
How to I represent a float and date fields that are not null in django correctly
I am using python 3 and django 1.11 got the following data in a .sql file: How do I use DecimalField and DateField components to represent the fields correctly. CREATE TABLE employee_per_diem ( employee_per_diem_id serial primary key, employee_month_id integer references employee_month not gs, travel_date date not null, return_date date not null, days_travelled integer not null, per_diem float default 0 not null, cash_paid float default 0 not null, tax_amount float default 0 not null, full_amount float default 0 not null, );