Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build Django Query Expression for Window function
I have postgres query, and I want to represent it using Django QuerySet builder I have a table: history_events date -------------------------- amount 2019-03-16 16:03:11.49294+05 250.00 2019-03-18 14:56:30.224846+05 250.00 2019-03-18 15:07:30.579531+05 250.00 2019-03-18 20:52:53.581835+05 5.00 2019-03-18 22:33:21.598517+05 1000.00 2019-03-18 22:50:57.157465+05 1.00 2019-03-18 22:51:44.058534+05 2.00 2019-03-18 23:11:29.531447+05 255.00 2019-03-18 23:43:43.143171+05 250.00 2019-03-18 23:44:47.445534+05 500.00 2019-03-18 23:59:23.007685+05 250.00 2019-03-19 00:01:05.103574+05 255.00 2019-03-19 00:01:05.107682+05 250.00 2019-03-19 00:01:05.11454+05 500.00 2019-03-19 00:03:48.182851+05 255.00 and I need to build graphic using this data with step-by step incrementing amount sum by dates This SQL collects correct data: with data as ( select date(date) as day, sum(amount) as day_sum from history_event group by day ) select day, day_sum, sum(day_sum) over (order by day asc rows between unbounded preceding and current row) from data But I can not understand how to build correct Queryset expression for this Another problem - there is no data for some days, and they do not appear on my graph -
Redirect from ListView to another ListView in Django 2.1
I'm struggling with one problem for some time. I would like to trough the website in following way. Home page with links to categories -> When I go to categories then I would list all offers with this main categories. But also for given Category I would like to have posibility to filter those Category by subcategories. For now I'am fighting with step number one. Here is my code. class HomeView(ListView): context_object_name = 'category' queryset = Category.objects.all() template_name = 'accounts/home.html' class GetOffersByCategory(ListView): model = Offer template_name = 'offer/offer_list.html' context_object_name="category" def get_queryset(self): self.publisher = get_object_or_404(Category, name=self.kwargs['category']) return Offer.objects.filter(category=self.category) And my Urls path('', views.HomeView.as_view() ,name='home'), path('offers/<category>',views.GetOffersByCategory.as_view(),name='offers'), The main problem for me is to operate with urls in templates. Because I understand those simplier patterns like { url 'name' } but I don't know exacly how to create link like {% 'category:'MyCategoryFromDB' %}. I don't want to going trough the for loop, because I know my categories. I hope that explanation of my problem is correct and it will be solved with your help :) -
How to set empty date field to a default date
How do I set a default value for an empty date field. This is what i have tried but it doesn't seem to work. request.GET.get('received_date', '1/1/2000') -
Django - How to pull out a book from genre model
Im studying django. I'm trying to get every book per genre that is connected to my genre model. here's my genre model. class Genre(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name and here's my book model. class Book(models.Model): ```some fields``` genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") def display_genre(self): return ', '.join([genre.name for genre in self.genre.all()[:3]]) display_genre.short_description = 'Genre' def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs={'slug': self.slug}) and here's my attempt to pull out the book from genre with its detail def genre(request): genres = Genre.objects.all() context = { 'genres': genres } return render(request, 'catalog/genre_list.html', context) -
404-page not found error Admin login page is not showing up?
when i give the URL:http://127.0.0.1:8000 it is showing successfully installed but when i give http://127.0.0.1:8000/admin it is showing 404 page not found. Cant reach to django administration login page Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: ^admin/ The current path, admin, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
it is valueerror while iam running my project
I am not able to execute my project.it is showing valueerror when i open in browser C:\Users\sai sriram\Desktop\svnitbook>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). March 28, 2019 - 20:26:03 Django version 2.1.7, using settings 'svnitbook.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: / Traceback (most recent call last): File "C:\Users\sai sriram\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\sai sriram\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 111, in _get_response resolver_match = resolver.resolve(request.path_info) File "C:\Users\sai sriram\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py", line 493, in resolve sub_match = pattern.resolve(new_path) File "C:\Users\sai sriram\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py", line 346, in resolve kwargs.update(self.default_args) ValueError: dictionary update sequence element #0 has length 1; 2 is required [28/Mar/2019 20:26:13] "GET / HTTP/1.1" 500 65273 -
Why i'm unable to open twice a django-uploded-file?
I'm new to Django, i would like to open a uploded-file in a validator to make sure the file is good, then if it's good re-open it in my view function to exctact the data. I'm not sure if it supposed to be done like that. Tell me what you think. Here is my validator at it's simple state : def validate_file(value): with value.open("r") as sf: pass # do some checks with the data # now the file is closed and this is my view function : def home(request): if request.method == 'POST': # create 2 form form_message = Filtre_message_form(request.POST) form_spatial = Filtre_spatial_form(request.POST, request.FILES) if all((form_message.is_valid(), form_spatial.is_valid())): # if the file is good open it f = request.FILES['file'].open(mode='r') else: # create 2 empty form form_message = Filtre_message_form() form_spatial = Filtre_spatial_form() return render(request, 'home.html', locals()) And i get this error ValueError: I/O operation on closed file. Here is the error stack : Traceback (most recent call last): File "H:\workspace\test_Django\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "H:\workspace\test_Django\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "H:\workspace\test_Django\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "H:\workspace\test_Django\django_test\app_test\views.py", line 16, in home f = request.FILES['file'].open(mode='r') File "H:\workspace\test_Django\venv\lib\site-packages\django\core\files\uploadedfile.py", line 87, in … -
how to configure django-request-token?
I am trying to use django-request-token to create a temporary url to send in a confirmation email , but I'm having some difficulties. I configured everything as in: https://pypi.org/project/django-request-token/#description and I'm trying to run the public link code. it's raising me this error: \Essence\Nature\views.py", line 270, in token = RequestToken.objects.create_token( NameError: name 'RequestToken' is not defined I added the app and I added the middleware. Currently I am using the SQLite default database, I read this uses postgreSQL, so maybe it's something related? have anyone ever used this Django module? views.py # a token that can be used to access a public url, without authenticating # as a user, but carrying a payload (affiliate_id). token = RequestToken.objects.create_token( scope="foo", login_mode=RequestToken.LOGIN_MODE_NONE, data={ 'affiliate_id': 1 } ) @use_request_token(scope="foo") def view_func(request): # extract the affiliate id from an token _if_ one is supplied affiliate_id = ( request.token.data['affiliate_id'] if hasattr(request, 'token') else None ) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Nature', 'request_token', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'request_token.middleware.RequestTokenMiddleware', ] Looking forward to generate a random temporary url with a token, some structured example would be great -
Django intermediate table with a many-to-many field instead foreign key?
I have 2 models in my application: User Tower My goal is to associate many towers to a user using an intermediate table because I need to add a period of time. So I have something like this in my models: class Tower(models.Model): name = models.CharField(max_length=128) class User(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField('Tower', through='Dates') class Dates(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) tower = models.ForeignKey('Tower', on_delete=models.CASCADE) begin_date = models.DateTimeField() end_date = models.DateTimeField() But my goal was to have the field tower in class Dates to a many-to-many like this: tower = models.ManyToManyField('Tower', blank=True) So that i can associate many towers to a user in a certain period. But unfortunately django says that i need to use forgeignkey to Tower and User classes. Have any solution for this? To apply directly the many-to-many field in the intermediate table? Or I must create a new class, sort of a GroupTower, that have a many-to-many field to the Tower class? Something like this: class Tower(models.Model): name = models.CharField(max_length=128) class GroupTower(models.Model): tower = models.ManyToManyField('Tower', blank=True) class User(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField('Tower', through='Dates') class Dates(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) tower = models.ForeignKey('GroupTower', on_delete=models.CASCADE) begin_date = models.DateTimeField() end_date = models.DateTimeField() Thanks in advance. -
Django Q Queries & on the same field?
So here are my models: class Event(models.Model): user = models.ForeignKey(User, blank=True, null=True, db_index=True) name = models.CharField(max_length = 200, db_index=True) platform = models.CharField(choices = (("ios", "ios"), ("android", "android")), max_length=50) class User(AbstractUser): email = models.CharField(max_length=50, null=False, blank=False, unique=True) Event is like an analytics event, so it's very possible that I could have multiple events for one user, some with platform=ios and some with platform=android, if a user has logged in on multiple devices. I want to query to see how many users have both ios and android devices. So I wrote a query like this: User.objects.filter(Q(event__platform="ios") & Q(event__platform="android")).count() Which returns 0 results. I know this isn't correct. I then thought I would try to just query for iOS users: User.objects.filter(Q(event__platform="ios")).count() Which returned 6,717,622 results, which is unexpected because I only have 39,294 users. I'm guessing it's not counting the Users, but counting the Event instances, which seems like incorrect behavior to me. Does anyone have any insights into this problem? -
Problem with django, error logs when loading a page without noticeable other problem
i'm here because i have a problem that i really tried to resolve by myself for the last 2 days but without any result. I'm new on django and also on stackOverflow so sorry if i did stupid mistakes. I'm working on a django website with not a lot of thing for now, but i have some problems when a page load (the error doesn't happens everytime). When i load a page, i often have a hudge error log that i don't understand. Seems to be a problem with accessing to some files but i'm not sure about that. I tried many things, i reinstalled others version a python, tried with others versions of django, tried to change things in my settings. But nothing worked i'm currently using python 3.6 and: amqp==2.4.2 anyjson==0.3.3 asn1crypto==0.24.0 beautifulsoup4==4.7.1 billiard==3.5.0.5 celery==4.2.2 certifi==2019.3.9 cffi==1.12.2 chardet==3.0.4 cryptography==2.6.1 Django==2.1.7 dnspython==1.16.0 eventlet==0.24.1 greenlet==0.4.15 idna==2.8 kombu==4.3.0 monotonic==1.5 pycparser==2.19 pyOpenSSL==19.0.0 pypiwin32==223 pytz==2018.9 pywin32==224 redis==3.2.1 requests==2.21.0 six==1.12.0 smc-python==0.6.2 soupsieve==1.8 urllib3==1.24.1 vine==1.3.0 xlrd==1.2.0 xlutils==2.0.0 xlwt==1.3.0 error logs [28/Mar/2019 15:10:20] "GET /static/bootstrap.min.css HTTP/1.1" 200 8192 Traceback (most recent call last): File "C:\Users\ex.antonin.alliance\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\ex.antonin.alliance\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\ex.antonin.alliance\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\ex.antonin.alliance\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", … -
Query for ManyToMany=List
I need to solve Foo.objects.filter(object=(obj1, obj2)) Is this possible with a query or i need to solve this otherwise? Imagine we have 4 objects foo1.m2mfield = (obj1, obj2, obj3, obj4) foo2.m2mfield = (obj1, obj4) foo3.m2mfield = (obj1,) foo4.m2mfield = (obj1,obj2) I need the query return only foo4 Thanks -
Django show page of user favourites
I want to create a page where the user can see his favorite posts. How can I modify the following template to show the use favorite post ? {% if (user has any favorite posts %} show here {% else %} User has no favorite posts {% end if %} </tr> Here is the .html file <td> <form method='POST' action="{% url 'foobar:favourite_post' video.id %}"> {% csrf_token %} <input type='hidden'> <button type='submit'>Bookmark</button> </form> </td> Here is the view.py file def favourite_post(request, fav_id): video = get_object_or_404(Video, id=fav_id) if request.method == 'POST': video.favourite.add(request.user) return redirect('/foobar/%s' % fav_id) Here is the models.py file from django.contrib.auth.models import AbstractUser class ProjectUser(AbstractUser): def __str__(self): return self.email class Video(models.Model): name = models.CharField(max_length=255), videofile = models.FileField(upload_to="static/videos/"), favourite = models.ManyToManyField(ProjectUser, related_name="fav_videos", blank=True) -
How to limit the number of items displayed in Django app
I have this Django model in my newspaper app: class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) It currently displays all articles but I want to limit what is displayed to the 3 most recent articles. How is that done? -
SyntaxError: invalid syntax for a noob django project
I'm just following a tutorial on how to make a basic website through Django and I keep getting this syntax error. How do I get it to go away? please help! File "/home/reineman/Caesar/caesarmain/views.py", line 36 selected choice = question.choice_set.get(pk=request.POST['choice']) ^ SyntaxError: invalid syntax def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'caesarmain/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", I expected it to work just as the tutorial said it would, I am following an up to date tutorial as well ( although I am still very new to this, so its prob something very simple ) thank you! -
Django - How to add pagination in detailview
How can i add pagination in detail class view? here's my views.py class AuthorDetailView(NeverCacheMixin, generic.DetailView): model = Author paginate_by = 1 and the pagination code that i used, which is not working. {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-dark mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-dark mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-dark mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="btn btn-outline-dark mb-4" href="?page={{ page_obj.next_page_number }}">Next</a> {% endif %} {% endif %} -
How to serialize an array of strings?
I am taking an array of products so that the customer is able to create order for multiple products. This is my product serializer class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = 'all' This is my customer order serializer class CustOrderSerializer(serializers.ModelSerializer): price = serializers.SlugRelatedField(slug_field='price', queryset=Price.objects.all()) # product = serializers.SlugRelatedField(slug_field='product', queryset=Product.objects.all()) area = serializers.SlugRelatedField(slug_field='address', queryset=Area.objects.all()) city = serializers.SlugRelatedField(slug_field='city', queryset=City.objects.all()) product = ProductSerializer(many=True, read_only=True) class Meta: model = CustOrder fields = '__all__' -
Axios not storing Django session cookie
With a Vue frontend and Django backend either Axios won't store or Django won't send the session cookie. I've tried toggling SESSION_COOKIE_HTTPONLY in settings.py but still not able to see the cookie. Intercepting the response the CSRF cookie is sent but not the session. import axios from 'axios' import Cookie from 'js-cookie' import store from '../store' import { TokenService } from '../services/storage.service' const ApiService = { _cookieInterceptor: axios.interceptors.response.use(response => { const sessionCookie = Cookie.get() console.log('Cookie', sessionCookie) return response }), get(resource, withCredentials = false) { return axios.get(resource, { withCredentials: withCredentials }) } } And I'm sure to set withCredentials to true when making API calls. const StoreService = { detail: async function(key) { const url = `/store/${key}/` const response = await ApiService.get(url, true) return response.data } } In my Django tests I can see that the session cookie is in the response. class Test(APITestCase): def test_get(self): response = self.client.get('/store/1/') print(response.cookies['sessionid'] -
Following Django tutorial-Access denied for user 'Django'@'localhost' (using password:YES)") when I try to receive a response from Client()
When I try to follow this step in the tutorial: >>> # on the other hand we should expect to find something at '/polls/' >>> # we'll use 'reverse()' rather than a hardcoded URL >>> from django.urls import reverse >>> response = client.get(reverse('polls:index')) I get the response: django.db.utils.OperationalError: (1045, "Access denied for user 'Django'@'localhost' (using password: Yes)") I'm using WAMP Server 3.1.7, Python 3.7.2, & Django 2.1.7. (The tutorial is at this link, in case any background info I don't provide in this post is needed.) In my settings.py file, here is my snippet from the DATABASES segment: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'lab', 'USER': 'Django', 'PASSWORD': 'MYPASS', 'HOST': 'localhost', 'PORT': '3306', } } I've tried changing the User, but this doesn't seem to be the location it's pulling the User from, as I still get the same error with 'Django'@... rather than 'ChangedUser'@... like I had expected. I can log in to mysql through the Command Prompt using: mysql -u Django -p Enter password: MYPASS I'm able to log in with no issues using this method. I've also tried logging in with root & granting all permissions to user Django on my database using: GRANT ALL … -
How can I create buy buttons with bootstrap and sqlalchemy?
I have an application, written in Python and using the flask framework, where people can register, log in and see products. The products have buttons but doesn't work. I want the user to be able to order anyone of these items, that includes me getting the order into a database. Also I want the user to be able to see the order in his account page. Is this possible with bootstrap and SqlAlchemy f.ex? I hope I don't have to write in the products again, since it takes a lot of time. Can someone maybe direct me to a github page where they use bootstrap and Sqlalchemy to create this? I have only tried searching for bootstrap/sqlalchemy ecommerce, but I don't get any hits. Here's a snippet of my products made with bootstrap: <div class="container"> <h1>Heiskort (Barn under 16)</h1> <div class="row"> <div class="col-md-4"> <div class="thumbnail"> <img src="/static/action-athlete-athletes-848618.jpg" alt="" class="img-responsive"> <div class="caption"> <h4 class="pull-right">500-, NOK</h4> <h4><a href="#">Dagskort</a></h4> <p>Dagskort passer de som skal kjøre 1-3 ganger i bakken en uke, f.eks at dere kommer på ferie og skal bare være her noen dager. </p> </div> <div class="ratings"> <p> <span class="glyphicon glyphicon-star"></span> <span class="glyphicon glyphicon-star"></span> <span class="glyphicon glyphicon-star"></span> <span class="glyphicon glyphicon-star"></span> <span class="glyphicon … -
How to provide a queryset for a foreign key field in django inline_formset?
I have the below forms: class Purchase_form(forms.ModelForm): class Meta: model = Purchase fields = ('date','party_ac', 'purchase') widgets = { 'date': DateInput(), } def __init__(self, *args, **kwargs): self.Company = kwargs.pop('company', None) super(Purchase_form, self).__init__(*args, **kwargs) self.fields['date'].widget.attrs = {'class': 'form-control',} self.fields['party_ac'].queryset = Ledger1.objects.filter(company = self.Company) self.fields['purchase'].queryset = Ledger1.objects.filter(Company = self.Company) class Stock_Totalform(forms.ModelForm): class Meta: model = Stock_Total fields = ('stockitem') def __init__(self, *args, **kwargs): self.Company = kwargs.pop('Company', None) super(Stock_Totalform, self).__init__(*args, **kwargs) self.fields['stockitem'].widget.attrs = {'class': 'form-control select2',} self.fields['Total_p'].widget.attrs = {'class': 'form-control',} Purchase_formSet = inlineformset_factory(Purchase, Stock_Total, form=Stock_Totalform, extra=6) My models: class Purchase(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True) date = models.DateField(default=datetime.date.today,blank=False, null=True) party_ac = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger') purchase = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger') class Stock_Total(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True) purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') I want to make a queryset for the inline form field stockitem that it will filter the result in the form according to request.user and company as I have done it for the normal Purchase_form(I have done it using get_form_kwargs(self) in normal form). I am having a difficulty to do a queryset in inlineform. I want to do something like this in my inline_form: self.fields['stockitem'].queryset = Stockdata.objects.filter(company = self.Company) As I have done in normal forms. Any idea anyone how to do this? … -
I tried to output the action.url attribute value using console.log. using jquery but undefined
I tried to output the action.url attribute value using console.log. using jquery but undefined The result is undefined I think something went wrong. I do not know what's wrong. I would appreciate it if you could tell me where the wrong place is. $ (document) .ready (function () { $ ('# comment_form'). submit ((e) => e.preventDefault (); <! - console.log ("You have clicked on the comment input button") -> var $ form = $ (this); console.log ("$ form:", $ form) var url = $ form.attr ('action'); console.log ("url (request to save comment):", url); }} }); github: https://github.com/hyunsokstar/ask_class/blob/master/blog/templates/blog/post_detail.html https://github.com/hyunsokstar/ask_class/blob/master/blog/views_cbv.py -
Django redirect after login is going in infinite loop
This question has been answered earlier but those solutions are not working for me. My setup have Django 1.9 and MongoDB as backend. I have custom user model. I have a webpage where I am uploading files. that flow is working fine. Now I have to make that page login protected. When I am trying to access https://localhost/upload it is redirecting me to https://localhost/login_page?next=/upload I am giving correct credentials and I can see in django logs that it is redrecting me to /upload but again pointing me back to login page. models.py class Uploadedfiles(models.Model): docfile = models.FileField(upload_to='uploads') views.py from django.contrib.auth.decorators import login_required import os @login_required() def uploadfiles(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): newdoc = Uploadedfiles(docfile=request.FILES['docfile']) newdoc.save() return HttpResponseRedirect(reverse('upload')) else: form = UploadForm() # A empty, unbound form ufiles = Uploadedfiles.objects.all() return render( request, 'upload.html', {'ufiles': ufiles, 'form': form} login_page.html <div> {% if next %} <form action="/login/?next={{ request.path }}" method="post" > {%else%} <form action="/login_page/" method="post" > {% endif %} {% csrf_token %} <p><b>Login</b></p> <input type="email" name="email" placeholder="Email" required=""> <input type="password" name="password" placeholder="Password" id="new_password"> <span id="message"></span> <button type="submit" name="Login"><b>Login</b></button> </form> </div> login view def LoginPage(request,*args, **kwargs): msg = "Please provide details" next = request.POST.get('next', request.GET.get('next', '')) if … -
Unable to read Django FileField?
I am trying to read from Django Filefield, as can be seen in my Django Model: import os import win32api from django.db import models from custom.storage import AzureMediaStorage as AMS class File(models.Model): ''' File model ''' file = models.FileField(blank=False, storage=AMS(), null=False) timestamp = models.DateTimeField(auto_now_add=True) remark = models.CharField(max_length=100, default="") class File_Version(File): """ Model containing file version information """ version = models.CharField(max_length=25, default="") @property def get_version(self): """ Read all properties of the given file and return them as a dictionary """ props = {'FileVersion': None} # To check if the file exists ? ### This returns FALSE print("Is the file there? ", os.path.isfile(str(File.file)) ) But os.path.isfile() keeps returning False. How do I read from FileField, into my custom model ? -
django application static files not working in production
static files are not working in production even for the admin page. I have already checked all the given answers STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') the above code is my settings