Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail full width admin
I have the following StructBlock sections = blocks.ListBlock( blocks.StructBlock( [("header", blocks.CharBlock()), ("content", blocks.RichTextBlock())] ) ) I am using the above block in my page admin as follows: content = StreamField( [("article_sections", blocks.ArticleSectionBlock())], null=False, blank=False ) content_panels = Page.content_panels + [StreamFieldPanel("content")] In the wagtail admin, this field is very narrow and hard to use: Is there a way to make it full width in the admin to provide more space to type? -
Import Error: sessionauthtoken.authentication.SesssionTokenAuthentication
Import error, What to install to run the code? ImportError: Could not import 'sessionauthtoken.authentication.SesssionTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. AttributeError: module 'sessionauthtoken.authentication' has no attribute 'SesssionTokenAuthentication'. -
How to manually select data from database in django?
I am trying to make a management system for a hospital. I have these two models: class Case(models.Model): user = models.ForeignKey(User,default=1,on_delete=models.CASCADE) symptoms=models.CharField(max_length=60) disease=models.CharField(max_length=30, blank = True) starting_date=models.DateField(default=now) last_visit=models.DateField(blank = True) def __str__(self): return str(self.user.first_name)+"\t"+str(self.last_visit) class Visits(models.Model): case = models.ForeignKey(Case,default=1,on_delete=models.CASCADE) medicine = models.CharField(max_length=50,blank=True) progress = models.CharField(max_length=20,blank=True) Date = models.DateField(default = now) test = models.CharField(max_length=50,blank=True) temperature = models.IntegerField(blank = True) bp = models.CharField(max_length = 6, blank = True) current_status = models.CharField(max_length=60) disease = models.CharField(max_length=30,blank=True) def __str__(self): return str(self.case_id) There can be many visits to a single case, further, a user can have many cases. The user should be able to select which case he wants to create the visit for. I have no idea how to do that. I can get all the cases of the user by: cases = Case.objects.filter(user = request.user) after that, how to manually be able to link a case to a visit? -
How can I use same database for two different projects one is my python based Desktop App and another is my django app. Could you please help me?
I have a single database which I want to for my both apps one is my Python based app and another is Django project. What will be the path for my Django project if I am doing so. My whole project structure is MAIN APP --KEY (PYTHON) --PACKAGE (PYTHON) --RESOURCES (PYTHON) --DJANGO PROJECT (DJANGO) --COMMON DATABASE(THIS IS MY DATABASE THAT I WANT TO USE FOR BOTH ABOVE PACKAGES) --MAIN.PY (FILE TO GENERATE DATABASE) For this what would be the Django database path. I am new to Django so don't have that much idea about database paths although I tried various things and searched on various places but not getting exact idea. Could you please help me? -
Time picker not working rendering on the HTML page, DJANGO 2.1
I am trying to show the time picker on the html and use that data in the form using django2.1. Unfortunately, I am only able to make the datefield work, not the time picker. Based on the example, can someone show me how to use it and make it work on the form, views and html? models.py class TimeSlot(models.Model): start_date = models.DateTimeField() stop_date = models.DateTimeField() forms.py class CreateTimeSlotForm(forms.ModelForm): start_time = forms.TimeField(widget=forms.TimeInput(attrs={'class':'timepicker'})) stop_time = forms.DateField(widget=forms.DateInput(attrs={'type':'date'})) class Meta: model = TimeSlot views.py def foo(request): if request.method == 'POST': form = CreateTimeSlotForm(data=request.POST or None) if form.is_valid(): form.save() else: form = CreateTimeSlotForm() context = { 'form': form, return render(request, 'core/list.html', context) html <div class="col-sm-3 ml-3 mb-5"> <form action="." method="post" class="order-form"> {% csrf_token %} {{ form.as_p }} </br> <button class="btn btn-primary" type="submit" value="Place order">Save & Close</button> </form> </div> Thank you for your help. -
Windows authentication with permissions (from ldap?) for a Django web application
I work for a company that has a number of web applications on the intranet. All of these apps are hosted on IIS servers and users who have access to these applications are auto logged in when they open these apps. I am writing a web application in Django which will be hosted on the intranet. Now, I can do LDAP authentication with django-ldap to query the Microsoft AD service and log in specific users or I can use the "REMOTE_USER" value set by IIS to log in users using their Windows account (RemoteAuthentication backend). However, I can't seem to set permission and roles or restrict users using the RemoteAuthentication backend. Is there any way to combine the above two? I would like my users to be auto logged in to the Django app using their windows account but only the users that should have access to the Django app and also set permissions. -
Stripe UI Component not rendering correctly in Django app
I'm following an outdated course titled 'Python eCommerce Build a Django eCommerce Web Application' the instructor is informative but a lot of the syntax is outdate, which has required me to research on how to implement features using the latest version django, bootstrap and currently stripe for the checkout page. I'm reading the guidelines for using Stripe's UI Component because so much has changed since the instructor recorded the section on implementing Stripe. The issue that I am trying to resolve is the Stripe Elements are not appearing in the browser, but when I use the browser's development tools to inspect I can see that the UI Component elements are populating. I read that "the address of the page that contains Elements must start with https:// rather than http://. " so I installed runserver_plus --cert-file cert.crt. Yet the UI Component Elements are still not appearing! Also, System check identified no issues. checkout.html {% extends 'base.html' %} {% block script %} <!-- Stripe.js v3 for Elements --> <script type="text/javascript"> const stripe = Stripe('pk_test_5555555555t6mx8z8U1uS00uTestHpU'); const elements = stripe.elements(); </script> {% endblock %} {% block content %} <form action="" method="post" id="payment-form" class="StripeForm">{% csrf_token %} <div class="form-row"> <label class="StripeLabel" for="card-element"> Credit or debit card … -
How to populate a related field on selection of a choice field in inline formset
I am working on an inline formset where: a. the user will be filling the header data first b. next while in the inline section, user selects a choice field (a product name) and I want this action to trigger filling other field/s with a value from a related table (FK relationship). The related field/s will have information like the pricing items in the related field. I want this to basically facilitate user acceptance (i.e. without having to click additional buttons). I have tried a few examples from the web (like populating the price field using a query) but I am unable to capture the user selection of product from the drop down list. Tried JQuery but I am not really able to get around. How do I achieve this? -
Django local dev server hangs with chrome after form submission. Works in firefox
Ok this is a strange one. Here is what I do to reproduce the problem (windows 10/python 3.7.1/django 2.5.5): Create a new virtual env with virtualenv-wrapper and 'mkvirtualenv' command Install Django in the virtual env using 'pip install django' Create a new Django project Migrate for first time to default sqlite database createsuperuser Run dev server Access 127.0.0.1:8000/admin via chrome Log in with superuser credentials I see a http post in the dev server console window. It looks like this: (default-users) C:\Users\kmfae\Documents\test\django-default-users>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 05, 2019 - 19:13:22 Django version 2.2.5, using settings 'defusers_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [05/Sep/2019 19:13:40] "GET /admin HTTP/1.1" 301 0 [05/Sep/2019 19:13:40] "GET /admin/ HTTP/1.1" 302 0 [05/Sep/2019 19:13:40] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1819 [05/Sep/2019 19:13:40] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [05/Sep/2019 19:13:40] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [05/Sep/2019 19:13:40] "GET /static/admin/css/responsive.css HTTP/1.1" 200 17944 [05/Sep/2019 19:13:40] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [05/Sep/2019 19:13:40] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [05/Sep/2019 19:13:40] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [05/Sep/2019 19:13:47] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 But in the chrome browser I don't get redirected … -
Filter list in Django when clicked on the option given
I am working on filtering the list (in this case it's displaying image based on the url in the database) when clicked on an option. And by this I mean I have a dropdown of character names, and by clicking on the option (name), it should return a list of displaying only the images of that certain character. I am fairly new to Django, still trying to understand the connection between urls, template and views. Any help or advice of which direction I should go for would be greatly appreciated, thanks! I have looked at the Django URL dispatcher documentation. And the URLconf example is something I'm aiming for, but I am not too sure how to pass in the value... https://docs.djangoproject.com/en/2.2/topics/http/urls/ I have also tried looking for example with filters, but it seems a lot of the filter others implemented are with entering the field, and filter based on the keyword entered. Template: {% block content %} <ul> <li><a href="#home">Home</a></li> <li class="dropdown"> <a href="javascript:void(0)" class="dropbtn">Characters</a> <form class="dropdown-content"> {% for c in character_name %} <a> {{ c.name }} </a> {% endfor %} {% endblock %} </div> </li> </ul> <div class="row"> {% for c in card_list %} <div class="column"> <div class="card"> … -
How to reference context specific processor dictionary items in a template via strings (using render_as_template)?
In Django, in my DB I've created string variables containing boilerplate HTML with dynamic URLs, and I can't quite get them to work in my templates. I'm using render_as_template so the dynamic URLs work. I tried custom template tags, but when I use those with render_as_template, it fails to load. I then tried a custom context processor. I created two functions in the context processor, one for hyperlinks, and one for tooltips. I got the tooltips processor to work, but I can only reference them in the template via their number in the auto-generated dict from the queryset. I did the same with the hyperlink processor, then tried modifying it to use string keys instead of integers, but it doesn't load all of the field. I must be missing something. custom_tags.py from django import template register = template.Library() @register.simple_tag def rdo_hyper(): value = Boilerplate.objects.filter(name='RDO').values_list('hyperlink',flat=True) return value[0] custom_context.py from myapp.apps.wizard.models import Boilerplate def boilerplate_hyperlink_processor(request): boilerplate_hyper = { "foo": Boilerplate.objects.filter(name='Aftermarket').values_list('hyperlink',flat=True), "bar": Boilerplate.objects.filter(name='Sights').values_list('hyperlink',flat=True) } return {'boilerplate_hyper': boilerplate_hyper} def boilerplate_tooltip_processor(request): boilerplate_tooltip = Boilerplate.objects.values_list('tooltip',flat=True) return {'boilerplate_tooltip': boilerplate_tooltip} template.html {% load static %} {% load custom_tags %} {% rdo_hyper as rdo_hyper %} {% load render_as_template %} ... <html> {% autoescape off %} 1. {% rdo_hyper %} … -
NoReverseMatch error. My URL is not a valid view function or pattern name despite having a URL and View associated with it
I am trying to make a form with an input button group that redirects the user to another URL given the button they pushed. I am currently receiving a NoReverseMatch when I don't think I should be. I went through the top answer of What is a NoReverseMatch error, and how do I fix it? but don't think those apply to me. The form in index.html: <form action="/main/community/" method="get"> <div class="btn-group" role="group" aria-label="Basic example"> <input type="button" class="btn btn-secondary" value='Comm1'> <input type="button" class="btn btn-secondary" value='Comm2'> <input type="button" class="btn btn-secondary" value='Comm3'> </div> </form> My URL's: app_name = 'main' urlpatterns = [ path('', views.Index, name='index'), path('community/', views.Community, name='community'), path('community/choice',views.CommView, name='CommView'), path('admin/', admin.site.urls) ] My views: def Community(request): try: pass except (KeyError): pass else: return HttpResponseRedirect(reverse('community/choice')) def CommView(request): return HttpResponse("Test success!.") When I press the buttons no redirect occurs. When I manually input the URL of /community/choice/ I receive the following error: NoReverseMatch at /main/community/ Reverse for 'community/choice' not found. 'community/choice' is not a valid view function or pattern name. -
Issue in uploading image file through test.py in DJango
Trying to populate a table having a column models.ImageField(upload_to='dataset/', blank=True) the directory dataset is created when I upload image. but after that 'OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect:' is throwing and the image is not saved in the directory 'dataset'. 'J:\BIOMETRICS\Student_projects\Biometric-ID-app\Biometric_App\biomteric_app\version 1.0 impl\biometric_app_root\media\dataset\C:' this is the url trying to create and throwing the error -
Multiple file uploads with Django form
I'm trying to write an app that can handle uploading multiple files at a time. I had the app working for a single file upload, but adding a loop to process a list of files hasn't worked yet. #models.py class image(models.Model): filename = models.CharField(max_length=100, blank=False, null=False) image = models.ImageField(upload_to='images/') uploaded_at = models.DateTimeField(auto_now_add=True) Form: class ImageForm(forms.ModelForm): class Meta: model = image fields = ('image',) widgets = {'image': forms.ClearableFileInput(attrs={'multiple':True}),} # Added to allow multiple file selections in one dialog box And relevant part of views.py: def image_upload(request): if request.method == 'POST': for f in request.FILES.getlist('image'): formI = ImageForm(request.POST, f, instance=image()) if formI.is_valid(): fs = formI.save(commit=False) fs.filename = f fs.user = request.user fs.save() (There's other stuff going on in the view, but it currently breaks before that). The result is the error: AttributeError: 'TemporaryUploadedFile' object has no attribute 'get' from the line: if formI.is_valid(): I originally had formI = ImageForm(request.POST, f, instance=image()) with request.FILES instead of f, and it seems likely that change is what's breaking this. What should I have instead of those two options? request.FILES results in only one image out of the selected being uploaded. What is the correct object to pass to ImageForm? Using Python 3.6.8 and Django 2.2.4 -
Django 2.2.5 'NoneType' object has no attribute 'lower' when performing Sum Distinct. Was working on Django 2.1.7
My application uses this rather simple model, to access data from an existing table: class Table01(models.Model): id = models.IntegerField(primary_key=True) fecha = models.DateField(blank=True, null=True) sucursal = models.IntegerField(blank=True, null=True) remito = models.IntegerField(blank=True, null=True) codcli = models.IntegerField(blank=True, null=True) razon = models.CharField(max_length=25, blank=True, null=True) domi = models.CharField(max_length=25, blank=True, null=True) turno = models.IntegerField(blank=True, null=True) codart = models.TextField(max_length=6, blank=True, null=True) canti = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) precio = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) tot = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = "TABLE01" app_label = "datatables" The backend for this database is SQLite With Django 2.1.7 and this model, my application was performing successfully the following query: sumrem = (Table01.objects.filter(fecha = some_date, turno = some_turno, codcli =some_customer).values("fecha", "turno", "sucursal", "remito", "razon") .annotate(Sum(F("tot"), distinct=True))) to get the distinct sum of the 'tot' field, which was working as expected on Django 2.1.7 When I upgraded to Django 2.2.5, this error appeared: Python 3.7.3 (default, Apr 3 2019, 05:39:12) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from .models import Table01 >>> from django.db.models import F, Sum, Count >>> sumrem = Table01.objects.filter(fecha='2019-05-10', turno=4, codcli=50).values("fecha", "turno", "sucursal", "remito", "razon").annotate(Sum(F("tot"), distinct=True)) Traceback (most recent call last): File "<console>", line 1, in … -
Docker Role for postgres doesn't exist with django
I'm running a docker container that takes a postgres database from another host. It looks like my docker compose file is connecting to the database but when i run docker exec -it container python manage.py makemigrations or docker exec -it container python manage.py createsuperuser i get 2019-09-05 23:25:33.553 UTC [29] FATAL: password authentication failed for user "postgres_user" db_1 | 2019-09-05 23:25:33.553 UTC [29] DETAIL: Role "postgres_user" does not exist. db_1 | Connection matched pg_hba.conf line 95: "host all all all md5" db_1 | 2019-09-05 23:26:27.289 UTC [30] FATAL: password authentication failed for user "postgres_user" db_1 | 2019-09-05 23:26:27.289 UTC [30] DETAIL: Role "postgres_user" does not exist. db_1 | Connection matched pg_hba.conf line 95: "host all all all md5" Here is the db portion of my docker compose file db: image: postgres environment: - POSTGRES_HOST=host_ip - POSTGRES_USER=postgres_user - POSTGRES_PASSWORD=bad_password - POSTGRES_DB=postgres_database - POSTGRES_PORT=5432 ports: - "5434:5432" volumes: - postgresql-data:/var/lib/postgresql/data restart: always Here is my db settings in my settings.py 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres_database', 'USER': 'postgres_user', 'PASSWORD':'bad_password', 'HOST': 'db', 'PORT': '5432', } } Running psql host_db_ip -U postgres_user -W works fine and I'm able to connect. I tried removed all docker images, containers, and systems and rebuilding everything. My guess … -
Django channels connect one client without browser
I implemented Django channels tutorial and it's working ok. I have a Django app and two clients connect to the same room correctly exchanging messages. Now I'm searching for a solution where one these clients to connect automatically and without using a browser. I want e.g. that such client replies automatically given a specific message and I need that such "calculation process" takes place from the client-side. Any idea how can I implement such a feature? -
Saving a celery task (for re-running) in database
Our workflow is currently built around an old version of celery, so bear in mind things are already not optimal. We need to run a task and save a record of that task run in the database. If that task fails or hangs (it happens often), we want to re run, exactly as it was run the first time. This shouldn't happen automatically though. It needs to be triggered manually depending on the nature of the failure and the result needs to be logged in the DB to make that decision (via a front end). How can we save a complete record of a task in the DB so that a subsequent process can grab the record and run a new identical task? The current implementation saves the path of the @task decorated function in the DB as part of a TaskInfo model. When the task needs to be rerun, we have a get_task() method on the TaskInfo model that gets the path from the DB, imports it using getattr, and another rerun() method that runs the task again with *args, **kwargs (also saved in the DB). Like so (these are methods on the TaskInfo model instance): def get_task(self): """Returns … -
zip on the fly files also made on the fly with python-django
I'm creating an excel file on the backend of my django app, it works but now i need to zip it before sending it back to download and i'm having problems using zipfile to do it The code for the excel works just great but is the zipping that is presenting some problems, it seems that i cant just simply put "write(output)" (output being an stringio file) output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output) sheet = workbook.add_worksheet() data = [[14, 11, 2], [48, 47, 63], [650, 89, 47]] for rownum, columns in enumerate(data): for colnum, cell_data in enumerate(columns): sheet.write(rownum, colnum, cell_data) workbook.close() output.seek(0) # Creating the zip file s = StringIO.StringIO() zf = zipfile.ZipFile(s, "w") zf.write(output) zf.close() resp = HttpResponse(zf, content_type = "application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=file.zip' return resp With this code i get the following error: coercing to Unicode: need string or buffer, instance found and when i use "output.getvalue()" i get: stat() argument 1 must be encoded string without null bytes, not str -
How to generate a Word document using Django
I'm new to Django and would like to create a form where users can input some data, and have a Word document be created for download. I was using the templated-docs library (https://pypi.org/project/templateddocs/) to accomplish this task, but I'm receiving an error. in my views.py: from templated_docs import fill_template from templated_docs.http import FileResponse def get_document(request): """ A view to get a document filled with context variables. """ context = {'user': request.user} # Just an example filename = fill_template('sample.odt', context, output_format='pdf') visible_filename = 'greeting.pdf' return FileResponse(filename, visible_filename) After the user inputs information in the form, I'm getting this error: get_template_sources() takes 2 positional arguments but 3 were given the error is produced from the variable that's in views.py: filename = fill_template('sample.odt', context, output_format='pdf') -
Django: order by and coalesce
What would be the Django equivalent of this query Comment.objects.raw('SELECT * FROM comments_comment where post_id=11 order by coalesce(parent_id, id), (case when parent_id is null then 1 else 2 end ), created_at') -
Admin side modification django
I have this class In which when I submit a name it goes to admin and only admin can approve this. I want that when admin approve a email automatically should be sent to user. class myab(models.Model): generic_name = models.CharField(max_length=50, null=False) timestamp = models.DateTimeField(auto_now_add=True) is_approved = models.BooleanField(null=False, default=False) I only wanted to know how to trigger email code . I have everything else just wanted to understand how to trigger that function when Admin will approve this post. -
How to Upload files in graphene-file-upload with apollo-upload-client to Python Database.?
I'm trying to upload a file to a django backend using graphene-file-upload which has the mutation to link the backend to the react frontend where I'm trying to use apollo-upload client to link it with graphql. In my django model an empty file is being successfully uploaded but it is not uploading the real file which I'm selecting but uploads an empty file. Like it uploads nothing {} but the instance is created in the database where another story is added which is empty. Here is some of my code. My Database Model. models.py class Story(models.Model): file = models.FileField(null=True) created_at = models.DateTimeField(auto_now_add=True) MY schema.py from graphene_file_upload.scalars import Upload class StoryType(DjangoObjectType): class Meta: model = Story class UploadFile(graphene.Mutation): story = graphene.Field(StoryType) class Arguments: file = Upload() def mutate(self, info, file): for line in file: print(line) story = Story(file=file) story.save() return UploadFile(story=story) My frontend File.js import React from 'react'; import { Mutation } from 'react-apollo'; import {withStyles} from '@material-ui/core/styles'; import gql from 'graphql-tag'; const styles = theme => ({ layoutRoot: {} }); const UploadFile = () => ( <Mutation mutation={gql` mutation($file: Upload!) { uploadFile(file: $file) { story { file } } } `} > {mutate => ( <input type="file" required onChange={({ target: … -
Django Wagtail: Is there any option to make wagtail fieldPanel disabled?
Another question concerning Wagtail admin. I have django model for received emails. I show these models in Wagtail using ModelAdmin. I would like to make this only read-only. A good solution would be possibility to disable Wagtail fieldPanels. But I can't find any info if that is possible. Only workaround so far seems to be register custom .js file inside ModelAdmin Class: my admin.py class EmailAdmin(ModelAdmin): model = Email menu_label = "Emails" menu_icon = "mail" menu_order = 300 add_to_settings_menu = False exclude_from_explorer = False empty_value_display = 'N/A' list_per_page = 10 index_view_extra_js = ["js/wagtail.js",] # extra .js code to disable fields list_display = ('subject', 'name_surname', 'phone', 'email', 'text_', 'date', 'sent', 'change_seen') I would like to ask you if there is some more native Wagtail way how to disable fieldPanels. -
Django: Dump data from models directly into a file
I used python manage.py dumpdata -a --format yaml to output it as yaml which is okay, but how would I do it if I want it in a file that I can keep and use again if necessary?