Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to youtube-dl video download directly to a user side not download file in local system using python Django?
I am trying to youtube videos download directly to the client-side. I don't want to store files in the local system. For that, I used the youtube-dl python library. I also want youtube-dl video download direct to AWS S3. Please help me. -
How to get value from dict in a loop in a django template
I need to get the value of totale in this dictionary dinamically: { "periodo": "2021-12", "corrispettivi": { "10.00": { "totale": -100.0, "imposta": -9.09, "imponibile": -90.91 }, "22.00": { "totale": 10773.81, "imposta": 1942.82, "imponibile": 8830.99 } }, "saldo": { "totale": 10673.81, "imposta": 1933.73, "imponibile": 8740.08 }, "ndc": 782, "ingressi": 782 }, in my template {% for entrata in entrate %} <h3>Periodo: {{ entrata.periodo }}</h3> <table style="width:100%"> <thead> <tr> <th></th> <th style="text-align:right">TOTALE</th> <th style="text-align:right">IMPOSTA</th> <th style="text-align:right">IMPONIBILE</th> </tr> </thead> <tbody> {% for corrispettivo in entrata.corrispettivi %} <tr> <th>IVA {{corrispettivo}} %</th> <td>{{corrispettivo.totale}}</td> <td>{{corrispettivo.imposta}}</td> <td>{{corrispettivo.imponibile}}</td> </tr> {% endfor %} </tbody> </table> {% endfor %} but corrispettivo.totale doesn't work i tried this guide but I don't understand how it works how can I access the value of totale? -
Introduce a ForeignKey filed in my Project Model
I have a system that uses, class MyModel(models.Model) book_classes = (("","Select"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4')) b_class = models.CharField('Form',max_length=4,choices=book_classes,default="n/a") I would like to switch it to use a foreignkey from a Klass model class Klass(models.Model): name = models.CharField(max_length=20) class MyModel(models.Model) b_class = models.ForeignKey(Klass,on_delete=models.CASCADE) The system already has a lot of data that uses class MyModel(models.Model) book_classes = (("","Select"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4')) b_class = models.CharField('Form',max_length=4,choices=book_classes,default="n/a") What effect will the change have on the already existing data? -
django channels WebsocketCommunicator TimeoutError
I am trying to run the following test: tests.py from rest_framework.test import APITestCase from myapp.routing import application from channels.testing import WebsocketCommunicator from account.models import User from rest_framework.authtoken.models import Token class Tests(APITestCase): def setUp(self): self.user = User.objects.create(email='test@test.test', password='a password') self.token, created = Token.objects.get_or_create(user=self.user) async def test_connect(self): communicator = WebsocketCommunicator(application, f"/ws/user/{self.token}/") connected, subprotocol = await communicator.connect() self.assertTrue(connected) await communicator.disconnect() application is a boilerplate instance of channels.routing.ProtocolTypeRouter (like in here: https://channels.readthedocs.io/en/latest/topics/routing.html). Everything works fine in production. The test exits with the following error: Traceback (most recent call last): File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 74, in receive_output return await self.output_queue.get() File "/usr/lib/python3.7/asyncio/queues.py", line 159, in get await getter concurrent.futures._base.CancelledError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/sync.py", line 223, in __call__ return call_result.result() File "/usr/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/usr/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/sync.py", line 292, in main_wrap result = await self.awaitable(*args, **kwargs) File "/home/projects/myapp/myapp-api/app/tests.py", line 35, in test_connect connected, subprotocol = await communicator.connect() File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/channels/testing/websocket.py", line 36, in connect response = await self.receive_output(timeout) File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 85, in receive_output raise e File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/testing.py", line 74, in receive_output return await self.output_queue.get() File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/timeout.py", line 66, in __aexit__ self._do_exit(exc_type) File "/home/projects/myapp/myapp-env/lib/python3.7/site-packages/asgiref/timeout.py", line … -
How do I include SSL when testing a Djang app
I'm doing integration tests and one of our vendors require we make requests from a secure server. When doing manual testing, I can accomplish this using python manage.py runserver_plus --cert-file cert.pem --key-file key.pem However, I don't know how to incorporate runserver_plus and the arguments when running Django TestRunner(). if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings_integration' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests.integration_tests"]) sys.exit(bool(failures)) The TestRunner() does not appear to take arguments. -
How to handle file delete after returning it has response in Django rest framework
Currently I am performing the below steps in my DRF code. 1.Capturing the file name in a request 2.Searching the given file name in a SFTP server. 3. If the file is available in SFTP server,downloading it to local path in a folder called "downloads" Returning the file as response with FileResponse Now I need to delete the file which i downloaded from SFTP or simply delete everything in downloads folder. What will be best approach to achieve this? How about an async celery task before returning FileResponse. Kindly help me with the best approach for this -
Cloud build can't connect to replica database
I'm deploying django app with GCP Cloud build service. In cloudbuild.yaml I define step to apply migrations with gcr.io/google-appengine/exec-wrapper tool: - id: "apply migrations" name: "gcr.io/google-appengine/exec-wrapper" args: [ "-i", "gcr.io/$PROJECT_ID/${_SERVICE_NAME}", "-s", "${PROJECT_ID}:${_REGION}:${_DB_INSTANCE_NAME}", "-e", "GOOGLE_CLOUD_SECRETS_NAME=${_GOOGLE_CLOUD_SECRETS_NAME}", "-e", "DJANGO_SETTINGS_MODULE=${_DJANGO_SETTINGS_MODULE}", "--", "python", "manage.py", "migrate", ] Everything is working fine with one "default" database. Then: DATABASES = { "default": env.db("DATABASE_URL"), "replica": env.db("REPLICA_DATABASE_URL"), } When I added new mysql replica database with name gcp-replica-2015-07-08-1508, Cloud build service starting failing with error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/cloudsql/myproject-228819:us-central1:gcp-replica-2015-07-08-' I checked my db config by printing DATABASES variable in Cloud build and config have correct data, but if you look on error you will notice that error returns with cut string at the end ! without -1508 If I skip this step and deploy my app with same config to Cloud Run everything is working fine. Service account have following roles: Replica DB Version MySQL 5.7 -
How do i display the category name of a product instead of Category object (1) django 3.1
So my django backend is not displaying the category name but is instead giving me a category object result screenshot of undesired result under the category field. How do i fix this?? Below is a snippet of my admin.py and model.py category/admin.py from django.contrib import admin from .models import Category # Register your models here. class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('category_name',)} list_display = ('category_name', 'slug') admin.site.register(Category, CategoryAdmin) categories/model.py from django.db import models # Create your models here. class Category(models.Model): class Meta: verbose_name = 'category' verbose_name_plural = 'categories' category_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=255, blank=True) cat_image = models.ImageField(upload_to='photos/categories', blank=True) def __str__(self): return self.category_name store/models.py class Product(models.Model): product_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() out_of_stock = models.BooleanField(default=False) is_available = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name store/admin.py from django.contrib import admin from .models import Product # Register your models here. class ProductAdmin(admin.ModelAdmin): list_display = ('product_name', 'price', 'category', 'modified_date', 'is_available', 'out_of_stock') prepopulated_fields = {'slug': ('product_name',)} admin.site.register(Product, ProductAdmin) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'category', 'accounts', 'store', -
how can I fix the problem in this command
django-admin startproject lecture3 django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was includ ed, verify that the path is correct and try again. At line:1 char:1 django-admin startproject lecture3 + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Suggestion [3,General]: The command django-admin was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\django-admin". See "get-help about_Command_Precedence" for more details. -
Strange Error When Checking If Object Exists
Thanks ahead of time for the help. I am trying to check if a cart object exists when a user visits the "myCart" page. If it does not, it should then create a new instance and use the user's id as a foreign key for reverse lookup. So I used the exists() method in an if statement. What's weird is that instead of executing the else block, it just throws me an error telling me the object doesn't exist. The test user doesn't have a cart object associated with it yet and that's obvious. What I don't understand is why it isn't triggering my else statement. Maybe I have been coding too long and need some sleep and that's why I'm missing it. Anyway if you guys could take a look for me I'd really appreciate it. :) The Error: Weird Error #the views.py file for this app: def myCart(request): context = {} if request.user.is_authenticated: owner = request.user.id if Cart.objects.get(cart_owner=owner).exists(): context['cart'] = cart return render(request, 'cart/myCart.html', context) else: cart = Cart(cart_owner=owner) context['cart'] = cart return render(request, 'cart/myCart.html', context) else: return HttpResponseRedirect(reverse("login")) def update_cart(request): if request.user.is_authenticated: owner = request.user.id cart = Cart.objects.get(cart_owner=owner) productID = request.GET['id'] product = Product.objects.get(pk=productID) if not product … -
Using Twilio Verify with Gmail API
I'm using Twilio Verify API in my web application. I've done email integration with sendgrid API but I'm facing some problems with my SendGrid account so I decided to setup email integration with Gmail API. I have it already working on my website. So can anyone help me understand how I can achieve the verify API integration with Gmail API. def verifications(email, via): try: return client.verify \ .services(settings.TWILIO_VERIFICATION_SID) \ .verifications \ .create(to=email, channel=via) except Exception as e: print(e) message = send_email.create_message("MYAPP <myemail@gmail.com>", email, "OTP Verification", msg) send_email.send_message(service, "me", message) Is there any why I can combine both of these. Please help me if you can I've been on this for a long time now. Thank You. -
Schema for Rest Framework serializer with modified to_representation
I implemented a modification of the to_representation method of a serializer in order to flatten a nested relation through class LocalBaseSerializer(serializers.ModelSerializer): """Helper serializer flatenning the data coming from General Information.""" general_information = GeneralInformationSerializer(read_only=True) class Meta: abstract = True model = None exclude = ("id", "created_at") def to_representation(self, instance): data = super().to_representation(instance) general_information = data.pop("general_information") _ = general_information.pop("id") return {**general_information, **data} class ContractReadSerializer(LocalBaseSerializer, serializers.ModelSerializer): class Meta: model = Contract exclude = ("created_at",) It works as expected but, up to now, I did not manage to have the correct schema as shown from the extract below ContractRead: type: object description: |- Helper serializer flatenning the data coming from General Information. properties: id: type: integer readOnly: true general_information: allOf: - $ref: '#/components/schemas/GeneralInformation' readOnly: true beginning_of_the_contracts: type: string format: date termination_of_the_contracts: type: string format: date required: - beginning_of_the_contracts - general_information - id - termination_of_the_contracts I did not find any help neither in DRF documentation nor in drf-spectacular one. Thanks in advance for any help. -
is there any way to call a function(in another python file) and get the same return in Django view
I am trying to get a return from a function that is in similarity.py (function name returnTablewithURL) to Views.py. When I print the variable df in similarity.py it gives the output in dataframe. Like this: Similarity (%) https://en.wikipedia.org/wiki/The_quick_brown_f... 0.876818 https://knowyourphrase.com/the-quick-brown-fox 2.371295 I want to get the same output for fileupload function in views.py. So I tried to call the function from views (meaning from fileupload function) but it shows something in numbers. Output( with the help of print statement to check if it is same): <function returnTableWithURL at 0x000001D3631311F0> I have tried some other methods but in vain. It would be really helpful if i could use some suggestion and help Views.py: def fileupload(request): # Handel file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): #Process for handeling the file snd store it on mongodb newdoc = Document(docfile = request.FILES['docfile']) #Contain process for extracting data in a file and storing them in DB as textfield newdoc.fileData = request.FILES['docfile'].read() newdoc.username = request.user newdoc.save() # Redirect to the document list after post result(newdoc.fileData) # Here i am trying to get the result from # returnTableWithURL function. This function is in # another python dframe = returnTableWithURL print(dframe) return render(request, … -
I am creating a simple website with 3 pages but i keep getting an erro. ModuleNotFoundError: No module named 'HomePage'
I cannot figure out why I keep getting the ModuleNotFoundError: No module named 'HomePage' error I'm fairly new to Django but have spent a majority of the day trying to figure out how to make a homepage where I could link a Homepage.html and have a different page on my original page. Any help would be appreciated this is my second question ever on here please be gentle. Below is the full error am getting. PS C:\Users\admin\Desktop\InstitutionFinderWebsite> python manage.py runserver; Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\python\python3.10.0\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\python\python3.10.0\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\admin\.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\admin\.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site- packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\admin\.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File"C:\Users\admin\.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site- packages\django\core\management_init_.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\admin.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\admin.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\admin.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\admin.virtualenvs\InstitutionFinderWebsite- jRRQ2QPD\lib\site-packages\django\apps\config.py", line 223, in create import_module(entry) File "C:\python\python3.10.0\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, … -
How can I check if the current request is from htmx
I'm using Django, Is there a way to check if the current request is from HTMX -
python coverage - specify the working directory
I have a django application called edison with multiple django-apps in it. I run tests on them using coverage: coverage run --source='.' edison/manage.py test application_one coverage run --source='.' edison/manage.py test application_two ... My repo structure is: -- edison [the repo name] -- edison [a django application] -- schuedled_jobs -- internal_packages In my tests files I import stuff from internal_packages directory and when I run the coverage commands i get the error ModuleNotFoundError: No module named 'internal_packages'. My question is: how do I change the working directory of coverage to be the root directory - so it will recognise all modules? -
Django static files to AWS S3 return 403 forbidden
I'm working on a Django(3) project which is deployed at Heroku. I'm trying to connect AWS S3 using Django Storages to upload Static and Media files to S3 Bucket. Note: I have googled a lot and tried every solution I found, but nothing solved my issue, so don't mark this as duplicate, please! I have created an S3 bucket with the Public access enabled and added the following CORS configuration: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "POST" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Also, created an IAM user with programmatic access and gives the permission as S3FullAccess And here's what I have in **settings.py** AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_QUERYSTRING_AUTH = False AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-east-1' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' If I open files from the bucket directly I can see the file in the browser, but when I load my site (pythonist.org) these files return with 403 forbidden Here's the response from browser's Network tab for a file: Summary URL: https://s3.amazonaws.com/pythonist.org/css/normalize.css Status: 403 Forbidden Source: Network Initiator: pythonist.org:18 Don't know what's wrong here, Thanks in advance! -
coverage.misc.NoSource: No source for code: '/usr/src/server/rep-1>'
I am using the coverage package for quite a while now and it functioned well until yesterday it just fails at the level of generating a report I believe. There were no changes on how the functionality which is way more bizarre. I have the below coveragerc file: [run] source = . branch = True concurrency = multiprocessing omit = manage.py config/asgi.py config/wsgi.py config/settings.py */migrations/* *test* [report] show_missing = True skip_covered = True and Django manage.py file is as the following: import os import sys COVERAGE_ACCCEPTANCE = 85 def main(): argv = sys.argv try: command = argv[1] except IndexError: command = "help" default_settings = "config.settings" running_tests = (command == "test") if running_tests: default_settings = "config.settings_test" from coverage import Coverage cov = Coverage() cov.erase() cov.start() os.environ.setdefault("DJANGO_SETTINGS_MODULE", default_settings) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?", ) from exc execute_from_command_line(argv) if running_tests: cov.stop() cov.save() cov.combine() if round(cov.report()) < COVERAGE_ACCCEPTANCE: sys.exit(1) cov.erase() if __name__ == "__main__": main() After the tests are run successfully, the coverage raises the below error: Ran 317 tests in 96.790s OK … -
DjangoCKEditor Configuration Fully Enabled
I am using djangocms-text-ckeditor on a couple of my sites. On one of them, I have the following in base.py CKEDITOR_SETTINGS = { 'language': '{{ language }}', 'toolbar': 'full', 'toolbar_HTMLField': [ ['Undo', 'Redo'], ['ShowBlocks'], ['Format', 'Styles'], ], 'skin': 'moono-lisa', 'removePlugins': ['image'], 'extraPlugins' : [ # these are non-standard plugins 'codesnippet', 'html5audio', 'image2', 'autogrow', ], } This provides the following editor toolbar On another site, I have not added anything into base.py and get this My question is how I can get the CMSPlugins section in the first site. Also, what should a config look like if I want all plugins enabled explicitly? -
Editing many_to_many fields in admin_panel __init__() takes 13 positional arguments but 14 were given
I was looking for a way to edit, display and delete when using M2M fields in the admin panel. based How To Edit ManyToManyField In Django Admin list Display Page? . When adapting to my project, I encounter the error init() takes 13 positional arguments but 14 were given app.admin class app.admin class ReceptChangeList(ChangeList): def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin): super(ReceptChangeList, self).__init__(request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin) # these need to be defined here, and not in MovieAdmin self.list_display = ['action_checkbox', 'name', 'ingredient'] self.list_display_links = ['name'] self.list_editable = ['ingredient'] @admin.register(Recept) class ReceptAdmin(admin.ModelAdmin): #list_display = ('author','name','description',) def get_changelist(self, request, **kwargs): return ReceptChangeList def get_changelist_form(self, request, **kwargs): return ReceptChangeListForm app.forms from django import forms from api.models import Ingredient class ReceptChangeListForm(forms.ModelForm): ingredient = forms.ModelMultipleChoiceField( queryset=Ingredient.objects.all(), required=False) -
django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments
I cannot register a new user due to below error: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uid64': 'Mjk', 'token': 'aydhbh-1b0354ce0dd3df37193a6f22e95b0c4e'}' not found. 1 pattern(s) tried: ['account/activate/(?P<uidb64>[-a-zA-Z0-9_]+)/(?P<token>[-a-zA-Z0-9_]+)/$'] urls.py: urlpatterns = [ path('register/', views.account_register, name='register'), path('activate/<slug:uidb64>/<slug:token>/', views.account_activate, name='activate'), # User dashboard path('dashboard/', views.dashboard, name='dashboard'), ] views.py: def account_register(request): if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False user.save() # Setup email current_site = get_current_site(request) subject = 'Active your account' message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject=subject, message=message) return HttpResponse('Registered successfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_encode(uidb64)) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('account:dashboard') else: return render(request, 'account/registration/activation_invalid.html') account_activation_email.html: {% autoescape off %} Hi {{ user.user_name }}, Your account has been successfully created. Please click below link to activate your account. http://{{ domain }}{% url 'account:activate' uid64=uid token=token %} {% endautoescape %} A new user is registered to a DB but as you can see there an error error image Do you … -
django tag { % block content % } isn't working
so i just started learning django, i understand the basic tag blocks but it didn't works well on my page. i have page called index.html and question.html i write like this in index.html <body> <div> <div> sum content </div> <div> { % block content % } { % endblock % } </div> </div> </body> and like this in question.html : { % extends 'index.html' % } { % block content % } <<my content>> { % endblock % } but the content in question.html didn't show up in index.html. i've checked my setting and didn't have django-stub like in other case. and if you want to know the structure, it goes like : djangoProject1 >djangoProject1 >myweb >static >templates -index.html -question.html Thank you in advance! -
Add attribute to admin model Django
I'm trying to add an attribute to my user admin model, but it doesn't work, here is what I succeded to do (I want to add inactivity field): from django.contrib import admin from .models import User class usersAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'inactivity') admin.site.register(User, usersAdmin) Here is my model code: class User(models.Model): username = models.TextField(max_length=140, default='uid', primary_key=True) first_name = models.TextField(max_length=140, default='cn') last_name = models.TextField(max_length=140, default='givenName') inactivity = models.IntegerField(default=500) def _str_(self): return self The error occurs when I'm trying to access to my added field from my views: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) data['username'] = self.user.username data['first_name'] = self.user.first_name data['last_name'] = self.user.last_name data['inactivity'] = self.user.inactivity print(self.user) return data the error says: Traceback (most recent call last): File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework_simplejwt\views.py", line 27, in post serializer.is_valid(raise_exception=True) … -
Updating FileField Or ImageField In Django, Django-Ninja?
enter image description here How can I assign The New Image In The ImageField ????? -
How to get current user in models.py?
I have a model like this class Orders(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) The logic is the companies to send offers to get the specific travel. When you send an offer you will not have access to that travel anymore untill the base company accept or reject your offer. So when the specific company logged in I want to show them if they sent an offer or not. The company name is saved in the user that is logged in. What I tried to do is this class Order(models.Model): @property def has_sent_offer(self): Offer.objects.filter(order=self.pk, company=request.user.company) But in the models.py I don't have access to request.user