Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest - testing api delete
Currrently I am testing my django rest api, but I am stuck on delete method. My url looks like this path('books/shelfs/<int:shelf>/readers/<int:pk>/', views.ReaderViewSet.as_view( {'get': 'retrieve', 'delete': 'destroy', 'patch': 'partial_update'}), And My ViewSets looks like this def destroy(self, request, pk=None, *args, **kwargs): if request.data.get("book_type") is None: raise ParseError(detail="book_type is required, options are : 'global, non-global'") try: instance = self.get_object() user = self.request.user serializer = self.get_serializer(self.get_object()) ....... self.perform_destroy(instance) except Http404: pass return Response(status=status.HTTP_204_NO_CONTENT) And my test case is this def test_book_delete(self): # check if delete works book_type = {'book_type': 'global'} response = self.client.delete("/api/v1/books/shelfs/{}/" "reader/{}/".format( 1, 2), data=book_type) self.assertEqual(response.status_code, 204) But its alway 415 error The question is, how to pass this book_type in delete ? -
dynamically adding series to highcharts
I'm relative new to highcharts so I'm not that knowledgeable. But what I am trying to do is that I am trying to dynamically create series with a name and some x, y values. To get the x and y values I use two dictionaries looking like this: The X values. They are dates The Y values. They are seconds What I want to do is create a series that have the names of the keys and then they can have multiple points for x, y values. So for example at "Fiber_Mätning" I have two values in the key in both dictionaries. What I want to do is that I create a series with the name "Fiber_Mätning", and then it should have two points where I give both x and y value. So the 1st point in "Fiber_Mätning" would be x:"2020-10-28" y:"28800" and the 2nd point in "Fiber_Mätning" would be x:"2020-10-29" y:"18000" After that I would move on onto the next key in both dictionaries and do the same. So the way I create the series need to be a function that is dynamically creating series and the points depending on the amount of keys and values in the dictionaries. … -
Making API request using React
I am building a "Yahoo Finance" clone and I am having trouble fetching the users data from my own API and displaying it using React components. I have tested the API route itself and it works fine, however when trying to fetch the data from within the React component, the request is never made. (I know this because I added the line for printing "Data fetched" in order to verify) views.py: @login_required def dashboard(request): return render (request, "holdings/dashboard.html") def user_holdings(request): user = Profile.objects.get(user=request.user) positions = user.positions.all() data_response = {} data_response["holdings"] = [] for position in positions: position_data = {} position_data["symbol"] = position.symbol response = requests.get("https://www.alphavantage.co/query?function=OVERVIEW", params={"symbol": position.symbol, "apikey": "4JU2DZ6Q8876MFXK"}) data = response.json() name = data["Name"] position_data["name"] = name response = requests.get("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY", params={"symbol": position.symbol, "apikey": "4JU2DZ6Q8876MFXK"}) data = response.json() price = data["Time Series (Daily)"]["2020-10-28"]["4. close"] position_data["price"] = price data_response["holdings"].append(position_data) print("Data fetched") return JsonResponse(data_response, safe=False) dashboard.html: <div id="app" /> <script type="text/babel"> class App extends React.Component { render() { return ( <UserHoldings /> ); } } class UserHoldings extends React.Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, items: [] }; } componentDidMount() { fetch("http://127.0.0.1:8000/user_holdings") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result.holdings }); }, // … -
Bundle and Minify CSS and JS for plotly dash
I am using this package for using plotly dash for Django in one of my projects. django-plotly-dash The website I am working on expects heavy traffic and the scaling of the web app is very important for the client. Dash applications in Django are being served in an iframe and there are pages where I have multiple iframes and dash applications rendered on a single page. These iframes take ages to load due to all CSS and javascript files they are loading which is not a good user experience. I did R&D and a lot of googling but could not find a good resource in any of the forums on how can I use bundled and minified CSS and javascript files with plotly-dash. Any suggestion related to plotly-dash or Django-plotly-dash is welcome. Note: Packages used to minify and bundle Django static files will not work with this scenario as I do not control the javascript and CSS files being loaded in the dash application plotly dash handles it. (Or let me know if I am wrong.) -
Image field doestn work propertly in template [django]
I dont know why image doestn show in template... I have: MODEL.py class Ad(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200, blank=False, null=False, unique=False) image = models.ImageField(blank=False, null=False, upload_to='ads_image/') In my view I have VIEW.py class AllAdsListView(ListView): template_name = 'ads/ads_list.html' model = Ad paginate_by = 5 def get_queryset(self): return self.model.objects.all().order_by('-pk') In project settings: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') In project urls (...) path('', include('ads.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) At last my template: {% if object_list %} {% for ad in object_list %} <img src="{{ ad.image.url }}" alt="Photo"> {% endfor %} When im using only: {{ ad.image.url }} -> on wbsite is correctly dir with file: /mediafiles/ads_image/a591133ab7babbcc48b2bb7b74a45815.jpg but when I'm usint this <img src="{{ ad.image.url }}" alt="Photo"> nothing is show up ;/ -
Creating a College CMS | Which one will be suitable Django or Node
I have a Final Year Project, Now I want to create a College Management System Where students can view their result, Attendance, Fee, announcements and other activities too. It has Multiple Users ( Admin (HOD), Teachers and Students (Semester 1,2,3,4,5,6,7,8 ) ). Now my question is Which tool will be best for this kind of multiple users tasks. Let me Share your Detail Opinion. -
blog.Post: (models.E014) 'ordering' must be a tuple or list (even if you want to order by only one field). in django
I am making models for my django blog application. But upon running python manage.py makemigrations blog, I get this error message: SystemCheckError: System check identified some issues: ERRORS: blog.Post: (models.E014) 'ordering' must be a tuple or list (even if you want to order by only one field). Here is my models.py file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') class Meta: ordering = ('-publish') def __str__(self): return self.title The error says that my ordering should be a list or tuple. But it already is. I can't understand this error. Can someone please help me out? Thanks in advance -
django Social media post Automation
How can I write a script in Django that will post an image and description on all social media pages like Facebook, Instagram, Twitter, and LinkedIn? -
CSS is not connecting in HTML?
"I am aware that there are other posts on this, however, none of the answers have helped fix my issue. I am making a django project and would like to use some basic css on my page, however it does not seem to be linking. The html file is in a folder called templates, while the css is in a folder called static. Here is what I used to link my css."This is the way i linked; <link rel="stylesheet" type="text/css" src="{% static 'css/defualt.css' %}">. I tried different ways to link the css file from folder static.please bare with since I am still new in programming. please help, thnks in advance. -
Django allauth facebook login
Imm trying to use facebook login from Django allauth social login, I think i missing some config. When i try to login to using facebook it keeps greetings with a error ..... SITE: domain name = localhost:8000/ display name = localhost ERROR: Facebook has detected {AppName} isn't using a secure connection to transfer information. Until {AppName} updates its security settings, you won't be able to use Facebook to log into it. ERROR 2: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. -
pip install django_heroku ERROR: Command errored out with exit status 1:
I tried to run the command pip install django_heroku in my terminal but it gave me this error. Ive tried to run it in the virtual environment but it still doesn't work. Ive removed some of the code since it has exceeded the 30,000 character limit. I'm pretty new to Django and to programming in general so this is quite complicated for me. Please help me. Thank you very much. Last login: Fri Oct 30 11:02:23 on ttys000 john@MacBook-Pro-john ~ % pip install django_heroku Collecting django_heroku Using cached django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) Requirement already satisfied: django in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from django_heroku) (3.1.2) Requirement already satisfied: dj-database-url>=0.5.0 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from django_heroku) (0.5.0) Requirement already satisfied: whitenoise in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from django_heroku) (5.2.0) Requirement already satisfied: pytz in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from django->django_heroku) (2020.1) Requirement already satisfied: asgiref~=3.2.10 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from django->django_heroku) (3.2.10) Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from django->django_heroku) (0.4.1) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/lf/xxr916px64v56ysf7mzg19dh0000gn/T/pip-install-j_vf2_qy/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/lf/xxr916px64v56ysf7mzg19dh0000gn/T/pip-install-j_vf2_qy/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/lf/xxr916px64v56ysf7mzg19dh0000gn/T/pip-wheel-ubkf3qey cwd: /private/var/folders/lf/xxr916px64v56ysf7mzg19dh0000gn/T/pip-install-j_vf2_qy/psycopg2/ Complete output (151 lines): running … -
How to update a ManyToManyField in Django using Ajax
I am working on an app that allows users to track workouts they do at the gym. I would like the user to be able to select an area of the body they want to focus on, which will then link to a list of specific exercises. The user will be responsible for creating all the data themselves. The problem I am having is that I want to apply ajax to my forms so that the data is added without a page refresh. At the moment I am about half way there... I have an area model, and an exercise model: models.py: class Exercise(models.Model): name = models.CharField(max_length=100) class Area(models.Model): name = models.CharField(max_length=100) exercise = models.ManyToManyField(Exercise) I have a view and a template which allow the user to create an area they want to work on. The ajax code I have written for this section is working how I would like. views.py class AreaList(View): def get(self, request): form = AreaForm() areas = Area.objects.all() return render(request, 'tracker/areas.html', context={'form': form, 'areas': areas}) def post(self, request): form = AreaForm(request.POST) if form.is_valid(): new_area = form.save() return JsonResponse({'area': model_to_dict(new_area)}, status=200) else: return redirect('tracker:areas') areas.html: <form id="addAreaForm" method="post" data-url="{% url 'tracker:areas' %}"> {% csrf_token %} {{ form … -
show data from models into many html pages without give it url in Django
i have problem with my data , it's don't appear in my html page i tried do this but nothing happen and when i add url for it and open url in browser it works fine . but i don't want give it url i need just show data in page to use it in other html page like include 'test.html' i mean show data in many pages model.py : class BestArticals(models.Model): name = models.CharField(max_length=240) url = models.URLField(default="",max_length=240) image = models.ImageField(upload_to='images/',null=True, blank=True) def get_image(self): if self.image and hasattr(self.image, 'url'): return self.image.url else: return '/path/to/default/image' def __str__(self): return self.name veiws.py : def Best_Articals(request): best_posts = BestArticals.objects.all() context = {'best_posts' : best_posts} return render(request,'android/side_bar_good_posts.html',context=context) html page : {% for post in best_posts %} <ul style="text-align:right"> <li> <img src="{{post.get_image}}" height="80px" width="80px"> <a href="{{post.url}}" style="color:black"> {{post.name}} </a> </li><br> </ul> {% endfor %} what is the problem here -
How to work around Django's lack of composite keys in this complicated case?
I can't seem to figure out how to work around the lack of composite keys in Django for the following case. I'm going to write the schema I'd like using SQLite3 dialect): PRAGMA foreign_keys = ON; CREATE TABLE A ( id_a INT PRIMARY KEY, name_a TEXT ) WITHOUT ROWID; CREATE TABLE B ( id_b INT PRIMARY KEY, name_b TEXT ) WITHOUT ROWID; CREATE TABLE C ( id_c INT PRIMARY KEY, name_c TEXT ) WITHOUT ROWID; CREATE TABLE AB ( id_a INT, id_b INT, PRIMARY KEY (id_a, id_b), FOREIGN KEY (id_a) REFERENCES A(id_a), FOREIGN KEY (id_b) REFERENCES B(id_b) ) WITHOUT ROWID; CREATE TABLE BC ( id_b INT, id_c INT, PRIMARY KEY (id_b, id_c), FOREIGN KEY (id_b) REFERENCES B(id_b), FOREIGN KEY (id_c) REFERENCES C(id_c) ) WITHOUT ROWID; CREATE TABLE ABC ( id_a INT, id_b INT, id_c INT, blah TEXT, PRIMARY KEY (id_a, id_b, id_c), FOREIGN KEY (id_a, id_b) REFERENCES AB(id_a, id_b), FOREIGN KEY (id_b, id_c) REFERENCES BC(id_b, id_c) ) WITHOUT ROWID; Tables AB and BC have compound key constraints that are easily worked around using surrogate keys but table ABC has complex key constraints and cannot be implemented directly in Django. Here's some test data INSERT INTO A VALUES (1, "a1"), (2, … -
geodjango leaflet map not showing
I'm playing with Django and leaflet since a short time. It's fun, most the time, but frustrating, sometimes... Right now I'm having trouble displaying a leaflet map on my django front-end website, using a detailView and a template only. I've been looking for a solution since days and I couldn't manage it by my own, so here I am. I have no error, the container just shows blank, as if it couldn't call one of the embeded scripts properly : Here are the installed apps in my settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leaflet', 'django.contrib.gis', ] Here is my base.html : <!DOCTYPE html> {% load leaflet_tags %} <html lang=fr> <head> <title>{% block head_title %}titre{% endblock head_title %}</title> {% include 'snippets/css.html' %} {% leaflet_css %} {% leaflet_js %} </head> <body> {% include 'snippets/nav.html' %} <div class='container'> {% block content %} {% endblock content %} </div> {% include 'snippets/js.html' %} </body> </html> then my template : {% extends "base.html" %} {% block head_title %}{{ block.super }} | {{ object.nom }}{% endblock head_title %} {% block content %} <h1>{{ object.nom }}</h1> <table class="table table-sm"> <tr> <th>Catégorie</th> <td>{{ object.categorie }}</td> </tr> <tr> <th>Localisation</th> <td>{% leaflet_map "main" callback="map_init" %} <script … -
Django models/SQL How to determine the wanted "GROUP BY" part of the query?
I have a Django model ProjectName like this: class ProjectName(models.Model): name = models.CharField(_("name"), max_length=255) hasused = models.BooleanField() def __str__(self): return self.name class Meta: managed = False db_table = 'timeentry_project' It is a database view and my goal is to put the most recent projects to the top of the view and get rid of any duplicates in order to be able to provide the queryset to a ModelChoiceField as a parameter. That is also why ProjectName.objects.raw query does not solve the problem. ModelChoiceField does not accept a raw query set. That is also why I cannot use a set containing duplicates. The current situation is that I have the following queryset (Django queryset for that is OK) content: ID Name hasbeenused 81 Mossefixaus 1 80 Ladojen korjaus 0 81 Mossefixaus 0 82 Wartburg autojen koneremontit 0 The boolean value in a 'hasbeenused' column tells has the project been dealt with before or not. The used ones should be on the top of the list. The problem is that I cannot create a Django query that would produce the correct resultset that would be: ID Name max 81 Mossefixaus 1 80 Ladojen korjaus 0 82 Wartburg autojen koneremontit 0 The following … -
Comparing dates using a comparator inside Django template
I am trying to compare the end date of an event with today's date to see if the event has ended. If the event has ended, the website user would not have a button to enrol and if the event has not started or is ongoing, the user would have a button to enrol in html. I have tried this in my html template: {% if event.end_date|date:"jS F Y H:i" <= today|date:"jS F Y H:i" %} {% include 'event/includes/enroll.html' %} But the button shows whether or not the event has ended already. I wanted to add a method in my django model like this: @property def is_today(self): return self.datefinish == datetime.today().date() But I am not sure how to import the method and use it in html template then. I wanted to try to add a variable in my view like this: (Django - Checking datetime in an 'if' statement) is_today = model.end_date >= datetime.today() return render_to_response('template.html', {'is_today': is_today}) But a colleague has written a Class-based view to render the template and not sure how to add the variable to render using the class-based view. I also got an error: TypeError: '>=' not supported between instances of 'DeferredAttribute' and 'datetime.datetime' If … -
Django : NameError: name 'UserAdmin' is not defined [closed]
could you kindly help me on this one please. I just followed the code on the tutorial that I am watching and yet there's an error showed. (NameError: name 'UserAdmin' is not defined) Here's the code: admin.py from django.contrib import admin from .models import User class UserAdmin(admin.ModelAdmin): list_display = ['user_fname', 'user_lname', 'user_email', 'user_position'] admin.site.register(User, UserAdmin) models.py class User(models.Model): user_fname = models.CharField(max_length=200, verbose_name='First Name') user_lname = models.CharField(max_length=200, verbose_name='Last Name') user_email = models.EmailField( unique=True, max_length=200, verbose_name='Email') user_position = models.CharField(max_length=200, verbose_name='Position') pub_date = models.DateField(default=now) def __str__(self): return self.user_email -
Django: How to import a string variable into the django settings file from a middleware
I have a variable in my settings file, SITE_HOST_NAME, that I would want to dynamically change and update according to the current tenant domain, say, t1.leap.com. I have written a custom middleware that fetches the current tenant domain, the problem is appending the current tenant domain it generates to the settings file variable that is currently an empty string. nb: I am implementing multitenancy using Django tenants. settings.py SITE_HOST_SCHEMA = os.getenv('SITE_HOST_SCHEMA', 'http') SITE_HOST_NAME = '' SITE_HOST_PORT = os.getenv('SITE_HOST_PORT', 8000) _default_siteurl = "%s://%s:%s/" % (SITE_HOST_SCHEMA, SITE_HOST_NAME, SITE_HOST_PORT) if SITE_HOST_PORT else "%s://%s/" % ( SITE_HOST_SCHEMA, SITE_HOST_NAME) SITEURL = os.getenv('SITEURL', _default_siteurl) my_middleware.py from django.conf import settings from django.db import connection from django.utils.deprecation import MiddlewareMixin as MIDDLEWARE_MIXIN from django_tenants.utils import remove_www, get_tenant_model, get_public_schema_name from customers.models import Domain class CustomTenantMiddleware(MIDDLEWARE_MIXIN): def get_tenant(self, model, hostname, request): return model.objects.get(domain_url=hostname) def hostname_from_request(self, request): """ Extracts hostname from request. Used for custom requests filtering. By default removes the request's port and common prefixes. """ return remove_www(request.get_host().split(':')[0]).lower() def process_request(self, request): try: hostname = self.hostname_from_request(request) s = Domain.objects.get(domain=hostname) if s: settings.SITE_HOST_NAME = s.domain print(settings.SITE_HOST_NAME) except KeyError: pass # use default urlconf (settings.ROOT_URLCONF) -
Passing JSON data to React component
I am trying to develop an "Yahoo Finance"-style app using Django and React. The dashboard view creates the the JSON data for the users portfolio, and then passes it in the context to the html template, where I would like to use it to create React components. The JSON output for example, is as follows: {'PENN': {'name': 'Penn National Gaming, Inc', 'price': '56.5900'}, 'WMT': {'name': 'Walmart Inc', 'price': '140.0400'}} views.py: def dashboard(request): user = Profile.objects.get(user=request.user) positions = user.positions.all() data_response = {} for position in positions: position_data = {} response = requests.get("https://www.alphavantage.co/query?function=OVERVIEW", params={"symbol": position.symbol, "apikey": key}) data = response.json() name = data["Name"] position_data["name"] = name response = requests.get("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY", params={"symbol": position.symbol, "apikey": key}) data = response.json() price = data["Time Series (Daily)"]["2020-10-28"]["4. close"] position_data["price"] = price data_response[position.symbol] = position_data print(data_response) return render (request, "holdings/dashboard.html", { 'data_response': data_response }) dashboard.html: <div id="app" /> <script type="text/babel"> class App extends React.Component { render() { return ( <UserPosition data={{ data_response }} /> ); } } class UserPosition extends React.Component { render() { return ( ); } } ReactDOM.render(<App />, document.querySelector("#app")); </script> Additionally, I would appreciate any input on whether these API requests should be made server-side or client-side, before I get too deep into the project. -
Implementing Search Form with Django
Hello Stackoverflow community, I am having trouble with my form not rendering in Django. Here's my attempt to render an empty form in views.py. class SearchSite(forms.Form): query = forms.CharField(label="New Item", help_text="Search for any article located on the site.") def search(request): form = SearchSite() context = { "form": form, "query_matches": query_matches } response = render(request, "encyclopedia/layout.html", context) return response Here's what my urls.py file looks like: urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:page_title>", views.page, name="wiki"), path("wiki/", views.search, name="site_search") ] My layout.html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'site_search' %}" method="get"> {% csrf_token %} There should be something here {{ form }} <input type="submit"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> Create New Page </div> <div> Random Page </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> </body> </html> I have noticed two particular problems in above screenshot. Firstly, my form does not render when inside my index.html webpage, which extends layout.html. Secondly, when … -
Can Django changes model instance status when transaction.atomic rolled back?
I want order changes status when raising exception in transaction.atomic block. Does the following code work? try: with transaction.atomic(): order = Order.objects.create( status='PAYING' ) except Exception as e: order.status = 'FALIED' order.save() -
'OrderSerializers' object is not callable
Something is wrong, i try get data values in Order Model, Order Item The relationship Order and OrderItem is Many to Many The relationship Product and OrderItem is Many to Many I try read the docs about Serializer relations link docs But i always see error object is not callable in link api for Order and OrderItem. Help me to solve problem Thanks you everyone class ProductSerializers(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api:product-detail',lookup_field='slug') class Meta: model = Product fields = ('id', 'title', 'price','slug','category','describe','url') class OrderItemSerializers(serializers.ModelSerializer): tracks = ProductSerializers(many=True, read_only=True) class Meta: model = OrderItem fields = ('user', 'quantity','item', 'tracks') class OrderSerializers(serializers.ModelSerializer): tracks = OrderItemSerializers(many=True, read_only=True) class Meta: model = Order fields = ('user','ordered_date','items', 'tracks') -
How to display a spinner(loader) while downloading the file from django view
How to display a spinner/loader until file downloading in django view <button type="submit" class="buttons">Download</button> def some view(request): with fs.open("filename.pdf") as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=filename.pdf" return response -
Error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I have a strange error. I check my code over and over and can't seems to find the error. I write login function, works just fine, added logout function, works fine too. But when I tried to run the basic url, where I should go to the home page (http://192.168.2.80:8000/), it gives me this error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. I added decorators too, to restrict the pages, but can' understand why is the error. viwes.py: @login_required def index(request): return render(request, 'dashboard.html') def loginPage(request): form = AuthenticationForm() if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) if request.GET.get('next'): return redirect(request.GET.get('next')) else: return redirect('feedback:index') return render(request, 'login.html', {'form': form}) urls.py app_name = 'feedback' urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('', views.index, name="index"), ] the root urls.py: app_name = 'feedback' urlpatterns = [ path('admin/', admin.site.urls), path('', include('feedback.urls')), ] I also added these lines into my settings.py: LOGIN_URL = "login" LOGOUT_REDIRECT_URL = '/admin/' Anyone can see what I'm missing?