Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /users/login/
'learning.logs' is not a registered namespace. Request Method: GET Request URL: http://localhost:8000/users/login/ Django Version: 2.2.7 Exception Type: NoReverseMatch Exception Value: 'learning.logs' is not a registered namespace settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # my_apps 'learning_logs', 'users', ] learning_logs\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/',include('users.urls', namespace='users')), path('',include('learning_logs.urls', namespace='learning_logs')), ] users\urls.py from django.urls import re_path, path, include from django.contrib.auth.views import LoginView from . import views app_name = 'users' urlpatterns = [ # log in page path('login/', LoginView.as_view(template_name='users/login.html'),name='login'), ] learning_logs\urls.py from django.urls import re_path from . import views app_name = 'learning_logs' urlpatterns = [ # homepage re_path('^$', views.index, name='index'), # show all topics re_path('^topics/$', views.topics, name='topics'), # show dedicated topic re_path('^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), # added new topic re_path('^new_topic/$', views.new_topic, name='new_topic'), # added new entry re_path('^new_entry/(?P<topic_id>\d+)/$', views.new_entry, name='new_entry'), # edit entry re_path('^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry, name='edit_entry'), ] login.html {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">log in</button> <input type="hidden" name="next" value="{% url 'learning.logs:index' %}" /> </form> {% endblock content %} base.html <p> <a … -
Django, static files, and horizontal scalabilty
I am making a website in Django, and I am trying my best to make sure it is horizontally scalable. Due to the application being horizontally scalable, I am unable to save Images that users upload locally, in the media folder. I was wondering what are some ways I could save the images that the users upload, in such a way that would allow my application to be horizontal scalable? I do have a MariaDB Galera Cluster that I use to store other data, but it seems like saving images in a shared database might not be the best idea due to performance reasons (Storing Images in DB - Yea or Nay?). If I attempt to use the media folder, are there any solutions that could sync storage (folder) between different instances of the application? In general, what are some good practices for serving(download/upload) static content like images for horizontally scalable websites, and does Django provide anything to assist with this matter out of the box? -
Duplicate queries with inline_formset
In my web application I managed to create an inline_formset that works well. Problem now is when I have let's say 200 rows, each field that has foreign key is called 200 times to generate the drop down menu. I tried to use prefetch but queries are still duplicated, can you please help how to make query only once to get list of dropdown menu ? in forms.py class IssueForm(forms.ModelForm): class Meta: model=Issue fields=('__all__') IssueFormset=inlineformset_factory(IssuesList, Issue, form=IssueForm,extra=0) in views.py class IssuesListUpdateView(UpdateView): model=IssuesList fields='__all__' # ovewrite get_context_data to add formset as an additionnal parameter def get_context_data(self, **kwargs): context = super(IssuesListUpdateView, self).get_context_data(**kwargs) if self.request.POST: # if Save All issues button submitted if 'save_all' in self.request.POST.keys(): formset = IssueFormset(self.request.POST, instance=self.object) # sending formset to the template context['issues_formset'] = formset # save in the DB (saves only what has changed) #https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#saving-objects-in-the-formset # if formset.is_valid(): formset.save() # re-update context with new formset, this is need to refresh table in case of deleting an object # without this, issue is deleted but still visible in the table context['issues_formset'] = IssueFormset(instance=self.object) else: # sending formset to the template issues_formset=IssueFormset(instance=self.object) for form in issues_formset: form.fields["si"].queryset=Si.objects.prefetch_related('si_issues').\ all().filter(product__name='test') context['issues_formset'] = issues_formset return context In template: <form method="post">{% csrf_token %} <!-- … -
How could I make the pop up box stay on the screen so I can press the Ok button before it exits
What I am trying to do is after user click the update button the pop up box shows up on the screen then i can click the ok button to confrim or exit it. But on my code right now it just auto matically close the box after it shows up. Here is my JS if ($(document).find("#show_pop").val() == 1){ swal.fire({ title: "Updated Successfully!", text: "", type: "success", confirmButtonText: "OK" }).then(function(i){ }) } This is from my templates. <input id="show_pop" name="show_pop" value="{{ success }}" type="hidden" readonly> This is from my views.py just on the bottom part.... employee.save() context = { "success": 1, } print(context) return render(request, "index.html", context) -
How to create a membership record for a new user with django_rest_auth and django rest framework
I'm trying to create an invite/acceptance workflow with Django Rest Framework and Django Rest Auth. I have my initial account creation working just fine. Then a user creates a team, no problem. That owner now sends invites. Cool. Email's go out and the invitee get's the email with an ID for the team that they are being invited to. Here's where I'm struggling. There is a membership model that connects a team and a member. When a user has been invited registers, I want to create that membership record. So, where do I put that membership creation method? Is it in the serializer or the view? Django Rest Auth RegistrationView calls the save method of the RegistrationSerializer here. The serializer returns the created user to the view for the response. I know I need to create the membership record AFTER the user is created otherwise there isn't a user to add to membership. But I can't figure out where to do this? I was thinking of creating a create_membership method that is fired after the create method is run, but that isn't working. Something like this: def create_membership(self): team = "6edb0a55-199a-4aae-aa40-e7313186136b" return Membership.objects.create(team__id=team, member=self.user) Then calling it like this (this … -
Logo image in the navbar displays only on home page
The image of my logo on the navbar displays only on the home page, what should I do to fix it? That's root for the image on the navbar: <a class="navbar-brand waves-effect" href="/"> <img src="media\logoBrand.png"> </a> urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('core.urls', namespace='core')) ] if settings.DEBUG: import debug_toolbar urlpatterns += [path('__debug__/', include(debug_toolbar.urls))] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And urls.py core: from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import ( ItemDetailView, CheckoutView, HomeView, OrderSummaryView, add_to_cart, remove_from_cart, remove_single_item_from_cart, PaymentView, AddCouponView, RequestRefundView ) app_name = 'core' urlpatterns = [ path('', HomeView.as_view(), name='home'), path('checkout/', CheckoutView.as_view(), name='checkout'), path('order-summary/', OrderSummaryView.as_view(), name='order-summary'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), path('add-to-cart/<slug>/', add_to_cart, name='add-to-cart'), path('add-coupon/', AddCouponView.as_view(), name='add-coupon'), path('remove-from-cart/<slug>/', remove_from_cart, name='remove-from-cart'), path('remove-item-from-cart/<slug>/', remove_single_item_from_cart, name='remove-single-item-from-cart'), path('payment/<payment_option>/', PaymentView.as_view(), name='payment'), path('request-refund/', RequestRefundView.as_view(), name='request-refund') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So when i got to homepage the image is displaying, but when I go to let say /checkout/ i get an error in the console: Not Found: /checkout/media/logoBrand.png I am not sure why does it go to this directory Settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' … -
django template timeuntil timezone
I am rendering some meetings with django templates. {% for meeting in m %} <td>{{ meeting.start|date:"j F Y, g:i A" }}</td> <td>{{ meeting.start|timeuntil }}</td> {% endfor %} and view code now = datetime.datetime.now() + datetime.timedelta(hours=-5) m = Meeting.objects.filter( start__gte=now, status=Meeting.PENDING ).order_by("-start") context = { "m": m, } return render(request, "meetings/home.html", context) produces a table like Time Requested Time Pending (hrs) 7 December 2019, 12:00 AM 2 days 5 December 2019, 12:00 AM 12 minutes 4 December 2019, 11:00 PM 0 minutes my browser is in EST time and the api is UTC. The start time is rendered in local time correctly. But the timeuntil countdown is not in the localtime. Is there a good way to achieve the desired output? So far the best thing I can think of is to compute another datetime column with the client's timezone difference applied. Then the template could simply render {{ meeting.start_local|timeuntil }}. -
Programatically create Redirects in Wagtail
Is there a way to programatically create functioning Redirect objects in Wagtail? I am trying the obvious (naively creating the object): Redirect.objects.create(old_path='/test', redirect_link='https://stackoverflow.com') This creates a Redirect that is visible in the Wagtail admin panel, however navigating to /test simply 404s without redirecting. However, if I then save the Redirect from the admin panel, it suddenly works. Is there some special post-save logic I need to run in order to activate the redirect? I looked through the source and could not find anything. -
Pagination menu changing length
I'm paginating some data from a django model. My issue is that I don't know how to control the menu for the pages. I'd like it to show maybe 10 page links at a time and gradually move across. This works to a degree, as it moves forward it will show more, so if on page 1 it will show 1-10, if on page 2 it will show up to 11. The problem is I can't control this in a static fashion. I would like to show 1-10 and then once it gets to 6, display 2-11 and so on. it works from 6 onwards, the problem is at the beginning it will show 1-5, then 1-6, then 1-7 until it gets to 6 when it will look correct. I hope this makes sense.... Here's my html: {% if contacts.has_other_pages %} <ul class="pagination"> {% if contacts.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ contacts.previous_page_number }}">Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#">&laquo;</a> </li> {% endif %} {% if contacts.number|add:'-4' > 1 %} <li class="page-item"> <a href="?page={{ page_obj.number|add:'-5' }}">&hellip;</a> </li> {% endif %} {% for i in contacts.paginator.page_range %} {% if contacts.number == i %} <li class="page-item active"> <a … -
How to have CSS border span the length of the page but have elements remain inside container?
I am trying to create a navigation bar. I have used bootstrap for the body of my site and would like the navigation bar to span the same width. However, I want the border to span the full width; so that the elements 'Home, Learn, Progress, etc' appear to be right above the things in the actual page but not so that the border is cut off. TIA <div class="navbar container"> <div class="navbar-left"> {% url 'quizapp-home' as url %} <a href='{{ url }}' {% if request.path|slice:":6" == url %} id="current" {% endif %}><i class="fas fa-home"></i> Home</a> {% url 'quizapp-learn' as url %} <a href='{{ url }}' {% if request.path|slice:":7" == url %} id="current" {% endif %}><i class="fas fa-pencil-ruler"></i> Learn</a> {% url 'progress' as url %} <a href='{{ url }}' {% if request.path|slice:":10" == url %} id="current" {% endif %}><i class="fas fa-chart-line"></i> Progress</a> </div> <div class='navbar-right'> {% if user.is_authenticated %} {% url 'profile' as url %} <a href='{{ url }}' {% if request.path|slice:":9" == url %} id="current" {% endif %}> Profile</a> {% url 'logout' as url %} <a href='{{ url }}' {% if request.path|slice:":8" == url %} id="current" {% endif %}>Logout</a> {% else %} {% url 'login' as url %} <a … -
Django: ListView Pagination - This page has no results
I'm using a ListView to show all products from model UnitaryProduct. I've set pagination to 9, as there are 12 products for a category the page_num is 2. But when I go to the page 2, I get: "This page has no results". File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\paginator.py", line 52, in validate_number raise EmptyPage(_('That page contains no results')) django.core.paginator.EmptyPage: Esa página no contiene resultados [04/Dec/2019 17:12:03] "GET /catalogo?page=2 HTTP/1.1" 500 200977 HTML: <div class="d-flex justify-content-between"> <div class=""> <form method="get" action="{% url 'shop:catalogo' %}"> <div class="input-group"> <div class="input-group-prepend"> <label class="input-group-text" for="inputGroupSelect01">Categorías</label> </div> <select class="custom-select" searchable="Search here.." value={{filtro}} name="filtro"> <option value="todas" disabled selected>Seleccionar categoría</option> <option value="todas">Todas</option> <option value="celulares">Celulares</option> <option value="programacion">Programación</option> <option value="videojuegos">Videojuegos</option> <option value="cine">Cine</option> <option value="series">Series de TV</option> <option value="anime">Anime</option> <option value="musica">Música</option> </select> <div class="input-group-append"> <input class="btn btn-outline-secondary" type="submit" name="buscar" value="Buscar" style="margin-bottom: 0px;" /> </div> </div> </form> </div> <div class=""> {% if is_paginated %} <nav aria-label="..."> <ul class="pagination"> <li class="page-item disabled"> <span class="page-link">Anterior</span> </li> {% for i in page_obj.paginator.page_range %} <li class="page-item"><a class="page-link" href="/catalogo?page={{ i }}">{{ i }}</a></li> {% endfor %} <li class="page-item"> <!--<a class="page-link" href="/catalogo?page={{ page_obj.next_page_number }}"></a>Siguiente</a>--> </li> </ul> </nav> {% endif %} </div> </div> ListView: class CatalogoListView(ListView): model = UnitaryProduct template_name = "shop/catalogo.html" paginate_by = 9 def get_queryset(self): filter_val = self.request.GET.get('filtro', 'todas') filter_val … -
Bad request (400) (unsupported syscall) when trying to reach container in Google Cloud Run
I have successfully deployed a Google Cloud Run instance, its showing a green checkmark and I get an address to access the container on. I can also see that the logs show that uwsgi is booted. When trying the container locally I can access it on the port I give it... I suspect that the incorrect booting of the system is due to this line: 019-12-04T21:44:45.834539783ZContainer Sandbox Limitation: Unsupported syscall setsockopt(0x3,0x6,0x9,0x29eebd3f8794,0x4,0x0). Please, refer to https://gvisor.dev/c/linux/amd64/setsockopt for more information. 2019-12-04T21:44:45.834891693ZContainer Sandbox Limitation: Unsupported syscall setsockopt(0x4,0x6,0x9,0x29eebd3f8794,0x4,0x0). Please, refer to https://gvisor.dev/c/linux/amd64/setsockopt for more information. 2019-12-04T21:44:45.835166ZuWSGI http bound on 0.0.0.0:8080 fd 4 2019-12-04T21:44:45.841985Zspawned uWSGI http 1 (pid: 3) 2019-12-04T21:44:45.844243Zuwsgi socket 0 bound to TCP address 127.0.0.1:48977 (port auto-assigned) fd 3 Does anyone have any tips on getting the container to run on Cloud Run? -
Nginx takes too long to send the network response using Django with Gunicorn
I'm developing a web application with Django, and so far everything seems ok, but I'm having a big problem with my server response, usually the first time I want to enter it takes around 20 to 40 seconds to get the response back from the server. I'm using a Linode linux virtual machine running Ubuntu 18.04, is a very cheap plan just for now with only one core CPU, 2GB of ram and 50Gb of SSD storage, however as I'm the only one accessing the website I feel it is not correct that it takes so long to response (It just happen every time I restart nginx or gunicorn, or after some time of inactivity, after it respond it start to work with a normal speed). I made a performance record with chrome dev tools and these were my results: Network result As you can see the network request took 22 seconds, and if I check the main thread I can see that chrome detects that time as idle, and the real time it takes the server to process the view is only a few milliseconds. Chrome results I also have my server with an SSL certificate, the config for … -
Is there a way to have a "nested" reverse relation ship in Django REST Framework
I have Three objects: Product, Attribute, Attribute_Category Right now they are structured like this, I start at the Product. class Product(models.Model): name_single = models.CharField(max_length=30, unique=True) Bla... bla... bla... Currently I have a ForeignKey relation from the attribute to the product and the attribute_category. class Attribute(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='products') attribute_category = models.ForeignKey('AttributeCategory', on_delete=models.CASCADE, related_name='attributes') And some more data... And at last the attribute_category. class AttributeCategory(models.Model): name_single = models.CharField(max_length=30, unique=True) Yet more things... I was thinking with this structure I can filter the objects for a specific attribute- or _category. Though now I am stuck, Is there any way I can go from the product, to the category of its attributes and then get the relevant attributes. This way I can structure my response like this: product1: [ {attribute_category1: [{attribute1}, {attribute2}] }, {attribute_category2: [{attribute3}] } ] I would like to know, how can I get the desired JSON. Am I missing something? Because it feels like I am grossly overcomplicating things. I realize that this question is incredibly messy and might be worded really bad. I will try to think up some way of making the problem worded better, if anyone has any tips on the problem, or rewording it … -
GeoDjango display map on template form from model
I am trying to build a sample website based on Django(GeoDjango) and OpenStreetMap. So far I have this simple scenario: Models.py class Parks(models.Model): park_name_en = models.CharField(max_length=256) description = models.TextField() picture = models.ImageField() geom = PolygonField() @property def picture_url(self): return self.picture.url def __unicode__(self): return self.title views.py def park_insert(request): form = ParkForm() return render(request, 'addpark.html', {'form': form}) forms.py class ParkForm(forms.ModelForm): class Meta: model = Parks fields = ('park_name_en', 'description', 'picture',) geom = forms.PolygonField() and last but not least the template addpark.html <html> <head> {{ form.media }} </head> <body> <div id="map"> <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"/> </form> </div> </body></html> When I open the template page all fields come up right, except the PolygonField() which comes up as a text. How can I display a map on the user form also (I got it working in the admin panel, but I want to create a form for inserting new parks) -
Django factory boy post_generation in field with default value don't work
I have a model with a field that is a int type, that field have a default value I'm trying to set a value in that field with post_generation but nothing is happening, the field stay with the default value, when I try to use .set I get the following error: AttributeError: 'int' object has no attribute 'set' this is the field that I'm trying to populate @factory.post_generation def priority(obj, create, extracted, **kwargs): for series in range(obj.patrimony.count()): # this is a sequence of numbers series += 1 obj.priority.set(series) and this is the model, is just a simple model class Series(models.Model): priority = models.IntegerField(_("Priority"), default=0, null=True) Can someone open my eyes please? -
Complex Query from several models in django
I'm trying to query into three models. I need to get the amount products that are in the stores region location. These are my models: class Store(models.Model): name = models.CharField(max_length=255) logo = models.URLField(null=True, blank=True) user = models.OneToOneField(get_user_model(), models.CASCADE, related_name="user_store") region = models.CharField("Departamento", max_length=100) city = models.CharField("Ciudad", max_length=100) class Product(models.Model): name = models.CharField("Nombre del Producto", max_length=255) description = models.TextField() stock = models.PositiveIntegerField() seller = models.ForeignKey(User, on_delete=models.CASCADE) Product is related with user and it is related to store, what I want to do is something like this: { "Risaralda": 1523, "Cundinamarca": 8541 } where keys "Risaralda" and "Cundinamarca" are regions and values are the product amount in these places I tried something like this products = Product.objects.filter( seller__user_store__region__in=Store.objects.filter() .values("region").distinct()) And I got products in stores regions but i need to count how many products are in every store regions thank you a lot -
Django Session Form is not JSON Serialized
I'm trying to pass data from one view to another and im getting the following error . Exception Type: TypeError at /points/k8_points Exception Value: Object of type K8Points_ClassroomForm is not JSON serializable Here is my Views.py @login_required def K8_Points_Classroom(request): context_from_k8_points = request.session['k8_points_context'] if request.method == 'POST': form = K8Points_ClassroomForm() if form.is_valid(): form.save(commit=False) form.save() return render(request, 'points/k8_points_classroom.html', {'form': form}) else: return render(request, 'points/k8_pointsclassroom.html', {'form': form} ) else: form = K8Points_ClassroomForm() return render(request, 'points/k8_points_classroom.html', {'form': form} ) context_from_k8_points = request.session['k8_points_context'] @login_required def K8_Points(request): if request.method == 'POST': form = K8PointsForm(request.POST) if form.is_valid(): form.save(commit=False) classname = form.cleaned_data.get('class_name') date = form.cleaned_data.get('date') getstudents = Student.objects.filter(class_name = classname) students = getstudents.all() form = K8Points_ClassroomForm() context = {'form': form , 'students': students, 'classname': classname,'date': date,} request.session['k8_points_context'] = context return redirect('k8_points_classroom') else: return render(request, 'points/k8_points.html', {'form': form} ) else: form = K8PointsForm() return render(request, 'points/k8_points.html', {'form': form} ) Thank you for the help in advance ! -
QQplot using python and react
I want to display a qqplot in react webapp. My backend is Django and I can create a qqplot using import numpy as np import statsmodels.api as sm import pylab test = np.random.normal(20,5, 1000) sm.qqplot(test, line='r') pylab.show() sm.qqplot returns a matplotlib figure but I need the scatter plot and line data to send back to UI. Is there way extract that from the figure or is there a better way to do this ? -
Why can I access the Apache Tika server when using PyCharm but not from the command line?
I wrote a Python 3 program in PyCharm, and the program utilizes Apache Tika's parser. The relevant code looks like this. from tika import parser ... raw = parser.from_file(file_path) When I run the program using PyCharm, it works fine. I read that Java is required in order to access Tika, but as far as I know I don't have Java installed (interestingly, this post implies that Java is also needed for PyCharm). The only issue I experience is that I receive an error message as the program starts to run. So when I run the program in PyCharm, the initial output is... 2019-12-04 14:06:11,401 [MainThread ] [WARNI] Failed to see startup log message; retrying... and then the program runs successfully without me interacting with it. Parses beautifully. Well now I'm trying to use the same sort of Tika functionality in a Django project. I've got some code in views.py inside the Django project, and I can access it easily enough through urls.py. But when I add the Tika components and do my Django 'runserver' from the command line (the only way to do it as far as I know) this is what I receive. from tika import parser ... raw … -
Change bootstrap4 button "search" text
When I click to "Search" button on my site http://junjob.ru/ I go to http://junjob.ru/search/?q=&q2=ALL How can I change text "search" to "my_search" in this link? I need http://junjob.ru/my_search/?q=&q2=ALL I am using django web-framework. And fix should support queries from form My code vacancy_list.html <div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;"> <form action="{% url 'search_results' %}" method="get"> <div class="row"> <div class="col-lg-8 col-md-6 col-xs-12"> <input name="q" type="text" placeholder="Search..." class="form-control"> </div> <div class="col-lg-3 col-md-4 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>Other</option> </select> </div> <div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;"> <button class="btn btn-primary">Search</button> <!-- BUTTON --> </div> </div> </form> </div> views.py class HomePageView(ListView): model = Vacancy template_name = 'vacancy_list/vacancy_list.html' paginate_by = 5 page_kwarg = 'vacancy' context_object_name = 'vacancies' queryset = Vacancy.objects.order_by('-published_date') def paginate_queryset(self, queryset, page_size): """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_('Page is not “last”, nor can it be converted to an int.')) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) }) def vacancy_detail(request, pk): vacancy = … -
Django Social Auth - Google: AttributeError: 'NoneType' object has no attribute 'provider'
I am receiving this error when trying to login via google, I've tried just about everything I can think of and similar issues on SO don't seem to help. I have a custom user model setup as such: models.py from django.contrib.auth.models import AbstractUser from django.db import models class Departments(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class AlluredUser(AbstractUser): departments = models.ManyToManyField(Departments) def __str__(self): return self.username forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import AlluredUser class CustomUserCreationForm(UserCreationForm): class Meta: model = AlluredUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = AlluredUser fields = ('username', 'email') Social Auth Pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details' ) Error Traceback http://dpaste.com/12TG5RZ I'm guessing it has something to do with the custom user model I created since I didn't have this problem beforehand. Any help would be much appreciated. -
Django - Multiple Select Box - Save Changes to Database
I was able to get a multiple select box working for edit mode: <section class="container"> <div> <select id="leftValues" size="5" multiple></select> </div> <div> <input type="button" id="btnLeft" value="&lt;&lt;" /> <input type="button" id="btnRight" value="&gt;&gt;" /> </div> <div> <select id="rightValues" size="4" multiple> {% for device in devices %} <option>{{ device }}</option> {% endfor %} </select> </div> </section> <div> <input type="text" id="txtRight" /> </div> </section> But when I select the save button, after making changes to the table, again in the template, edit_maintenance.html, it does not feed into the database. I'm still fairly new to this so any tips, examples, would be great. -
How can I add CSS to my Django project website?
How can i add css to my django site? Map structure: pychache static css main.css templates Now I have this in my html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Portfolio</title> {% load static %} <link href="{% static './css/style.css' %}" rel="stylesheet"> </head> <body> <p>portfolio</p> </body> </html> -
How to "load" dependent drop down upon page load?
I have a form with a dependent drop-down. This secondary drop-down is hidden whenever the primary option selected does not have any secondary options, and when the page first loads. Whenever the form is submitted, only the first field gets cleared out, since most of the time the drop-downs remain the same, however, since the script works whenever there is a change in the primary drop-down, since the load upon does not constitute a change, it just keeps the selected/submitted option on the primary drop-down, and will just display an empty secondary drop-down, even when the primary option selected does have secondary options. I got most of the JS from the drop-down from a tutorial, as I am not very familiar with it. For a more visual understanding: This is the form when the page first loads When you select an option that has secondary options, the other dropdown appears After you select a Station and submit, the Employee # clears, but the other two are supposed to remain, however, when the page reloads upon submission, it looks like this, and the station has been cleared according to the debugger since there are none technically. I don't care so much …