Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ibm_db_dbi::ProgrammingError: Cursor cannot be closed; connection is no longer active
I am new with django and I am trying to set up db2 with it. I am following the documentation's steps in order to get this done. The database connection was done successfully but when I try to do this: (myproject) C:\Users\myuser\mysite>py manage.py shell (InteractiveConsole) >>> from polls.models import Choice, Question # Import the model classes we just wrote. # No questions are in the system yet. >>> Question.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\sql\compiler.py", line 1136, in execute_sql cursor.close() File "C:\Users\myuser\Envs\myproject\lib\site-packages\ibm_db_dbi.py", line 1145, in close raise self.messages[len(self.messages) - 1] ibm_db_dbi.ProgrammingError: ibm_db_dbi::ProgrammingError: Cursor cannot be closed; connection is no longer active. I appreciate any help on this. Thanks in advance. I have tried to install ibm_db 3.0.1 and early versions and I get the same error. I have installed: python 3.7.4, django 2.2, ibm_db_django 1.2.0.0 and ibm_db 3.0.0 I expect this: # No questions are in the system yet. >>> Question.objects.all() <QuerySet []> -
How to avoid race conditions on celery tasks?
Considering the following task: @app.task(ignore_result=True) def withdraw(user, requested_amount): if user.balance >= requested_amount: send_money(requested_amount) user.balance -= requested_amount user.save() If this task gets executed twice, at the same time, it would result in an user with a negative balance... how can I solve it? It is just an example of race, but there are lots of situations like this in my code.. -
How to save data in the table to database using Django?
I use Django 2.1 and Python 3.7. I have some data in a table: <table class="table" border="1" id="tbl_posts"> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody id="tbl_posts_body"> <tr id="rec-1"> <td><span class="sn">1</span>.</td> <td><INPUT type="text" name="txt1" value="Name"/></td> <td><INPUT type="text" name="txt2" value="0"/></td> <td><a class="btn btn-xs delete-record" data-id="1"><i class="glyphicon glyphicon-trash"></i></a></td> </tr> </tbody> </table> A user can edit it and has to save it to the database in Django. How can I do it? I am a beginner in Django. Can I do it using form or ajax or any other suggestions. But I want to keep this structure. -
<hr> below each three <div>s
I'm trying to put a <hr> below each three <div>s (one <hr> per three <div>s), however I'm getting unexpected results. I came to the conclusion that I have to put a <hr> below each third <div>, but when I do that, it is not positioned correctly (see the demo). I am using this Django template: {% extends 'pages/base.html' %} {% load static %} {% block cssfiles %} <link rel="stylesheet" href="{% static 'products/css/list.css' %}" /> {% endblock %} {% block jsfiles %} <script type="text/javascript" src="{% static 'products/js/ellipsis.js' %}" defer></script> {% endblock %} {% block content %} {% for product in products %} <div class='product'> <div class='product-title'><a href="{{ product.get_absolute_url }}">{{ product.title }} ({{ product.year }})</a></div> <hr class='product-separator'> {% if product.image %} <div class='product-image'> <img src='{{ product.image.url }}' width='100' height='100'> </div> {% endif %} <p class='product-price'>${{ product.price }}</p> </div> {% if forloop.counter|add:1|divisibleby:3 %} <hr> {% endif %} {% endfor %} {% endblock %} Here is the jsfiddle link. -
bash script for docker permission denied in django project
I am learning docker and implemented docker in my Django project, currently, it is working great! no issue at all Now I am trying to make some command easy to run, that is why I write a shell script. coz, I am bored writing this too long command: docker-compose run web python /code/manage.py migrate --noinput docker-compose run web python /code/manage.py createsuperuser and more like above, to avoid writing long-lined command, i just wrote a shell script and this below: manage.sh is shell script file #!/bin/bash docker-compose run web python /code/manage.py $1 and later I tried to use my manage.sh file to migrate like ./manage.sh migrate Bit terminal throws me an error that is bash: ./manage.sh: Permission denied I am not getting actually what's wrong with it even I tried with sudo I believe if you are a docker expert, you can solve my problem. can you please help me in this case? -
Why isn't Django URL converter type working?
I am trying to write a unit test that will test a URLconf that follows Django's latest simplified URL routing syntax. This syntax allows the captured value to include a converter type. But what I've found is that the converter type doesn't seem to be working. Here is the URLconf I want to test: urlpatterns = [ path('club/<int:club_id>/', login_required(views.show_club), {'template': 'show_club.html'}, name='show-club'), ... ] As you can see, I want to pass the club ID as an integer. Now here is my test: class TestURLs(TestCase): def test_show_club(self): path = reverse('show-club', kwargs={'club_id': 10}) match = resolve(path) assert match.view_name == 'show-club' assert 'club_id' in match.kwargs assert match.kwargs['club_id'] == 10 When I run this test, I get an assertion error on the third assert: File... in test_show_club assert match.kwargs['club_id'] == 10 AssertionError If I insert a set_trace in my code and examine the match variable, I can see that the assertion is failing because the club_id key contains a string value of '10': ResolverMatch(func=activities.views.show_club, args=(), kwargs={'club_id': '10', 'template': 'show_club.html'...}) If my converter type is <int:club_id>, shouldn't kwargs['club_id'] contain the integer value 10 instead of the string '10'? I also inserted a set_trace in my code and then ran the code through that view. … -
Refresh from DB keeps OneToOneField Relation
I have a simple model relation: class Foo(models.Model): bar = models.OneToOneField(Bar) Say I do the following: >>> bar = Bar.objects.create() >>> foo = Foo.objects.create(bar=bar) >>> Foo.objects.all().delete() >>> bar.foo is None False This is expected because bar is still referencing the foo object. But now when I try to get a fresh copy of bar from the DB, i.e. without the related foo, I tried: >>> bar.refresh_from_db() >>> bar.foo is None False Why does foo not come back as None? I see that in the docs it says that only fields of the model are reloaded from the database when using refresh_from_db(). Does foo not count as a field of bar in this case? -
javascript snippet not working in django template
it's been a while since I did Django and I found an example of calling a view from a button that I needed: How do I call a Django function on button click? I built my template to match the example given: <html> <head> <title>Tournament Registration</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> function register() { alert("Hi") } </script> </head> <body> <p>{{ tournament.name }}</p> <p>Start time: {{ tournament.start_time }}</p> <button onclick="register">Register</button> </body> </html> At first I just wanted it to pop an alert box so I know it's working at all. When I click the button however, nothing happens, and I get no error message in console. Are you able to call script tags in a Django template, or am I doing something else wrong here? Thank you -
How to link and update several Django models with a Foreignkey
I'm trying to make a link between two models, for achieve this I'm using several Foreignkey. Everything works fine until I delete one object of Url_lb. It seems Django can't update his table index and stuck whith a past index of Url_lb class Url_lb(models.Model): url = models.URLField(max_length=500) name = models.CharField(max_length=300) headers = models.TextField(max_length=3000) payload = models.TextField(max_length=3000) user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) state_item = models.BooleanField(default=True) def __str__(self): return self.url class Scrapper(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=300) url = models.URLField(max_length=300) image = models.URLField(max_length=300, default='.....') price = models.IntegerField(default=0) date = models.DateTimeField(auto_now=False) user = models.ForeignKey(User, on_delete=models.CASCADE) state_item = models.ForeignKey(Url_lb, on_delete=models.CASCADE) def __str__(self): return self.name I understand that the ID of Url_lb is never the same, but I don't understand why the table didn't update itself after an event like deleting an object... Error Display in Django server : db_1 | 2019-09-13 15:03:33.216 UTC [179] ERROR: insert or update on table "scrapper_scrapper" violates foreign key constraint "scrapper_scrapper_state_item_id_f11f58e2_fk_scrapper_url_lb_id" db_1 | 2019-09-13 15:03:33.216 UTC [179] DETAIL: Key (state_item_id)=(1) is not present in table "scrapper_url_lb". db_1 | 2019-09-13 15:03:33.216 UTC [179] STATEMENT: INSERT INTO "scrapper_scrapper" ("id", "name", "url", "image", "price", "date", "user_id", "state_item_id") VALUES (477944121, 'Chapeau ****', 'https://***.****', 'https://******', 1, '2019-09-13T17:03:18'::timestamp, 1, 1) Error … -
Deploy sentry helm in kubernetes cluster
I have deployed sentry on kubernetes last week, using this helm chart stable/sentry. Pods work fine but i cannot access to the website, it crash every time I access to the endpoint. I checked logs of the worker, sentry-web and postgres pods and see this. This is logs of the website pod: self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/sentry_sdk/integrations/django/__init__.py", line 396, in execute return real_execute(self, sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 80, in inner raise_the_exception(self.db, e) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 78, in inner return func(self, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 22, in inner return func(self, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 101, in inner six.reraise(exc_info[0], exc_info[0](msg), exc_info[2]) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 94, in inner return func(self, sql, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/base.py", line 74, in execute return self.cursor.execute(sql, clean_bad_params(params)) django.db.utils.ProgrammingError: ProgrammingError('relation "sentry_projectkey" does not exist\nLINE 1: ...te_limit_window", "sentry_projectkey"."data" FROM "sentry_pr...\n ^\n',) SQL: SELECT "sentry_projectkey"."id", "sentry_projectkey"."project_id", "sentry_projectkey"."label", "sentry_projectkey"."public_key", "sentry_projectkey"."secret_key", "sentry_projectkey"."roles", "sentry_projectkey"."status", "sentry_projectkey"."date_added", "sentry_projectkey"."rate_limit_count", … -
How to define a field that automatically takes the mean of all the data of another integer field of the model of which it is foreign key?
I want this field to be predefined, and automatically calculate the average of all integer data in the field of which it is a foreign key. Exemple : class Product (models.Model): title = CharField(...) #this field set automatically the average, and also update after #adding new price_average = FloatField(...) class ProductItem (models.Model): title = CharField(...) price = IntegerField(...) _product = ForeignKey(Product) is it possible in this way or do I have to implement a method that does it automatically in the background? -
I am getting an error whenever I import forms in the models.py file
So basically, I am making a website where users can upload posts, with images in them. In my models.py file, I have a bit of code where I need a forms.py thing, so in the top of the models.py file, I imported the needed form. from .forms import PostForm But then I get this error: ImportError: cannot import name 'UserProfileInfo' from 'mainapp.models' I have tried to do mainapp.forms import PostForm mainapp.forms import * But none of these work. I can't find anything online either about this problem. Imports from forms.py. This is where the error is occuring. from .models import UserProfileInfo, Post, Comment In the above snippet, I am importing some of models And this is thre models.py import from .forms import PostForm Here is the Post model class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField(max_length=4000) created_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='post_images',blank=True,null=True) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) tags = TaggableManager() def __str__(self): return self.title def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False def save(self, *args, **kwargs): super().save(*args, **kwargs) So the reason I need to import forms is because of the super(PostForm) bit. Here is the needed form class PostForm(forms.ModelForm): class Meta(): model = Post fields = … -
Django static files resolving after collectstatic
I have run python manage.py collectstatic so I have copies of my static files in "/static" folder. But now Django uses files from /static/myapp/js/myapp.js, not from myapp/static/myapp/js/myapp.js what should I change to resolve myapp/static/myapp/js/myapp.js first? settings.py STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' -
What is the difference between "return my_view" and "return redirect(my_view)" and how to get a mixed result?
I have a home in which I have a form that I get some info from students to suggest them some programs to apply to. The home view is as below: def home(request): template_name = 'home.html' home_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some stuff return programs(request) else: my_form = MyModelForm() home_context.update({'my_form': my_form, }) return render(request, template_name, home_context) In the second view, I have the same form and I want this form to be pre-occupied with the information I entered in the home page. That is why in the above, I passed my POST request to programs view that is as below: def programs(request): template_name = 'programs.html' programs_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some other stuff else: my_form = MyModelForm() programs_context.update({'my_form': my_form, }) return render(request, template_name, programs_context) The drawback of this strategy (passing the POST request in the home view to the programs_view) is that the url in url bar does not change to 'example.com/programs' and stays as 'example.com' . I will have some problems including problems in pagination of the programs. The alternative is that I do this: def home(request): template_name = 'home.html' home_context = {} if request.POST: … -
System to allow multiple users to work on same workbook
I am trying to build a web app with the following flow: users upload excel files to the web app. The app saves the data into a database and performs calculations on it. Then the system will output a workbook from the calculated data that multiple users have access and edit on, through the web app. The users should be able to use certain functionalities that are found in excel such as VLOOKUP, SUMPRODUCT and so on. For now, I am thinking of using django for backend and Azure services for the system; Azure web app services for the web app itself and azure sql service for the database. However, I'm not sure if there's a platform where I can store the output files and also allow users to open the files in an Excel online-like structure and directly edit (and use other workbook functionalities like VLOOKUP) on it through the web app. I've looked into Azure blob storage and Azure Files service to store the output files, but I'm not sure how I can open and edit the file from the web app. Please let me know if such thing can be done. Any other recommendations will also be … -
Django do not ask user from database for request
In my Django project I have a public API endpoint built with Django Rest Framework's APIView. It does not need to know anything about the user. Still, Django automatically fetches the session and the user from the database. Is there a way to not do this since it causes two unnecessary DB hits? Here is the code: class TermListView(APIView): permission_classes = () authentication_classes = () def get(self, request, format=None): qs = Term.objects.all().only('original_word') return Response([term.original_word for term in qs]) -
Django - UnboundLocalError
I have a function in a view that I am using to upload CSV data and write to a DB. That part is working. But when I try to check if there was data updated or created, I am getting an error which reads "local variable 'created' referenced before assignment". The function in the view is as follows def bookings_upload(request): prompt = { 'order': "Please import a valid CSV file" } if request.method == "GET": return render(request, 'booking_app/importBookings.html', prompt) csv_file = request.FILES['bookings'] if not csv_file.name.endswith('.csv'): messages.error(request, "This file is not a .csv file.") return redirect('/booking_app/bookings_upload/') data_set = csv_file.read().decode('utf-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Bookings.objects.update_or_create( book_date=column[0], grower_number=column[1], bales_booked=column[3], sale_date=column[6], book_id=column[11], reoffer=column[12] ) ) if created: messages.success(request, "Bookings have been imported successfully") else: messages.warning(request, "No new bookings were imported. Please check/verify your csv file") context = {} return render(request, 'booking_app/importBookings.html', context) What am I missing? Any assistance will be greatly appreciated. -
Jquery notification on Django message reception
I am trying to display a notification on a Django page when a Django message is received, usually after posting a form. This is the code I've written in my Django template, in the beginning of the <body> : {% if messages %} {% for msg in messages %} {% if msg.level == DEFAULT_MESSAGE_LEVELS.INFO %} <p>Displays OK</p> <script type="text/javascript"> $(document).load(function(){ new PNotify({ title: 'Regular Notice', text: 'Check me out! I\'m a notice.', type: 'info' }); }); </script> {% endif %} {% endfor %} {% endif %} The "Display OK" is there, no notifications pop up however. The page is based on the octopus html/css template : https://github.com/FireflyStars/octopus which uses the pnotify module for notifications (http://sciactive.com/pnotify/) The octopus template implements a button which triggers notifications. ui-elements-notifications.html: <button id="default-primary" class="mt-sm mb-sm btn btn-primary">Primary</button> examples.notifications.js : (function( $ ) { 'use strict'; $('#default-primary').click(function() { new PNotify({ title: 'Regular Notice', text: 'Check me out! I\'m a notice.', type: 'info' }); }); }).apply( this, [ jQuery ]); If I integrate the button html code on that same Django page, the notification displays correctly when clicking on the button, which leads me to believe that the libraries are correctly imported. I am not asking for debugging, … -
Problem with using the State variable in google api + Django
I'm trying to add the ability to save files to google disk to the django application. I took as a basis an example from the official documentation written in flask link import google_auth_oauthlib.flow from googleapiclient.discovery import build from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect import os os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' SCOPES = 'https://www.googleapis.com/auth/drive' cred = os.path.join(settings.BASE_DIR, 'credentials.json') Function for upload file: def file_to_drive(request, import_file=None): state = request.session['state'] if state is None: authorize(request) else: flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( cred, scopes=SCOPES, state=state) flow.redirect_uri = "http://localhost:8000/oauth2callback" authorization_response = request.build_absolute_uri() flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials service = build('drive', 'v3', credentials=credentials) file_metadata = { 'name': 'My Report', 'mimeType': 'application/vnd.google-apps.spreadsheet' } media = MediaFileUpload(import_file, mimetype='text/html', resumable=True) file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: %s' % file.get('id')) return (f"https://docs.google.com/document/d/{file.get('id')}/edit") And function for user authorization def authorize(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( cred, scopes=SCOPES) flow.redirect_uri = "http://localhost:8000/oauth2callback" authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') request.session['state'] = state return HttpResponseRedirect(authorization_url) urls.py path('oauth2callback', authorize, name='authorize'), path('to_drive', file_to_drive, name='file_to_drive'), In function file_to_drive searching for the value of the state parameter from the session, if it is not found, the authorize function is called. In the end, I get a message oauthlib.oauth2.rfc6749.errors.MismatchingStateError: (mismatching_state) CSRF Warning! State not equal in request and response. Error traseback looks like … -
ModuleNotFoundError: No module named 'admin'
I have this new remote job, where I had to clone all the code from a repository, and I have to make an export of the database from MySQL hosted in RDS. The first problem is that when I set up the configuration to start the app, it raise an error telling me this: Run Configuration Error: Broken configuration due to unavailable plugin or invalid configuration data. The other thing is that I already have the data dumped and set up in my local storage (the app works this way, is no longer using AWS Cloud) but when I try to do an python manage.py migrate , this error comes up... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\core\management\__init__.py", line 312, in execute django.setup() File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Tony-App\Documents\App\venv\lib\site-packages\django\apps\config.py", line 86, in create module = import_module(entry) File "C:\Users\Tony-App\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked … -
page boy found (404) notes.url
when i run the server this show up Page not found (404) Using the URLconf defined in notes.urls, Django tried these URL patterns, in this order: admin/ notes/ The empty path didn't match any of these notes urls.py from django.contrib import admin from django.urls import include , path urlpatterns = [ path('admin/',admin.site.urls), path('notes/', include('notes_app.urls')) ] notes_app urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$' , views.all_notes , name='all_notes'), url(r'^(?P<id>[\d]+)$', views.detail , name='note_detail') ] view from django.shortcuts import render from django.http import HttpResponse from .models import Note # Create your views here. ## show all notes def all_notes(request): # return HttpResponse('<h1> Welcome in Django Abdulrahman </h1>' , {}) all_notes = Note.objects.all() context = { 'all_notes' : all_notes } return HttpResponse (request , 'all_notes.html' , context) ## show one note def detail(request , id): note - Note.objects.get(id=id) context = { 'note' : Note } [enter image description here][1] return render(request,'note_detail.html' , context) -
Clarification needed for Including extra context to a serializer in Django REST Framework
According to: https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context I can write: serializer = AccountSerializer(account, context={'request': request}) and then serializer.data will look like: # {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'} but it doesn't say how I am to implement it. I mean it must be based on a call to rest_framework.reverse a bit like in this example: class CompleteTaskModelSerializer(rest_serializers.ModelSerializer): resultLocation = rest_serializers.SerializerMethodField() class Meta: model = TaskModel fields = ('id', 'resultLocation') def get_resultLocation(self, obj): return reverse('model', obj.model, request=request) but it won't acknowledge that there is anything called request in my method get_resultLocation. How is this magic supposed to work? -
Exporting django template data to excel and pdf
Respected developers. I need help with exporting data using template. I installed django-import-export and added it to admin panel now i can only export data from admin panel i want to know how can i export excel file using template example in this image.please also provide me doc links for exporting to pdf excel csv i will be thankfull to you. my admin.py from django.contrib import admin from import_export import resources from import_export.admin import ImportExportActionModelAdmin from.models import Business from.models import Add class AddResource(resources.ModelResource): class Meta: model = Add # class AddAdmin(ImportExportActionModelAdmin): # pass admin.site.register(Add) admin.site.register(Business) views.py def export_page(request): dataset = AddResource().export() print (dataset.csv) return render (request ,'export_page.html', ) this data is printing in console. -
Get list of all URL names in Django
I am putting together a template tag for active/currently visited links in a navigation bar so I can easily add the proper active CSS class to the link. I am have created code that works fine for either a mix of passed in urls with the same url-parameters included, but it does not allow me to pass in urls that have different params. {% make_active 'index' %} and {% make_active 'users' 1 %} could not be grouped together accurately as {% make_active 'index~users' 1 %} because I am using reverse() to see if the url exists. What I want is to just check the names from each of the url pattern files in my project and if the name exists, then I return the appropriate active class...but I cannot figure out how to simply grab the names. Is this possible, or can someone help with the code? @register.simple_tag(takes_context=True) def make_active(context, view_names, *args, **kwargs): """ Template tag that returns active css classes if a current link is active :param context: Context of view where template tag is used :param view_names: the view names passed into the :param args: :param kwargs: :return: """ print(args, kwargs) if not kwargs.pop('class', None): class_to_return = 'sidebar-item-active' … -
Django - Why db doesn't raise Exception when User.email is None?
I wan't User.email field to be required. I know that blank=True will make it required inside forms but I want to force this on the database level. The weird is that Django's User model has email with null=False by default so I don't understand why I can create a user just doing: User.objects.create(username='foo') And the database doesn't raise any error. Can someone explain?