Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Retain Filter and Export/Download data to csv/xlsx
I would like with a click of a button in the template to export the current selected records to a .csv file. Here's my partial template that includes the form elements: <form method="get"> <p>{{ summary_filter.form }} <button type="submit">Search</button></p> <button type="submit" name="period" value="current_month" class="btn btn-sm btn-outline-secondary"> Current Month </button> <button type="submit" name="period" value="last_month" class="btn btn-sm btn-outline-secondary"> Last Month </button> <button type="submit" name="period" value="current_qtr" class="btn btn-sm btn-outline-secondary"> Current Quarter </button> <button type="submit" name="period" value="last_qtr" class="btn btn-sm btn-outline-secondary"> Last Quarter </button> <button type="submit" name="export_data" value="export_data" class="btn btn-sm btn-outline-secondary"> Export messages </button> </form> Here's my view for this particular page: def summary(request): """ Summary page - Displays summary of data by day in tables """ all_messages = Message.objects.all() summary_filter = SummaryFilter(request.GET, queryset=all_messages) if request.GET: filter_messages = summary_filter.qs messages = data_filter(request.GET.get('period'), filter_messages) else: messages = data_filter("current_month", all_messages) df = pd.DataFrame.from_records(messages.values()) filename = "message_export.csv" sio = io.BytesIO() sheetname = "Messages" PandasWriter = pd.ExcelWriter(sio, engine='xlsxwriter') df.to_excel(PandasWriter, sheet_name=sheetname) PandasWriter.save() sio.seek(0) workbook = sio.getvalue() response = StreamingHttpResponse(workbook, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response For example, I filter to 'Current Quarter' by clicking on the current_qtr button. The page displays correctly filtered. I'd then like to click on the 'export data' button retaining the current quarter (and … -
Vue + Django rest: cant upload image with axios
Im trying to send post request from vue to my api based on DRF. Everything works well with get and post json requests. If im trying to send form with file inside, i get some errors like The submitted data was not a file. Check the encoding type on the form? or 415 Unsupported Media Type . I tryed to fix it with FormData and enctype="multipart/form-data" in header of form and in axios request, i setup MultiPartParser in my viewset, but DRF still gives me an error: Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/andrey/.local/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 65, in __call__ return self.application(environ, start_response) File "/home/andrey/.local/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 141, in __call__ response = self.get_response(request) File "/home/andrey/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/home/andrey/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/home/andrey/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/andrey/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/andrey/.local/lib/python3.6/site-packages/django/views/debug.py", line 91, in technical_500_response text = reporter.get_traceback_text() File "/home/andrey/.local/lib/python3.6/site-packages/django/views/debug.py", line 340, in get_traceback_text c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) File "/home/andrey/.local/lib/python3.6/site-packages/django/views/debug.py", line 305, in get_traceback_data 'filtered_POST_items': list(self.filter.get_post_parameters(self.request).items()), File "/home/andrey/.local/lib/python3.6/site-packages/django/views/debug.py", line 177, in get_post_parameters return request.POST File "/home/andrey/.local/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 110, in … -
How can I get my bokeh map to appear on my Django application
i have been using the jupyter notebook to make some visualisations using my csv file. i need to be able to show this map on my django web app but have no idea how to go about that. I have tried putting the code into my views file and rendering this to my html file but i dont know how to use my csv file in this case. import bokeh import pandas as pd from bokeh.io import output_notebook, show from bokeh.plotting import figure from bokeh.models import ColumnDataSource, HoverTool from bokeh.transform import linear_cmap from bokeh.palettes import Spectral6, RdYlGn, viridis, Plasma256, RdYlGn10, YlOrRd4, Reds9 from bokeh.tile_providers import CARTODBPOSITRON_RETINA from pygeotile.point import Point output_notebook() %matplotlib inline pred = r'path' pred = pd.read_csv(pred) for index, row in pred.iterrows(): point = Point.from_latitude_longitude(latitude=row['Latitude'], longitude=row['Longitude']) pred.at[index,'x'] = point.meters[0] pred.at[index,'y'] = point.meters[1] pred.at[index,'size'] = 15 # int(row[bnf]/100) p = figure(plot_width=900, plot_height=400, x_axis_type="mercator", y_axis_type="mercator", x_range=(-928267, -573633), y_range=(7168390, 7422161)) p.add_tile(CARTODBPOSITRON_RETINA) mapper = linear_cmap(field_name='type', palette=Spectral6,low=0 ,high=1) source = ColumnDataSource(pred_crime) p.circle(x='x', y='y', source=source, size='size', fill_color=mapper, line_alpha=0.5, line_color='black') p.add_tools(HoverTool(tooltips=[("type","Type")])) show(p) i want to know where to put these files and what i need to change to get it working in pycharm -
Stop Django translating times to UTC
Timezones are driving me crazy. Every time I think I've got it figured out, somebody changes the clocks and I get a dozen errors. I think I've finally got to the point where I'm storing the right value. My times are timestamp with time zone and I'm not stripping the timezone out before they're saved. Here's a specific value from Postgres through dbshell: => select start from bookings_booking where id = 280825; 2019-04-09 11:50:00+01 But here's the same record through shell_plus Booking.objects.get(pk=280825).start datetime.datetime(2019, 4, 9, 10, 50, tzinfo=<UTC>) DAMMIT DJANGO, IT WASN'T A UTC TIME! These times work fine in templates/admin/etc but when I'm generating PDF and spreadsheet reports, this all goes awry and I'm suddenly have to re-localise the times manually. I don't see why I have to do this. The data is localised. What is happening between the query going to the database and me getting the data? I bump into these issues so often I have absolutely no confidence in myself here —something quite unnerving for a senior dev— so I lay myself at your feet. What am I supposed to do? -
Django: import data from CSV - tuple indices must be integers or slices, not str
In my Django APP I'd like to upload data to a model from a CSV. For reading the data I'm using pandas library. But I'm getting this error: File "D:\web_proyects\stickers-gallito-app\shop\management\commands\categories.py", line 23, in for row in tmp_data_categories.iterrows() TypeError: tuple indices must be integers or slices, not str I'm thinking is it because of how I've formulated my for loop, to read the data. models.py: class Category(models.Model): category = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True, null=True) video = EmbedVideoField(null=True, blank=True) class Meta: ordering = ('category',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('shop:allCat', args=[self.slug]) def __str__(self): return '{}'.format(self.name) commands/categories.py: import pandas as pd import csv from shop.models import Category from django.core.management.base import BaseCommand tmp_data_categories=pd.read_csv('static/data/categories.csv',sep=',', encoding="utf-8") class Command(BaseCommand): def handle(self, **options): categories = [ Category( category=row['category'], slug=row['product'], subcategory=row['slug'], subcategory_slug=row['description'], description=row['size'], image =row['quantity'], video=row['image'], ) for row in tmp_data_categories.iterrows() ] Category.objects.bulk_create(categories) I'm getting the error when calling: python manage.py categories -
Error running django app on httpd using mod_wsgi
Error log: [client 10.10.10.220] mod_wsgi (pid=11514): Target WSGI script '/opt/<project-name>/<app-name>/wsgi.py' cannot be loaded as Python module. [Tue Apr 09 11:06:39 2019] [error] [client 10.10.10.220] mod_wsgi (pid=11514): Exception occurred processing WSGI script '/opt/<project-name>/<app-name>/wsgi.py'. [Tue Apr 09 11:06:39 2019] [error] Traceback (most recent call last): [Tue Apr 09 11:06:39 2019] [error] File "/opt/<project-name>/<app-name>/wsgi.py", line 10, in <module> [Tue Apr 09 11:06:39 2019] [error] import os [Tue Apr 09 11:06:39 2019] [error] ImportError: No module named os httpd.conf: WSGIScriptAlias / /opt/<project>/<app>/wsgi.py WSGIPythonHome /opt/<project>/venv WSGIPythonPath /opt/<project> <Directory /opt/<project>/<app> <Files wsgi.py> Allow from all </Files> </Directory> Used: Python 3.6 with virtualenv Django 2.1 -
How to design an elearning platform database schema
Am i structuring my database schema properly? (POSTGRESQL) I need to design an online learning database schema where there is : 1/ a list of 'type of courses' (eg. Python) 2/ a list of 'course' based on each type. (eg. Tuples, Lists) 3/ for each course, there will be two sections : * questionnaire * additional information class Profile(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female') ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birthday = models.CharField(max_length=10, blank=False) location = models.CharField(max_length=50, null=True, blank=True) gender = models.CharField(choices= GENDER, max_length=10, default='Male') phone_number = models.CharField(max_length=10) position = models.CharField(max_length=30) created = models.DateTimeField(auto_now_add=True, auto_now=False) class Course(models.Model): name = models.CharField(max_length=20) user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='typecourses') slug = models.SlugField() description = models.TextField(max_length=500) number_of_courses = models.IntegerField() class Module(models.Model): name = models.CharField(max_length=20) courses = models.ManyToManyField(Course, related_name='courses') slug = models.SlugField() description = models.TextField(max_length=500) is_completed = models.BooleanField(default = False) date_completed = models.DateTimeField(auto_now_add=True) class Questionnaire(models.Model): name = models.TextField(max_length=500) **number_of_questions modules = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='questionnaire') class AdditionalInformation(models.Model): name = models.TextField(max_length=500) **Additional Information modules = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='additional_info') ** used because there are many questions. just a placeholder. Any help would be much appreciated. -
how can I generate swagger server for Django rest Api
I need to generate django server from swagger specs I need to generate django server from swagger specs -
Reference Many-to-Many Field with Django-Datatables-View
I have a Django view created with django-datatables-view: class ActivityListJson(BaseDatatableView): columns = ['description', 'entities'] order_columns = ['description', 'entities'] max_display_length = 500 def get_initial_queryset(self): return Activity.objects.all().prefetch_related('entities') def prepare_results(self, qs): data = [] for item in qs: entities = [] for entity in item.entities.all(): entities.append(entity.entityDescription) entities = ''.join(entities) data.append([item.description, entities]) return data With the entity for loop in prepare_results(), I am able to show the list of entities in the DataTable. However, I am running into Related Field got invalid lookup: errors. I think I may need to call the column something different in the columns list. Here are my models: class Entity(models.Model): entity = models.CharField(primary_key=True, max_length=25) entityDescription = models.CharField(max_length=400) def __str__(self): """ Returns default string representation of Entity. """ return '%s - %s - %s' % (self.entity, self.entityDescription) class Activity(models.Model): description = models.CharField(max_length=500) entities = models.ManyToManyField(Entity, related_name='entities') How should I adjust the view to properly reference the M2M field? Ideally, I would also get the string representation __str__ of Entity rather than just the entityDescription field. -
How do i specify SSL mode in my Settings.py
I'm trying to set up my project in Production. I'm currently getting an error "ERROR: pgbouncer cannot connect to server ERROR: SSL required". I've gone ahead to include the mode in my settings file but still doesn't resolve the issue. My current Settings.py looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DBName', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'xxx.xxx.xxx', 'PORT': '6543', 'server_tls_sslmode': 'Require', } } -
problem in using unique_together and saving authenticated user
There is a problem in my code for two fields entry uniqueness checking. I defined a model with unique_together to check uniqueness of a field records for each user, but it accepts duplicated entry added by that user. ''' model.py from django.db import models from django.contrib.auth.models import User class UserItem(models.Model): definer = models.ForeignKey(User, on_delete=models.CASCADE) item_name = models.CharField(max_length=50) . . class Meta: unique_together = ("definer", "item_name") ''' '''views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic.edit import CreateView, UpdateView, DeleteView class RecordCreateView(LoginRequiredMixin, CreateView): model = UserItem template_name = 'item_new.html' #excluding "definer" field and inserting its value by form_valid fields = ['item_name', . . .] def form_valid(self, form): form.instance.definer = self.request.user return super().form_valid(form) ''' I expect warning and preventing users to add new record with the same "item_name" added before by themselves, but it accepts them (without warning). When I replace "definer" with other fields, it works fine and warns for duplicate records. Additionally when records added by admin, it works and there will be the expected warning. I guess, this problem is for that the authenticated user is inserted as "definer" by "def form_valid" after the "unique_together = ("definer", "item_name")" did its role. On the other hand, uniqueness check in done when … -
Django models, referencing and storing model id
I have a model by name Order, I want to create and invoice_number field on this same model and store order id and some other generated text to make up order invoice_number and I can't figure it out, I think there is a short and neat way to achieve this and I will appreciate any help Thanks. This code throws and error that self is not defined here is my code import datetime YEAR = datetime.datetime.today().year class Order(models.Model): customer_contact = models.IntegerField() paid = models.BooleanField(default=False) date = models.DateTimeField(auto_now=True) salesman = models.CharField(db_index=True, max_length=20) discount = models.IntegerField(default=0) price = models.IntegerField(default=0) customer_name = models.CharField(db_index=True, max_length=20) apartment_name = models.CharField(db_index=True, max_length=20) flat_number = models.IntegerField() invoice_number = models.CharField(max_length=20, default=f'{YEAR}/INV/000{self.pk}') -
Optimize saving and reading django mysql objects
I have a django app that continuously receives updates of clients and reads data from the database. I have noticed that after saving an object my application is much slower reading the database. I am using django, python and mysql. I have used the django debug toolbar to monitor the time it takes to process these events and this what I have seen: INSERT INTO `manager_readmodel` (`timestamp`, `index`, `value`) VALUES ('2019-04-09 15:25:56', 0, 7777) [3.00ms] INSERT INTO `manager_readmodel` (`timestamp`, `index`, `value`) VALUES ('2019-04-09 15:25:56', 1, 7777) [4.01ms] INSERT INTO `manager_readmodel` (`timestamp`, `index`, `value`) VALUES ('2019-04-09 15:25:56', 2, 7777) [0.73ms] INSERT INTO `manager_readmodel` (`timestamp`, `index`, `value`) VALUES ('2019-04-09 15:25:56', 3, 7777) [1.75ms] SELECT `manager_readmodel`.`id`, `manager_readodel`.`timestamp`, `manager_readmodel`.`index`, `manager_readmodel`.`value` FROM `manager_readmodel` WHERE `manager_readmodel` ORDER BY `manager_readmodel`.`timestamp` DESC, `manager_readmodel`.`index` ASC LIMIT 4 [451.36ms] This is my code: value = 1 #example for i in xrange(1, 5): insert_list.append(models.ReadModel( timestamp=local_time, index=i, value=value )) models.ReadModel.objects.bulk_create(insert_list) # # # # readings = readings.all().order_by('-timestamp', 'index')[:4] reading_values = [] for i, r in enumerate(readings): reading_values.append(r.value) However if I do the reading a few seconds later than the saving I get this: SELECT `manager_readmodel`.`id`, `manager_readodel`.`timestamp`, `manager_readmodel`.`index`, `manager_readmodel`.`value` FROM `manager_readmodel` WHERE `manager_readmodel` ORDER BY `manager_readmodel`.`timestamp` DESC, `manager_readmodel`.`index` ASC LIMIT 4 [0.89ms] Is … -
Django Test is working with manage.py app test but not with manage.py test
I've written a TestCase for checking my view which needs a Teacher-Object. class ShowTeacherViewTest(TestCase): @classmethod def setUpTestData(cls): gender = Gender.objects.create(gender='Male') gender_id = gender.id Teacher.objects.create( gender_id=gender_id, first_name='Maria', last_name='Santana',) def test_view_uses_correct_template(self): teacher = Teacher.objects.first().id response = self.client.get(reverse('get_student'), {'teacher': teacher}) self.assertEqual(response.status_code, 200) When I am running 'manage.py test app' it all works perfect. If I'm running 'manage.py test' this Error disapears: self.model._meta.object_name students.gender.Gender.DoesNotExist: Gender matching query does not exist. I am using these teacher objects also in other models-tests because of some foreign keys. So, is it possible or neccesary to reset the test_db before every test? -
Show plotly chart in django
I create a graph in jupyternotebook and converted into html file, when I try to use in django as a template view I get this error Could not parse the remainder: '(['plotly'],function(plotly) {window.Plotly=plotly;});' from 'require(['plotly'],function(plotly) {window.Plotly=plotly;});' -
Django all auth: How to override the confirmation email url
What I want to do is to override confirmation email url in templates/account/email/email_confirmation_message.txt. I want to change this part To confirm this is correct, go to {{ activate_url }} to something like http://localhost:8080/confirm_email/{{ key }} so that the user can go to the page on frontend and then send the key to the endpoint on backend. However, I couldn't figure out where {{ activate_url }} comes from. I want to send the key to the endpoint made by rest-auth. How can I rewrite the url link on email? Or if it's too complitcated, what is the easy way to verify the email on frontend? -
How to get a INT or STR from VAR with function return?
I'm getting the user ID and I need this in INT format, but I only get with function return. How to convert from function to INT? I'm using Django 2.1.7 and python 3.7. from django.contrib.auth import authenticate from django.http import HttpRequest request=HttpRequest username='myuser' password='mypass' user = authenticate(username=username, password=password) def user_id(request): UID = request.user return(UID) UID=user_id print(type(UID)) <class 'function'> print(UID) <function user_id at 0x106cd9158> print(user.id) 19 -> I need this. But its not work when its called from Django HTTP. -
How to allow cors header with Django 1.7 for POST API
Im using Django 1.7 and restframework to generate API usable with angular 7, i have added the package cors header to allow the consumption of the API, the problem that it works only with GET API, but with POST it doesnt work, im getting this error : from origin **** has been blocked by CORS policy MIDDLEWARE_CLASSES = ( "MyHotel.middleware.GlobalRequestMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) CORS_EXPOSE_HEADERS = ( 'Access-Control-Allow-Origin: *', ) CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True -
Django filtering queryset based on input from URL
I am trying to get an API endpoint api/v1/device-groups/?customer=<customer_uuid> which returns the device groups related to the customer_uuid given in the URL but am not sure how to create this. models.py class Customer(models.Model): customer_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customer_name = models.CharField(max_length=128, unique=True) class DeviceGroup(models.Model): group_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customer_uuid = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) device_group_name = models.CharField(max_length=20) color = models.CharField(max_length=8) is_default = models.BooleanField(default=False) serializers.py class CustomerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Customer fields = ('customer_name', 'customer_uuid') class DeviceGroupSerializer(serializers.HyperlinkedModelSerializer): customer = CustomerSerializer(many=False, read_only=True, source='customer_uuid') class Meta: model = DeviceGroup fields = ('device_group_name', 'group_uuid', 'color', 'is_default', 'customer') I am not sure what I should do in my views.py and urls.py urls.py router = routers.DefaultRouter() router.register(r'device-groups', views.DeviceGroupViewSet, base_name='device-groups') urlpatterns = [ url(r'api/v1/', include(router.urls)), ] My views.py that returns all device groups related to this customer_uuid upon a GET request to /api/v1/device-groups/?customer_uuid=0bc899e9-4864-4183-8bcd-06937c572143/ class DeviceGroupViewSet(viewsets.ModelViewSet): serializer_class = DeviceGroupSerializer queryset = DeviceGroup.objects.filter(customer_uuid='0bc899e9-4864-4183-8bcd-06937c572143') I tried to override get_queryset like this, but it results in a KeyError views.py class DeviceGroupViewSet(viewsets.ModelViewSet): serializer_class = DeviceGroupSerializer def get_queryset(self): return DeviceGroup.objects.filter(customer_uuid=self.kwargs['customer_uuid']) What do I need to change to get an API endpoint /api/v1/device-groups/?customer=<customer_uuid>/ that returns filtered device groups? -
how to save the changes into docker
I currently have this image, that I'm pulling like this docker-compose up -d I'm then running a bunch of django scripts to make the image up-to-date namely python manage.py migrate and then python manage.py createsu and finally python manage.py runserver. However, each time I'm shutting down the image by doing a docker-compose down, all the changes are not applied. What can I do to save all the changes and to run the same image with the applied changes next time? -
Get file params (size, filename) in django rest framewrok
I need to get file params in my rest api. Model: class Movie(models.Model): title = models.CharField(max_length=100) attachment = models.FileField(upload_to='files/courses/', default=None, blank=True, null=True) def __str__(self): return self.title Serializer: class MovieSerializer(serializers.ModelSerializer): attachment = serializers.FileField() class Meta: model = Movie fields = ('title','attachment') View: class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer When I do GET request, I get the title, and file url, But I wnat to get also file size, and file name. How to do that? -
Django, html template, POST submit form not working
The 'Submit' button in this form, in this Django project, does not seem to do anything. I cannot spot the logic error in the code or files. sign.html (this is the page that displays). On clicking the submit button, it does nothing, but it should populate the database. {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'guestbook/styles.css' %}"> </head> <body> <h1>Tell the world how you're doing!</h1> <h2>Sign the guestbook</h2> <form class="form-signin" method="POST" action="{% url 'sign' %}"> {% csrf_token %} Enter your name:<br> <!--<input type="text" name="name" placeholder="Your Name here">--> {{form.name}} <br> Enter your comment:<br> <!--<textarea name="message" type="Textarea" placeholder="Your comment here" rows="10" cols="30"></textarea>--> {{form.comment}} <br><br> <input type="button" value="Submit"> </form> <p>Go to the <a href="{% url 'index' %}"> guestbook </a> itself</p> </body> </html> I suspect the problem is in the code below or possibly in the views.py file, but as it is not throwing any exceptions I cannot find it. It is the sign function below that is the relevant one to this question. views.py from django.shortcuts import render from .models import Comment from .forms import CommentForm # Create your views here. def index(request): comments = Comment.objects.order_by('-date_added') context ={'comments': comments} #name=Name.objects.order_by('-date_added') #return render(request,'guestbook/index.html') return render(request,'guestbook/index.html', context) def sign(request): if … -
Django display list of ForeingKey relationship
I'm using django 2 and python 3. In my model I have Users that can own a list of Applications. Applications can have only one Owner. I used a ForeingKey like so: class User(AbstractUser): # nothing interresting for this question here pass class StoreApplication(models.Model): owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name="applications" ) Now I would like to list the User's applications in the User's admin page, like a list of application names, just readonly stuff. Not in the list view, in the edit view. I'm aware of InlineModelAdmin and it does not seem to resolve my issue, as it includes the whole Application forms for each of the user's application. If I try to reference the field as "applications" in my user admin: class UserAdmin(admin.ModelAdmin): list_display = ("username", ) fieldsets = ( ("Général", { "fields": ("username", "applications", ) }), ) An error occurs: Unknown field(s) (applications) specified for User. Check fields/fieldsets/exclude attributes of class UserAdmin. -
Exporting dynamic table data using Django
I have a table generated by a screenscraping code which works perfectly. I have also added filters to this table (search bar, dropdown, and show entries limit). In addition, I have just added an export button which works when clicks and transfers all table data into a csv. The only negative is that the export button will export the entire table even if a filter is on. For example, if I set the dropdown to show only males in my table and limit the results to 10 per page, the export button will just export the entire table. I have searched for a while here but have not found a solution. Send help. this is my html as is <div class="table-responsive-sm"> <h2>The Law Society Solicitors</h2> <p>This is a table of the output of The Law Society Web Scraping Code: Juan S. Gonzalez Jr.</p> <div style="float:left" class= "col-sm-2"> <input class="form-control" id="Input" type="text" placeholder="Search..."> </div> <div class="table-title"> </div> <div id="show" style="float:right" class="table-filter"> <div class="col-lg-2"> <div class="show-entries"> <span>Show results</span> <select class="form-control" name="limit" id="maxRows"> <option value="5000 ">Full Table</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> </select> </div> </div> </div> <center> <div class="col-sm-3"> <div class="filter-group"> <label>Desired Role</label> <select id="mylist" onchange="myFunction()" class="form-control" > <option>None</option> <option>Assistant</option> <option>Associate</option> <option>Compliance … -
password authentication failed for user "born" using postgres in django project
“I'm migrating the database to the new database i created using postgresql, and it's bringing an error in my web application that the password authentication failed for user "born". Where did i go wrong” This is the server running python 2.7, php 5, postgres 9.5, django 2.1.7. In mywebsite/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'woman', 'USER': 'born', 'PASSWORD': 'secret', 'HOST': 'localhost', 'PORT': '', } } "I accepted the result to display the migrated tables, but the actual output is that the password authentication failed for user "born"