Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Datetime field shown as in admin panel
I have a model where I can create objects without a problem from the admin panel, I created a form to do the same directly within the website but I cannot manage to create an object directly from the form because of the error shown in the second picture. It is the "DateTimeField". Best case scenario, someone knows which piece of code is required for the form to display a menu ( as shown in picture 1 ) where the user can click which time and date he wants to. Thank you very much Second image: -
I cant install django using pip [closed]
I tried everything i found on the internet but it keeps showing like this enter image description here -
possible to use tuple, deconstruct with request.user, django?
Normally, I know tuple can be used as (email, username) = ('hello', 'user') that email will be equal to hello But I am wondering if I can do something like (email, username) = request.user so I do not have to keep on typing request.user and instead just use email and username like how javascript works. if I did the above, I would get an error saying TypeError: object is not iterable Thanks in advance for any suggestions and advices. -
Pythonanywhere TemplateDoesNotExist at /accounts/login/
When I run my app locally it works, but when I tried uploading it to pythonanywhere I get the following error: How do I fix this? If it will help my files are positioned like this: Music (the Django project folder) |_manage.py |_Music (the folder that contains settings file) |_App (the App itself with models, views etc. and my templates is here too) |_templates |_App |_registration |_login.html If you need more information I can upload it. -
I keep getting a naive date warning even though my model default uses timezoned date
Every time I run python manage.py test I get a warning saying that my model fields recived naive datetime: (venv) C:\Users\Philip\CodeRepos\Acacia2>python manage.py test journal.tests.test_models Creating test database for alias 'default'... C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\fields\__init__.py:1365: RuntimeWarning: DateTimeField Ledger.last_spreadsheet_update received a naive datetime (1970-01-01 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\fields\__init__.py:1365: RuntimeWarning: DateTimeField JournalEntry.last_integrity_check received a naive datetime (1970-01-01 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" However my models are configured with a default datetime that includes a timezone: class Ledger(models.Model): sort = models.PositiveIntegerField(default=0, blank=False, null=False) name = models.CharField(max_length=255) coa_sub_group = models.ForeignKey(COASubGroup, on_delete=models.PROTECT) is_reconcilable = models.BooleanField(default=False) spreadsheet_row = models.IntegerField(blank=True, null=True, unique=True) last_spreadsheet_update = models.DateTimeField(blank=False, null=False, default=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=timezone('UTC'))) class JournalEntry(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False, blank=False) date = models.DateField(null=False, blank=False) # Data integrity check fields last_integrity_check = models.DateTimeField(blank=False, null=False, default=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=timezone('UTC'))) integrity_check_fail = models.BooleanField(null=False, blank=False, default=0) What could I be doing wrong? -
403 CSRF verification failed Django when refresh url?
I have create a view that takes in a post request from my /login route, but after accepting the login post request and redirecting to /, when the user refresh the browser, I get a 403 CSRF failure code. How can i optimize my code so that if the user refreshes the browser it doesn't prompt the error? view def index(request): username = password = '' if request.method == 'POST': HttpReferrer = request.session.get('HttpReferrer') if HttpReferrer == '/login': username = request.POST['username'].lower().strip() password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return index_(request) else: err = {"err_login": {"code": 404, "message": "The username and password combination do not match our records. Please double-check and try again."}} return render(request, 'auth/auth.html', err) -
How to get details of Current User in Django Rest Framework?
I'm working on my API based on Django Rest Framework. I've managed to add current user automatically on POST request via HiddenField. Now I want to return some additional information about current user within the GET request for blog post. I've tried to access this data from CurrentUserDefault() and via source='author.username'. First one doesn't work at all, the second option breaks on Save, because author wasn't provided in request. class BlogSerializer(serializers.HyperlinkedModelSerializer): author = serializers.HiddenField(default=serializers.CurrentUserDefault()) # author_name = serializers.ReadOnlyField(source=serializers.CurrentUserDefault().name) # author_username = serializers.ReadOnlyField(source='author.username') How can I access details of Current User and append it as read-only fields? -
Not able to match field from get_user_model in django
I am working on a Books inventory project, where users can add their books and others can see them. What I'm trying on home page to show all the books, but only the owner will see the 'Edit' and 'Delete' options. Others will see 'View Details' Option. I've used get_user_model() feature of Django to get the owner of the book when the user adds new book: ... class Book(models.Model): title =models.CharField(max_length =255) author =models.CharField(max_length =255) genre =models.CharField(max_length=255) date=models.DateTimeField(auto_now_add =True) owner =models.ForeignKey(get_user_model(),on_delete =models.CASCADE,) ... Now when I'm mapping the username of the user and the owner of the book, It's not working. This id the HTML template: ... {% for book in object_list %} <div class="card"> <span class="font-weight-bold">{{book.title}}</span> <span class="font-weight-bold">by {{book.author}}</span> <span class="text-muted">Genre: {{book.genre}}</span> <span class="text-muted">Owner: {{book.owner}}</span> <span class="text-muted">User: {{user.username}}</span> <div class="card-footer text-center text-muted"> {% if user.username == book.owner %} <a href ="{% url 'book_edit' book.pk %}">Edit</a> | <a href="{% url 'book_delete' book.pk %}">Delete</a> {% else %} <a href="#">Show Details</a> {% endif %} </div> </div> <br /> {% endfor %} ... I'm bringring both the username and owner seprately too for comparison. Still I'm getting show details for all the books. For Debugging I also tried equating both 'user.username' and 'book.owner' … -
Python Django - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS
I am trying to populate my model of django using the faker module, however i get an error everytime i try to run the file that my django settings are not configured. My project name is index_project there are 2 apps that i have created 1. first_app 2. second_app In the first_app there are 3 models in which i m trying to push the data. Model Name : 1. Topic 2. Webpage 3. AccessRecord this is my code : import random from faker import Faker from first_app.models import AccessRecord, Topic, Webpage import os import django os.environ.setdefaults('DJANGO_SETTINGS_MODULE', 'index_project.settings') django.setup() i am working in a venv 'myFirstDjangoApp' Error Image from cmd -
How can we use same generic UpdateView for 2 urls mappings (one with pk, and one without pk)
What I am trying to achieve is to call the generic UpdateView in 2 cases. One with pk when the Submit button is clicked - This case works fine. But, I am not able to figure out how to call the same UpdateView without the pk (from navigation bar in base.html), so that just the form is displayed, and i can go ahead and edit the form and submit it. url.py path(r'update/<int:id>', views.LinkUpdateView.as_view(), name='update'), views.py class LinkUpdateView(UpdateView): template_name = 'update.html' form_class = LinkUpdateForm success_url = "/" model = Links def get_object(self): return Links.objects.get(id=self.kwargs.get("id")) models.py class Links(models.Model): id = models.CharField(max_length=50, primary_key=True) a = models.CharField(max_length=50) b = models.CharField(max_length=50) c = models.CharField(max_length=50) d = models.CharField(max_length=50) e = models.IntegerField() forms.py class LinkUpdateForm(forms.ModelForm): class Meta: model = Links fields = [ 'id', 'a', ] base.html (Navigation bar, this is where the update shud be called, without pk and form should be displayed) <li class="nav-item"> <a class="nav-link" href="{% url 'update' %}">Update</a> </li> update.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2>Update</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Update Link</button> </form> {% endblock %} I do not want to create additional url mapping to achieve this. Can … -
Ajax Form Request Not Functioning With Django
I'm new to handling AJAX requests in Django, and am following this tutorial for it. However, despite doing exactly the same thing, it does not work as expected for me. My code is below. views.py def profile_card(request): h = UserProfileInfo.objects.all() w = PlayCount.objects.all() c = ArtistCount.objects.all() y = Friend.objects.all() friend_form = forms.FriendForm() friend_search_form = forms.SearchForm() # Music Profile global e e = h[0] global high high = 0 global art_high art_high = 0 global high_artist high_artist = '' global highSong highSong = '' for x in range(0, (len(h)-1)): if str(h[x]) == str(request.user.username): e = h[x] break else: pass if len(w) != 0: for i in w: if str(i.user) == str(request.user.username): if i.plays > high: highSong = i.song high = i.plays if len(c) != 0: for f in c: if str(f.user) == str(request.user.username): if f.plays > art_high: high_artist = f.artist art_high = f.plays e.most_played_artist = high_artist e.save() else: pass # Friends ''' global friendTag friendTag = '' for r in y: if str(r.user) == str(request.user.username): friendTag = r if request.method == "POST": if str(request.POST.get("friendName")) == str(friendTag.friend): print('asakura akio') ''' global term term = [] global r r = [] if request.method == "POST": friend_search_form = forms.SearchForm(request.POST) friend_form = forms.FriendForm(request.POST) if friend_search_form.is_valid(): … -
Heroku - module not found
I'm trying to deploy a Django app to Heroku and it keeps crashing. When I read the heroku logs -tail i get: 2020-04-11T11:59:59.614465+00:00 app[web.1]: ModuleNotFoundError: No module named 'ElasticSearch' 2020-04-11T11:59:59.614808+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [12] [INFO] Worker exiting (pid: 12) 2020-04-11T11:59:59.768200+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [4] [INFO] Shutting down: Master 2020-04-11T11:59:59.768448+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-04-11T12:00:15.321075+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=esprojectsam.herokuapp.com request_id=2c8510c8-14d2-4892-867a-3e3a82707fd1 fwd="86.43.201.27" dyno= connect= service= status=503 bytes= protocol=https My procfile contsains web: gunicorn ElasticSearch.wsgi --log-file - ElasticSearch is the name of the application, caps and all. I've tried different formats for the Procfile like web: gunicorn ElasticSearch:app but none of it has worked. -
How to get parent's value from ForeignKey (in django-REST)?
I have Banks model class and Branches model class as below : class Banks(models.Model): name = models.CharField(max_length=49, blank=True, null=True) id = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'banks' class Branches(models.Model): ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=74, blank=True, null=True) address = models.CharField(max_length=195, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) my querry is as follows : branch = Branches.objects.get(ifsc=IFSC) # where IFSC is passed in URL My serializers look like below : class BranchSerializer(serializers.ModelSerializer): class Meta: model = Branches fields = '__all__' class BankSerializer(serializers.ModelSerializer): class Meta: model = Banks fields = '__all__' When i run the mentioned query, i get the following output:(example) { "ifsc": "UTIB0000007", "branch": "NEW DELHI", "address": "STATESMAN HOUSE, 148, BARAKHAMBA ROAD", "city": "DELHI", "district": "NEW DELHI", "state": "DELHI", "bank": 13 } Here 13 (in this example) is ForeignKey, But i want the value of that bank(i.e parent) instead of the key. The desired output should look like : { "ifsc": "UTIB0000007", "branch": "NEW DELHI", "address": "STATESMAN HOUSE, 148, BARAKHAMBA ROAD", "city": "DELHI", "district": "NEW DELHI", "state": "DELHI", "bank": "BANK NAME" } Please help me with this, i am new … -
Django - form.save() is not creating ModelForm
In my Django application users send feedback about task. I'm creating this form with ModelForm, and after form.save() my object is not creating and is not uploading to database. Here are my codes: views.py: @login_required(login_url='sign_in') def task_details(request, slug): if slug: task = get_object_or_404(Task, slug=slug) today = datetime.now().date() deadline = task.task_deadline.date() time_left = deadline - today form = CreateFeedbackForm() if request.method == 'POST': form = CreateFeedbackForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = CreateFeedbackForm() messages.info(request, 'Feedback sent.') context = { 'task': task, 'form': form, 'days_left': time_left.days } return render(request, 'task-details.html', context) models.py: class TaskFeedback(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True) sender = CurrentUserField() is_solved = models.BooleanField(default=False) feedback_content = models.TextField(max_length=1000, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): return self.feedback_content forms.py: class CreateFeedbackForm(forms.ModelForm): class Meta: model = TaskFeedback fields = ['feedback_content', 'is_solved'] def __init__(self, *args, **kwargs): super(CreateFeedbackForm, self).__init__(*args, **kwargs) -
Django: BlockingIOError: [Errno 11] write could not complete without blocking
I have the following view in DJango: def index(request): try: if request.GET['format'] is None: # The variable print('It is None') except: print ("This variable is not defined") format_hare = 'XYZ' pass else: print ("It is defined and has a value") format_hare = request.GET['format'] url_get= request.GET['url'] print(url_get) print(format_hare) subprocess.Popen(['/usr/bin/zsh','/home/test.sh', url_get, format_hare]) html = "<html><body>"+url_get+"</body></html>" return HttpResponse(html) I keep getting the following error sometimes. Not all times. Traceback (most recent call last): File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/utils/datastructures.py", line 78, in __getitem__ list_ = super().__getitem__(key) KeyError: 'format' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/web_dev/django_download/download/download/views.py", line 7, in index if request.GET['format'] is None: # The variable File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/utils/datastructures.py", line 80, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'format' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/web_dev/django_download/download/download/views.py", line 10, in index print ("This variable is not defined") BlockingIOError: [Errno 11] write could not complete without blocking [11/Apr/2020 11:56:30] "GET /run-sh?url=test.com HTTP/1.1" 500 80341 How to solve this. -
What might cause Visual Studio (2019 and 2019 Preview) to have problems using crispy forms for an otherwise working simple django application?
I've a workaround for this, but flagging as I could not find any other references to this issue. I'm following the CoreyMS Django tutorials on YouTube, to get a better grip on web applications with python (I use python for some data analytics work, mostly in Jupyter notebooks nowadays, but have a hobby project which I'd like to build). Anyway, I fired up visual studio as I was aware that it has capabilities to work with python and all seemed to progress fairly well. Corey's tutorials are excellent (clear and to the point) and while there are a few nuances different from the tools used in the video's, all was going well. However, fairly early on in the series (video 6 of 17), crispy forms are introduced. install django-crispy-forms add 'crispy_forms' to the settings.py project file. {% load crispy_forms_tags %} into the relevant template update section where the form is shown to utilise cripsy as a filter: {{ form|crispy }} All straightforward and after multiple checks, no issues with typo's or similar in the code BUT: If I run from a command prompt "python manage.py runserver" the form (a new user registration page) displays without any issue with all the … -
Django display number of objects in the account model
I am currently creating a rest api. I have an account and book model. The book model has a foreign key to the account. I want to add a number_of_books field in the account model which has an int representing how many books the user has. What is the best way to implement this? Do I need to calculate from the client side? Should I create a middleware that does this? Any help is appreciated. -
How to create ViewComponent in Django?
I want to create an html containing the Menu model, and when used, only needs {% include 'menu.html'%}, no need to pass the menu variable = Menu.object.all (). It is similar to ViewComponent in ASP.NET Core -
Django Model Inheritance - Instance attributes not set properly
Alas, my code was working perfect until I decided to "fix" it and use inheritance for some linked classes. I have a UserProgram class that inherits from MyUser and Program. When I changed the class definition to UserProgram(Program, MyUser), I started getting strange behavior with my UserProgram.objects.get() function, which gets the values from a stored procedure call via get_data_pk: raw('select 1 as id, * from SP_GetUserProgram(%s,%s,%s)', params) After adding the inheritance, I see the new objects have all the inherited fields, which is fine. But their attributes are not being assigned the correct values now. For instance, maxbudget and availablebudget should both be 400000, but that is incorrectly assigned to uploaddirectoryid. Creating the UserProgram objects manually, like UserProgram(...) works fine. I'm not sure what to do here. Any ideas? Below is a simplified version of my code. models class UserProgramManager(models.Manager): def get(self, userid, programname, schoolyear): return get_data_pk(self, 'SP_DCPGetUserProgram(%s,%s,%s)', (userid, programname, schoolyear) ) class MyModel(models.Model): class Meta: managed = False abstract = True class MyUser(AbstractBaseUser): userid = models.IntegerField(primary_key=True) objects = MyUserManager() class Program(MyModel): schoolyear = models.SmallIntegerField(primary_key=True) programname = models.CharField() def __init__(self,schoolyear=None,programname=None,*args,**kwargs): super(Program, self).__init__(*args,**kwargs) self.schoolyear = schoolyear self.programname = programname class UserProgram(Program, MyUser): uploaddirectoryid = models.CharField() objects = UserProgramManager() test.py # Works … -
How to create schedule in Django
So, I want to create a schedule of training in Django. My DB models looks models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Coach(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Пользователь", related_name="coach") name = models.CharField(max_length=200) phone = models.CharField(max_length=200) desc = models.CharField(max_length=500) avatar = models.ImageField(upload_to="coach_avatars/", blank=True) def __str__(self): return self.user.get_full_name() class TypeOfTraining(models.Model): coach = models.ForeignKey(Coach, on_delete=models.CASCADE, related_name="training_type") name = models.CharField(max_length=100) desc = models.CharField(max_length=500) price = models.FloatField(default=0) def __str__(self): return self.name class TrainingSchedule(models.Model): coach = models.ForeignKey(Coach, on_delete=models.CASCADE) training_type = models.ForeignKey(TypeOfTraining, on_delete=models.CASCADE) start_at = models.DateTimeField() def __str__(self): return str(self.id) how do I display data from the database in html form that looks like an image? example: how looks schedule on HTML page I have done HTML template. but I haven't how to show data from DB in my template. P.S. Sorry for my English. -
django call .annotate context processors in DetailView
My project depending on giving users points for any thing they do (post, comment, like, favourite, ....) i created context processor to use some calculations inside several templates. My problem is i cannot call these context processors inside template without for loop Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') favourite = models.ManyToManyField(User, related_name='favourite', blank=True) class Comment(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='commenter') post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') class Profile(models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') views.py class UserDetailView(DetailView): template_name = 'user/user-details.html' queryset = User.objects.all() def get_object(self): return get_object_or_404( User, username__iexact=self.kwargs.get("username") ) settings.py 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'common.context_processors.user_counters', ], templates.html <ul class="dynamic-tabs-list"> <li class="active" data-content=".content-posts">Posts <span class="badge badge-light">{{ user.posts.count }}</span></li> <li data-content=".content-comments">Comments <span class="badge badge-light">{{user.commenter.count}}</span></li> <li data-content=".content-favourites">Favourites <span class="badge badge-light">{{ user.favourite.count }}</span></li> <li data-content=".content-points">Points <span class="badge badge-light">{{ user.total_score }}</span></li> </ul> context_processors.py def user_counters(request): user_qs = User.objects\ .annotate( user_posts_count=Count('posts', distinct=True), user_posts_score=F('user_posts_count') * 10,)\ .annotate( user_comments_count=Count('commenter', distinct=True), user_comments_score=F('user_comments_count') * 10,)\ .annotate( user_favourites_count=Count('favourite', distinct=True), user_favourite_score=F('user_favourites_count') * 10,) \ .annotate( user_likes_count=Count('likes', distinct=True), user_likes_score=F('user_likes_count') * 10, ) \ .annotate( total_score=F('user_posts_score')+F('user_comments_score')+F('user_favourite_score')+F('user_likes_score') ) context = { 'user_qs': user_qs, } return context urls.py path('profile/<username>/', UserDetailView.as_view(), name='user-detail'), Any help please ? Thanks in-advance -
In a Django migration, how can I create an object and use it as default in another field?
I already have a model Area. I want to add a new model City, like: class City(models.Model): pass class Area(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT) # new field. How to create a migration which sets the existing areas to a city (called 'Mumbai')? I know I can do migrations.RunPython but how do I get the new city's id to pass to models.ForeignKey's default param? migrations.AddField( model_name='area', name='city', field=models.ForeignKey(default=???, to='location.City'), preserve_default=False, ), -
DJANGO - Extract filtred data to excel
I have a view with a django-filter that generate a filtred table. I would like to export this filtred table. For now, I success to export the non filtred data using xlwt 2 questions : - How to extract the filtred data ? - How to apply format date and hour in excel column ? I have a model Order with the fields 'Date','Hour','Category','Item', OrderFilter is a django-filter Views.py def data(request): orders= Order.objects.all() filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date','-Hour') return render(request, 'template.html',{'orders':orders,'filter': filter}) def export_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Hour', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Order.values_list('Date', 'Hour', 'Category', 'Item__Item') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response url.py path('data/',views.data, name='data'), url(r'^export/xls/$', views.export_data, name='export_data') template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <a class="btn btn-primary" href="{% url 'export_data' %}">Export</a> <table> display the filtred table ...</table> -
Where to find all models field type in Django?
class Products(models.Model): p_name = models.TextField() sku = models.TextField() price = models.TextField() desc = models.TextField() Also please suggest me an IDE that auto suggest models fields type. currently i am using sublime text. Thanks. :) -
Using django-environ; Django admin css not found
I removed the BASE_DIR and the os import because I am using django-environ. However when I entered the admin dashboard of Django, the css is not read so I only see plain html elements. Here is how part of my settings.py looks like. import environ root = environ.Path(__file__) - 3 # get root of the project env = environ.Env() environ.Env.read_env() # reading .env file SITE_ROOT = root() DEBUG = env.bool('DEBUG', default=False) TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = tuple(env.str('ALLOWED_HOSTS', default=[])) DATABASES = { 'default': env.db('DATABASE_URL') } SECRET_KEY = env.str('SECRET_KEY') # Static and Media Config public_root = root.path('public/') MEDIA_ROOT = public_root('media') # MEDIA_ROOT = root.path('media/') MEDIA_URL = env.str('MEDIA_URL', default='media/') STATIC_ROOT = public_root('static') STATIC_URL = env.str('STATIC_URL', default='static/') ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [root.path('templates/'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] So I also put in root.path('templates') into the DIRS of TEMPLATES. What should be written instead?