Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MSSQL: Override Foreign Key Constraint Name Generation
I am attempting to create a database model in Django 3.0 using django-mssql-backend as by db backend for SQL Server 2019. The database uses multiple schemas for the tables included in it with some of the tables being non-managed (already exist), and others being created from scratch through migrations. To get multiple schemas working, I used a hack I found on another answer on here that suggested formatting the tablename as follows: class MyModel(models.Model): ... class Meta: db_table = 'schema].[table' This is so that the SQL compiles to have the wrapped square brackets that automatically form on the outside complete the schema/table definition. The problem with this is that ForeignKey objects have their constraint names generate using this table name which causes invalid constraint names arise, causing the migration to fail once the tables are done being created and it comes time for the constraints to be created.\ They generate like this: [schema1].[table1_colname_id_bc165567_fk2_schema2].[table_colname] Is there a way to override this behaviour? If this can be overridden by forking the backend and adding manual compilation code how would I even go about doing that? Otherwise, how can I have foreign keys in my models while using multiple schemas and fully utilizing … -
Cookies are blocked during development DRF and Vue app
I have Django Rest Framework API and Vue SPA frontend app. I deploy both of them in the DigitalOcean App platform. I use Session Authentication. My problem is that Session and CSRF Token cookies do not work during development when Django and Vue are served by their default servers. I guess it is because of the Same Origin Policy and other security stuff. In the production, everything is working fine when they are on the same domain. I do not have this issue earlier because I was using Token Authentication which I found out is not suitable for web Apps. I need some way of using session and csrftoken cookies during development on my computer. Is this possible with Dockerazing both apps (they are in separete repositories currently) and starting them with some reverse-proxy like Nginx so they will have the same domain? Or mayby some other way so i could develop and deploy such app easier? I cant find any information about this problem in the internet, so maybe I am missing something, or should do something differently? -
Django: how to redirect to page with list of newly created objects after form post bulk_create
I have a simple form that allows user to paste csv data with the goal to create multiple model objects at one go. The form method is 'post'. Action url is a method that calls the django `bulk_create` to create the model objects returning the pks. Goal: After submission, I want to redirect to page showing a list of the objects corresponding to the pks. Is that possible? I have tried: return render(request, "list_template.html", context={'object_list': objects_with_pks}), passing the model objects as context data to another template (but there would be danger of duplicate submission upon refresh) Redirect user to a model DetailView which contains the pk in the url (but I have more than one pks created) return HttpResponseRedirect to a new page with a success message (but I won't be able to pass the pks to the new page) Other ways that I've thought but could not find an answer Can I pass multiple pks in a url? Is there a way to transform a POST request to a GET? Can querysets in a model ListView instance be passed as parameters? I am fairly new to web development and posting questions on stackoverflow. Please comment if its unclear and … -
Django: TypeError: Object of type ModelBase is not JSON serializable
I get Error 'TypeError: Object of type ModelBase is not JSON serializable'. But i don't use JSON. And i don't put any 'ModelBase' object to templates. It's started when i began to use request.session for global variables store. When i used global variables like in pure Python - this project worked ok. (On local developer server, but was a problem with works on deploy for multiuser load.) I can't understand where it problem is appears: I use Debug mode - my views.py function is runned proprly, it return exit_ for temlate: def page_Category_Main(request, cat_): #... exit_ = { 'category_name': category['category_name'], #str 'categories_list': categories_list, #list 'action': cat_, #str 'tbl_ttx_col': [x for x in tab_marketability.keys() if x not in ['id', 'brand', 'name', 'price_avg', 'appear_month']], #list 'tbl_data': tab_marketability, #dict 'tbl_data_nov': tab_novelty, #dict 'new_form': new_form, #dict 'enabled': enabled_return, #list 'checked_items': post_return, #list 'period': request.session['period_mth_rus'], #list 'tab_active': tab_active, #str 'tab_list': list(dict_tabs.keys()), #list 'tab_data': dict_tabs #dict } return render(request, template_name="al_category.html", context=exit_) And server begin to handles template al_category.html (I see it in Python Debuger, becouse template use some @register.filter function from views.py). And in unknown point raise this TypeError: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/Nb/ Django Version: 3.1.2 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', … -
Dynamic Model Creation, Migration, and Registration in Django 3.1
I'm working on a project where I've to dynamically create models. So far I've been able to create a model and store its instance in a variable. But when I'm trying to migrate and register it to admin panel, Django is throwing an error. This is the error that pops up when I try to load the admin panel. NoReverseMatch at /admin/ Reverse for 'app_list' with keyword arguments '{'app_label': 'System'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>auth)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.1.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'app_list' with keyword arguments '{'app_label': 'System'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>auth)/$'] Exception Location: D:\DynamicModelCreation\environment\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\DynamicModelCreation\environment\Scripts\python.exe Python Version: 3.6.6 Python Path: ['D:\\DynamicModelCreation', 'D:\\DynamicModelCreation\\environment\\Scripts\\python36.zip', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36\\DLLs', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36\\lib', 'c:\\users\\vaibhav\\appdata\\local\\programs\\python\\python36', 'D:\\DynamicModelCreation\\environment', 'D:\\DynamicModelCreation\\environment\\lib\\site-packages'] Server time: Thu, 11 Feb 2021 01:30:23 +0530 This is the function where I'm trying to migrate and register the model. def createModel(tableName, fields): class Meta: pass setattr(Meta, "app_label", "System") fields['__module__'] = "System.models" fields['Meta'] = Meta model = type(tableName, (models.Model, ), fields) class Admin(admin.ModelAdmin): pass admin.site.register(model, Admin) print(model._meta.fields) return model My aim is to create and migrate the models and register them successfully during the runtime. App name - System Project name - DynamicModelCreation -
Problem with accessing static files when deploying Django API using Google App Engine
I have schema.yml in the static folder in my project and during development everything seems to be working properly however after deployment to the App Engine I get the error Not Found /static/schema.yml. My configuration looks in the way shown below. Do you have any ideas what can be the cause of the problem? settings.py: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) STATIC_URL = '/static/' app.yaml: runtime: custom env: flex entrypoint: gunicorn -b :$PORT mysite.wsgi service: mysite-service handlers: - url: /static/ static_dir: static -
How to display data base table by using forms.py in Django
My name is R Kartheek. I'm new to Django. I know how to display database table by using HTML in Django. But, I don't know by using forms.py. Present learning that. Anyone, please help me with how to print the database table by using forms.py in Django. Just like <.objects.all()> how to use this by using Forms.py in Django? models.py: from django.db import models # Create your models here. class Emp_Data(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) mobile = models.BigIntegerField() email = models.EmailField(max_length=50) company = models.CharField(max_length=50) location = models.CharField(max_length=50) salary = models.IntegerField() views.py from django.shortcuts import render from .models import Emp_Data from .forms import Emp_Data_Form from django.http import HttpResponse from django.contrib import messages # Create your views here. def Emp_View(request): if request.method == 'POST': form = Emp_Data_Form(request.POST) if form.is_valid(): first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') mobile = request.POST.get('mobile') email = request.POST.get('email') company = request.POST.get('company') location = request.POST.get('location') salary = request.POST.get('salary') data = Emp_Data(first_name = first_name, last_name = last_name, mobile = mobile, email = email, company = company, salary = salary ) data.save() messages.success(request, f'Data submitted successfully...') form = Emp_Data_Form() context = {'form':form} return render(request, 'empformapp/empdata.html', context) else: return HttpResponse('Invalid form') else: form = Emp_Data_Form() context = {'form':form} return render(request, 'empformapp/empdata.html', … -
django paginator is not working but the link is working manually
I have a page that represents the articles based on categories. I am trying to make a pageinator for this page but I see no pageinator in my webpage. However when I enter the link manually it works. i don't know what I'm missing here... #my HTML page <div class="blog-pagination"> <ul class="justify-content-center"> {% if cat_articles.has_previous %} <li><a href="{% url 'website:category' cat_articles.previous_page_number %}"> <i class="icofont-rounded-left" ></i></a></li> {% endif %} <li><a href="#">1</a></li> <li class="#"><a href="#">2</a></li> <li><a href="#">3</a></li> {% if cat_articles.has_next %} <li><a href="{% url 'website:category' cat_articles.next_page_number %}"> <i class="icofont-rounded-right" ></i></a></li> {% endif %} </ul> </div> </div><!-- End blog entries list --> #my view def category(request, slug, page=1): cat = get_object_or_404(Category, slug=slug, status=True) articles_cat = cat.articles.filter(status='Published') paginator_cat = Paginator(articles_cat, 1) cat_articles = paginator_cat.get_page(page) context = { "category": cat_articles } return render(request, 'website/category.html', context) -
Server ERROR: smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server
This maybe a repeated question but I'm still facing issues on this, hope there's a solution around. Thanks in advance. I'm trying to send mail through my Gmail Account. I did get an App Password for it and everything. I'm using the newest version of Python. This is the Error I get: Traceback (most recent call last): File "E:\Python_old\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\Python_old\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Python_old\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "E:\Python_old\WebshopV4\ecommerce\store\views.py", line 71, in checkout send_mail( File "E:\Python_old\venv\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "E:\Python_old\venv\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "E:\Python_old\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "E:\Python_old\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 67, in open self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) File "C:\Users\Jeamp\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 755, in starttls raise SMTPNotSupportedError( smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server. Here is my Email configuration: # Email Settings EMAIL_HOST = 'smtp.gmail.com' Email_PORT = '587' EMAIL_HOST_USER = 'jeampo.jeampo@gmail.com' EMAIL_HOST_PASSWORD = 'MYPASSWORD' EMAIL_USE_TLS = True And here is my Django sendmail() function: # send an email send_mail( 'message from ' + message_name, # subject message_to_send, # message message_email, # from email ['myemail@outlook.de'], # To Email ) -
how to update value in database in django?
code It is Screenshot of my code for delete and update in django database. but here if I click on delete button it correctly deletes the targited value but if i press update button of any record it only update and show the value of last record. here I'm attaching the output screenshots main_output here if i print on any of update button it will show and update only the most recently added record modal -
Why does my heroku bash instance show my app folder to be empty?
I've deployed an app to heroku and ran heroku run bash -a {app_name} Once it successfully opens a bash console and I run ls I see nothing. If I run pwd it says I'm in the /app directory where my project files should be. I am also unable to run any commands using my manage.py file e.g. heroku run python manage.py migrate results in a python: can't open file 'manage.py': [Errno 2] No such file or directory -
'DatabaseOperations' object has no attribute 'geo_db_type'
I'm using 2 databases in my project. Sqlite3 for most things and then Postgis to create a geospatial database for my 'store locator' app. What I've done so far: 1] My postgres DB has been setup with the postgis extension 2] I have added the database in my settings.py, and also added'django.contrib.gis' under INSTALLED_APPS. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'geospatial': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geospatial', 'USER': '*****', 'PASSWORD': '*****', 'HOST': 'localhost', 'PORT': '5432' } } 3] I came across 'Database Routers' to make sure that my app was using the postgis db and not the default sqlite3 one and gave it a go but to no avail. facility/routers.py: from django.conf import settings class dbRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'facility': return 'geospatial' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'facility': return 'geospatial' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'facility' or obj2._meta.app_label == 'facility': return True return None def allow_syncdb(self, db, model): if db == 'geospatial': return model._meta.app_label == 'facility' elif model._meta.app_label == 'facility': return False return None mainapp/settings.py: DATABASE_ROUTERS = ['facility.routers.dbRouter'] Can someone please tell me what I'm doing wrong? Any and all help is … -
Staticfiles not copied to STATIC root (0 static files copied)
I am trying to get my app on heroku have the relevant settings as follows STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) if not DEBUG: AWS_ACCESS_KEY_ID = get_environment_variable("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = get_environment_variable("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = "the-bucke-name" AWS_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_DEFAULT_ACL = "public-read" AWS_LOCATION = "static" STATIC_URL = f"https://{AWS_CUSTOM_DOMAIN}/{AWS_LOCATION}/" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" else: STATIC_URL = "/staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") import django_heroku django_heroku.settings(locals(), staticfiles=False) When i run docker-compose run --rm web-app python manage.py collectstatic --noinput I get 0 static files copied to '/code/staticfiles' locally and on heroku 0 static files copied I cant seem to figure out which setting I am missing. The staticfiles folder is empty so not a case of unmodified files or there being no chnages to the css. -
Use video part as thumbnail
In you when upload videos with thumbnail on feed show that. But when no upload video with thumbnail YouTube randomly choose thumbnail from video part how to do this use python and django. -
How to prevent deletion of instance from Inline in Django Admin correctly?
I have two models look like: class Client(models.Model): # some client fields class User(models.Model): # some user fields owned_by = models.ForeignKey(Client, on_delete=models.CASCADE) is_main_user = models.BooleanField() Also I made admin part. StackedInline for User and ModelAdmin for Client which includes UserStackedInline. My goal is prevent deleting User which has is_main_user==True. I've made signal handler for pre_delete from User and raise ValidationError("You cannot delete main user") when condition is true. But when I try to delete user in admin, I was getting 500 error. I've expected to get readable message in admin. How I can correctly handle ValidationError on instance deletion in StackedInline? Or am I incorrectly preventing a specific instance from being deleted? -
NoReverseMatch at / Reverse for 'blog' not found. 'blog' is not a valid view function or pattern name
Not sure why I'm getting this error. It also says: "Error during template rendering In template /Users/aydanaslanova/Desktop/Travel_Project/todo/templates/todo/base.html, error at line 0" I don't have a blog.html or a blog url or a blog view? I only have one app (todo), that'all. For reference, I tried to add another app earlier called "blog" but later deleted it. Attaching settings.py, urls.py and base.html where I am getting the error. Similar questions were not helpful, unfortunately. -
Django model.FilePathField returns paths that have additional 'static' directories
I am new to Django, writing my first project (portfolio website) and stumbled upon such problem: So i a nutshell: model.FilePathModel when called in my .html site as {% static project.image %} returns: /static/projects/static/img/project1.png while it should return: /static/projects/img/project1.pn My question is: Why does addtional /static/ appears when there is none in my file sturcture? I am not sure if something with my understanding of Django static file managment is wrong, or of models.FilePathField for that matter. dir sturcture: Link to the snapshot procejts/models.py file : class Project(models.Model): allow_folders=True def __str__(self): return self.title title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length = 20) image = models.FilePathField(path='projects/static/projects/img' ) settings.py(static settings part) STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", BASE_DIR /'projects/static/', ] -
line 254, in add_coupon order.coupon = get_coupon(request, code) AttributeError: 'dict' object has no attribute 'coupon'
I am creating a django3 Ecommerce website and I've come through the following error when a guest user tries to enter a coupon : Traceback (most recent call last): File "/Users/miryamelliye/development/comdjanco/osivenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/miryamelliye/development/comdjanco/osivenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/miryamelliye/development/comdjanco/ecommerce/store/views.py", line 254, in add_coupon order.coupon = get_coupon(request, code) AttributeError: 'dict' object has no attribute 'coupon' views.py def get_coupon(request, code): try: coupon = Coupon.objects.get(code = code) return coupon except ObjectDoesNotExist: messages.info(request, 'This coupon does not exist') return redirect('checkout') def add_coupon(request): data = cartData(request) if request.method == "POST": form = CouponForm(request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = data['order'] order.coupon = get_coupon(request, code) order.save() messages.success(request, 'Successfully added coupon!') return redirect('checkout') except ObjectDoesNotExist: messages.info(request, 'You do not have an active order') return redirect('checkout') return redirect('checkout') my utils.py def cookieCart(request): #Create empty cart for now for non-logged in user try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('CART:', cart) items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] for i in cart: try: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'id':product.id, 'product':{'id':product.id,'name':product.name, 'price':product.price, 'imageURL':product.imageURL}, 'quantity':cart[i]['quantity'], … -
django 1.8.5 + Python 2.7 to Django 3.0 + Python 3.9
I have a massive Django 1.8.5 and Python 2.7.6 project. I need to upgrade it to Django 3.0, Python 3.9. Any recommendations on how to proceed ? Thanks. -
Cancel a save from save method in django models
So I have django model and I want to override save so that it only saves on certain instances. Is there a way to avoid a save from happening if a condition is met? The idea is if certain conditions defined with an if statement aren't met the instance fails to be saved. so for instance if there is not enough waiters we cancel the save, or if there is not enough tables we do the same. Here's my code: class Service(models.Model): id = models.AutoField(primary_key=True) arrival = models.DateTimeField(auto_now_add=True) exit = models.DateTimeField(null=True, blank=True) waiter = models.ForeignKey('Waiter', on_delete=models.CASCADE) table = models.ForeignKey('Table', on_delete=models.CASCADE) total_ammount= models.DecimalField(max_digits=15, decimal_places=2) def save(self, *args, **kwargs): if self.id == None: time = datetime.datetime.now() # check for waiters waiters = Waiter.objects.select_related().annotate(num_Service=Count('service', filter=Q(service__exit__gt=time))).all() available_waiters = waiters.filter(num_Service__lt=4) avalable_waiters_length = len(available_waiters) # check for tables tables = Table.objects.select_related().annotate(num_Service=Count('service', filter=Q(service__exit__gt=time))).all() available_tables = tables.filter(num_Service__lt=1) avalable_tables_length = len(available_tables) # return exception if a problem arises if avalable_tables_length == 0 and avalable_waiters_length == 0: print("not enough waiters or tables") if avalable_waiters_length == 0: print("not enough waiters") return if avalable_tables_length == 0: print("not enough tables") return # assign waiter and table waiter_obj = random.choice(available_waiters) self.waiter = waiter_obj table_obj = random.choice(available_tables) self.table = table_obj print(time.time()) # check if current … -
How do i go about making a django model field unique but only for individual users?
So I have this watchlist model class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='watchlist') symbol = CharField(max_length=10, unique=True) Where a user and a text symbol is saved. A user is not allowed to save two of the same symbol cuz that wouldnt be good logic. Thats why i added the unique=True. However, I later realized that i kinda misunderstood what unique does and that its unique across the whole table no matter who the user is. I only want it to be unique when the user is the same. So Test_User can save "ABC" and "DEF" but cant save "ABC" again. However User123 should be allowed to save "ABC" and so on. One bad solution to this would be taking care of it in my views when i save instances by getting a list of symbols saved already and checking if the given symbol is in that list or not and save accordingly. I consider this a bad solution because it wont work in admin and the redundancy will be insane if i need to use it in other views -
(djstripe.C001) Could not find a Stripe API key. HINT: Add STRIPE_TEST_SECRET_KEY and STRIPE_LIVE_SECRET_KEY to your settings
Stripe keys are not being detected correctly and I don't know where the error is in DJStripe. Here is how my Stripe is configured: STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") STRIPE_TEST_SECRET_KEY = "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx STRIPE_TEST_PUBLIC_KEY = "pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -
How to export models from admin page with username rather than user id?
I have a participant model in models.py Django as the following: from django.db import models from django.contrib.auth.models import User class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) score = models.FloatField(default=0) completed_study = models.BooleanField(default=False) def __str__(self): return self.user.username and I want to be able to export all the data from the admin page, so under the admin.py I added the following from django.contrib import admin from .models import Participant from django.contrib.auth.admin import UserAdmin as BaseAdmin from import_export.admin import ImportExportModelAdmin from import_export import resources from django.contrib.auth.models import User class UserResource(resources.ModelResource): class Meta: model = User fields = ('id', 'username') class UserAdmin(BaseAdmin, ImportExportModelAdmin): resource_class = UserResource class ParticipantAdmin(admin.ModelAdmin): list_display = ['user', ] readonly_fields = ('created_at', 'updated_at',) class ParticipantAdmin(ImportExportModelAdmin): pass admin.site.register(Participant, ParticipantAdmin) admin.site.unregister(User) admin.site.register(User, UserAdmin) I am able to export the data from the participant model, but I want under the user field to display the actual username rather than the id. How can I do that? is that even doable? -
request.user in generic view and in pure function in django
I was using django-rest-framework-simplejwt for authentication. Here is my settings.py filesettings.py file Initially I was trying to get login user by accessing request.user in a view function as shown below and passing access token in headers berear token: function test But I wasn't able to get the logged in user. Instead when I tried RetreiveAPIView of rest framework generics, it gave me the user..Here is the code for the same..Using RetreiveAPIView UserSerializer Initially I thought that both the request objects are same but it seems that there is some difference.. Can anyone explain me what is the difference between the two? -
Django Error Following Tutorial b/c using 3.1 not 1.9 TypeError: view must be a callable or a list/tuple in the case of include()
I know what the issue is, its that in my code I cant use a string to map my views to urls but Im not sure how to rewrite it so that it works. urls. py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('posts/', "posts.views.post_home"), ## *how do i rewrite this section* ] apps.py from django.apps import AppConfig class PostsConfig(AppConfig): name = 'posts' views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def post_home(request): return HttpResponse("<h1>Hello</h1>")