Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get_absoute_url issues?
1- Title link not working. When I click on the link it stays on the same page. 2- Create post not working. I get this error when I press the submit button. Error message: AttributeError at /post/create/ 'Post' object has no attribute 'get_absolute_url' urls.py from django.urls import path from .import views app_name='post' urlpatterns = [ path('index/',views.post_index, name='index'), path('<int:id>/detail',views.post_detail, name='detail'), path('create/',views.post_create, name='create'), path('<int:id>/update/',views.post_update, name='update'), path('delete/',views.post_delete, name='delete'), ] models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=120, verbose_name="Başlık") content = models.TextField(verbose_name="İçerik") publishing_date = models.DateTimeField(verbose_name="Yayımlanma Tarihi", auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post:detail', kwargs={'id': self.id}) #return "/post/{}".format(self.id) views.py from django.shortcuts import render, get_object_or_404, HttpResponseRedirect from django.http import HttpResponse from .models import Post from .forms import PostForm def post_index(request): posts = Post.objects.all() return render(request, 'post/index.html', {'posts': posts}) def post_detail(request, id): post = get_object_or_404(Post, id=id) context = { 'post': post, } return render(request, 'post/detail.html', context) def post_create(request): #if request.method == "POST": #print(request.POST) #title = request.POST.get('title') #content = request.POST.get('content') #Post.objects.create(title=title, content=content) #if request.method == "POST": #Formdan gelen bilgileri kaydet #form = PostForm(request.POST) #if form.is_valid(): #form.save() #else: #Formu kullanıcıya göster #form = PostForm() form = PostForm(request.POST or None) if form.is_valid(): post = form.save() return HttpResponseRedirect(post.get_absolute_url()) … -
how can I old login logic into a new login using form_valid?
I am trying to use the same logic as my old login to perform a more fancy login using sessions , and group permissions , but I want to achieve something. I want to send login messages as 'login_message' : 'The user has been removed' or 'login_message' : 'invalid', and later add custom html messages based on the response , but how can I grab the logic from my old login to my new login as I am using form_valid new login class Login(LoginView): authentication_form = CustomAuthenticationForm form_class = CustomAuthenticationForm template_name = 'login.html' def form_valid(self, form): login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) old login class LoginView(View): def get(self, request): return render(request, 'login.html', { 'form': AuthenticationForm }) def post(self, request): form = AuthenticationForm(request, data=request.POST) if form.is_valid(): user = authenticate( request, username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password') ) if user is not None: if user.is_active: login(request, user) return redirect('/') # home page else: return HttpResponse("A") # account disabled else: return HttpResponse("invalid_creds") settings LOGIN_REDIRECT_URL = '/account/profile' LOGOUT_REDIRECT_URL = '/' -
How to make online course with Django
I want to make an online course with Django, what modules are needed? Are there any references? -
How to Group and Sum Category with ORM-Query
Please note: Similar questions didn't help me as they have the category-foreignkey in the same class. I have a simple Invoice app with models Invoice, Position, Product and Category. The Product is bound to the Category. My target is to create a queryset that filters e. g. a specific date-range and then group all categories and build their sums Here is a screenshot of the invoice respectively of its positions: The expected result of the grouped query should look like this: Can you help me to create a query that groups and sums the categories within the filtered date-range? The only solution I was able to create was the filter of a specific date-range: queryset = Position.objects.filter(invoice__date_of_purchase__range=['2019-01-01', '2019-12-31']) models.py (which I have simplified): from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=120) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') def __str__(self): return self.name class Invoice(models.Model): invoice_code = models.CharField(max_length=15) date_of_purchase = models.DateField() customer_name = models.CharField(max_length=100) def __str__(self): return self.invoice_code class Position(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.DecimalField(decimal_places=2, max_digits=6) price = models.DecimalField(decimal_places=2, max_digits=8) total = models.DecimalField( decimal_places=2, max_digits=8, blank=True, null=True) # is calculated in view … -
Django Join on Composite foreign key
I have a relationship as Follows class Tblrfqvendor(models.Model): """RFQ Master for Vendors This typical represents the same RFQ sent to different people """ ven_rfqid = models.ForeignKey(Tblrfqmaster, db_column='RFQID', on_delete=models.DO_NOTHING, primary_key=True,related_name="venrfq") # Field name made lowercase. lineitem = models.IntegerField(db_column='LineItem') # Field name made lowercase. vendorid = models.CharField(db_column='VendorID', max_length=10) # Field name made lowercase. class Meta: managed = False db_table = 'tblRFQVendor' constraints = [constraints.UniqueConstraint(fields=['ven_rfqid', 'lineitem', 'vendorid'], name='unique_vendor_rfq')] ordering = ['-lastrevdate'] class Tblrfqitem(models.Model): """A Line Item for a particular Master Vendor RFQ """ item_rfqid = models.ForeignKey(Tblrfqvendor, db_column='RFQID', on_delete=models.DO_NOTHING, primary_key=True,related_name='items') # Field name made lowercase. lineitem = models.ForeignKey(Tblrfqvendor,on_delete=models.DO_NOTHING, db_column='LineItem') # Field name made lowercase. itemid = models.CharField(db_column='ItemID', max_length=100, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'tblRFQItem' constraints = [constraints.UniqueConstraint(fields=['item_rfqid','lineitem'], name='unique_item')] Now with the related name being items, I write Tblrfqvendorinstance.items.all() However this forms a query where a join is only created on the item_rfqid. Is there a way to help enforce joining on both item_line number and item_rfqid ? A work around I have is to do the following. ven_rfqs = Tblrfqmaster.objects.prefetch_related( Prefetch('venrfq', to_attr='line_items',queryset=Tblrfqvendor.objects.filter(vendorid=vendor_pk).select_related('items') .annotate(itemid = F("items__itemid")) .filter(lineitem=F('items__lineitem')) ) ).filter(venrfq__vendorid=vendor_pk) -
Django Multiple Databases Connections
I have two databases and router defined in my settings.py 'default': { }, 'primary': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ... }, 'auth': { // similar to primary } DATABASE_ROUTERS = ['pw_inspector.database_router.AuthRouter','pw_inspector.database_router.PrimaryReplicaRouter'] I am running into an issue where Django doesn't recognize the tables/relations within primary database. I tried reordering AuthRouter and PrimaryRouter but then Django won't recognize the User relations from auth database. Any suggestions? I tried making one of them the default but that doesn't solve the issue either. -
Django Model Occurrence Count
I'm fairly new to Django and I'm in need of assistance with my models. class Region(models.Model): region_name = models.CharField(max_length=10) def __str__(self): return self.region_name class Property(models.Model): prop_name = models.CharField(max_length=200) region_name = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name="Region") prop_code = models.IntegerField(default=0, verbose_name="Property") def __str__(self): return self.prop_name class Sale(models.Model): prop_name = models.ForeignKey(Property, on_delete=models.CASCADE) employee = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Person") prop_state = models.CharField(null=True, max_length=5, choices=[('new','New'),('used','Used')]) date = models.DateField('Sale Date') def __str__(self): return '%s : %s %s - %s' % (self.prop_name.prop_name, self.employee, self.date, self.prop_state) Here are my models. Property inherits from Region and Sale inherits from property. What I want to do is count the number of sales in a region and the number of sales on a specific property. However I do not know which would be the best way to approach this. I've tried using a lambda as a model field that uses the count() function but I wasn't able to see much success with that. Please let me know if you have any suggestions. -
Django REST Framework - Query models by field value
I have a Building model for which I have created a Serializer and ModelViewSet. Now I am able to get all Buildings with /api/buildings/ and get a Building object with /api/buildings/3 where 3 is the Building Id. How do I query for a Building object with a particular attribute value? For example, how do I get the Building object with name == "hospital"? Something like /api/buildings?name=hospital does not work. views.py class APIBuildingsViewSet(viewsets.ModelViewSet): queryset = Building.objects.all() serializer_class = BuildingSerializer models.py class Building(models.Model): building_id = models.AutoField('ID', auto_created=True, primary_key=True) name = models.CharField('Name', max_length=125, null=True, blank=False, unique=False) address = models.CharField('Address', max_length=256, null=False, blank=False) user_id = models.ForeignKey('accounts.User', on_delete=models.CASCADE, default=1) def __str__(self): return self.name serializers.py class BuildingSerializer(serializers.ModelSerializer): class Meta: model = Building fields = ('building_id', 'name', 'address', 'user_id') urls.py router = DefaultRouter() router.register(r'buildings', views.APIBuildingsViewSet, base_name='buildings') urlpatterns = [ url(r'^api/', include(router.urls)), ] -
How can I use cPython to profile a Django command I use in docker-compose?
My program is a shell command that I call thru django in docker. docker-compose exec foo ./manage.py bar Where foo is my app and bar is my python script I want to profile. I wanna know everything that cPython can tell me about what's happening in bar, without having to write cPython code inside my code but rather to use the shell command (once SSH to the docker container) like: /usr/bin/python3.7 -m cProfile -s cumtime ./manage.py bar But then I ran into issues of django.core.exceptions.ImproperlyConfigured: The app module <module 'apps.foo' (namespace)> has multiple filesystem locations (['/app/apps/foo', './apps/foo']); you must configure this app with an AppConfig subclass with a 'path' class attribute. Am I having a django setup issue, or is it a bad way of calling cPython within docker, or ...? -
Django Elastic Search DSL with faceted Search
I am using ElasticSearch-DSL with my Django App to search for products. I am able to fetch the results and put them in my template (search.html) and it is working as expected. I did some research but could not figure out how to add faceted search to my templates and how to implement faceted search. My documents.py from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from products.models import Products from elasticsearch_dsl import FacetedSearch, TermsFacet, DateHistogramFacet @registry.register_document class CarDocument(Document): class Index: # Name of the Elasticsearch index name = 'cars' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 1} class Django: model = Products # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'body_id', 'product_make', 'model_name', 'product_id', 'model_id', 'variant', 'transmission', 'bodystyle', 'yom', 'status', 'ex_showroom', 'registration_fees', 'insurance', 'handling_charges', 'fastag', 'on_road_price', 'min_price', 'max_price', 'rating', ] # Ignore auto updating of Elasticsearch when a model is saved # or deleted: # ignore_signals = True # Don't perform an index refresh after every update (overrides global setting): # auto_refresh = False # Paginate the django queryset used to populate the index with the specified size … -
Set Default Stylesheet Class for Images Uploaded using Django-CKEditor
I am using CK-Editor and Django (via django-ckeditor) to create a rich text field and upload images. However, some images are pretty large and I'd normally use bootstrap to make them responsive with the image-fluid class. For Images uploaded with the CKEditor in Django I can set this class manually by going into Image Properties > Advanced > Stylesheet Classes and setting it to image-fluid. Is there any way to set this class as a default? Currently I have tried the following in my settings.py with no luck: CKEDITOR_CONFIGS = { 'default': { 'stylesSet': [ { 'name': 'Image-Fluid', 'element': 'img', 'attributes': {'class': 'img-fluid'}, }, ], }, } Any idea if it is possible to set a deafult class for images uploaded using CKEditor? Thanks. -
I am having difficulties getting data from an associative model's parent model in Django
I am building an app for a charity organization that performs service projects. Users click sign up buttons for corresponding projects and are redirected to a page that displays other users enrolled in particular projects here is an image of the page. The problem is I can only display project participants by id when I want to list them by first and last name. # models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' chapter = models.ForeignKey('Club_Chapter',on_delete=models.PROTECT) REQUIRED_FIELDS = [] objects = UserManager() # Projects Availabe for Certain Clubs """ class Service_Project(models.Model): project_ID = models.IntegerField(primary_key=True) club_chapter = models.ForeignKey('Club_Chapter',on_delete=models.PROTECT) project_title = models.CharField(max_length=15, help_text='Enter field documentation') project_location = models.CharField(max_length=15, help_text='Enter field documentation') # Model where project sign up data is stored class ProjectRegistration(models.Model): project = models.ForeignKey(Service_Project, verbose_name='Project',on_delete=models.PROTECT) user = models.ForeignKey(User, related_name='volunteers', verbose_name='Worker',on_delete=models.PROTECT) time_registered = models.DateTimeField() service_hrs = models.DecimalField(max_digits=5, decimal_places=2) # views.py class ExtraContextMixin(object): def get_context_data(self, **kwargs): context = super(ExtraContextMixin, self).get_context_data(**kwargs) context.update(self.extra()) return context def extra(self): return dict() class DetailView(ExtraContextMixin, generic.DetailView): model = Service_Project template_name = 'catalog/detail.html' def extra(self): extra = ProjectRegistration.objects.all() return dict(extra = extra) <!-- detail.html --> {% for i in extra %} {% if extra and service_project.project_ID == i.project_id %} <ul class="list-group"> <li class="list-group-item d-flex … -
Django 'User object hasn't attribute META'
(SORRY FOR BAD ENG) When i make custom form (forms.py) class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True, label='Email') first_name = forms.CharField(required=True, label='First name', max_length=100) last_name = forms.CharField(required=True, label='Last name', max_length=100) class Meta(UserCreationForm.Meta): model = User fields = ["username", "first_name", "last_name", "email", "password1", "password2"] def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise ValidationError(self.fields['email'].error_messages['exists']) return self.cleaned_data['email'] Here is my views def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) user.save() login(user) return redirect('/index/') else: form = UserRegisterForm() def login(request): context = dict() return render(request, "dashboard/login.html", context) def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) user.save() login(user) return redirect('/index/') else: form = UserRegisterForm() context = {'form':form} return render(request, 'dashboard/register.html', context) def dashboard(request): return render(request, "dashboard/dashboard.html") Django returnig me "AttributeError at /register/ 'User' object has no attribute 'META'" idk why? I'd like to keep the sequence How to fix this? Write where I was wrong -
Why my get_queryset doesn't work when used on Model with OneToOneField
Hello Django Programmers, I have an issue which I don't understand. Here is my model class: class Profile(models.Model): name = models.CharField(max_length=50) employeeView = models.BooleanField(default=True) owner = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE, null=True) This class extends my User Model. Please notice that I'm using here OneToOneField in relation to User Model. This model is serialized with that Serializer: class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ( 'url', 'pk', 'name', 'employeeView') And finally I have view which I use to process GET (list) and POST requests to the database: below view works fine (for GET request), but it gives me all Profiles related with all users class ProfileList(generics.ListCreateAPIView): permission_classes = [ permissions.IsAuthenticated ] serializer_class = ProfileSerializer name = 'profile-list' queryset = Profile.objects.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) Because I would like to create view which could give me only profile for My user, I modifiet above view like so: class ProfileList(generics.ListCreateAPIView): permission_classes = [ permissions.IsAuthenticated ] serializer_class = ProfileSerializer name = 'profile-list' ##queryset = Profile.objects.all() def get_queryset(self): return self.request.user.profile.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) But when I send the GET request I get this error: {code} 'Profile' object has no attribute 'all' {code} So my question here is more general. Above view will work … -
how can i make jsonresponse that can be access by everyone without redirecting them to login django?
how can i make jsonresponse that can be access by everyone without redirecting them to login django? is there anyway to make a function public like def json_response(request): t={'tawfiq':'Accountant'} JsonResponse(t) please i just read about api and allowany but I couldn't figure out how to do it I will be very grateful if you helped me -
Unique text message objects ordered by date query Django ORM
I have a text message model as follows: class TextMessage(models.Model): from_phone_number = models.CharField(max_length=25) to_phone_number = models.CharField(max_length=25) date_of_message = models.DateTimeField(auto_now_add=True) message_body = models.TextField() I am trying to return a Django queryset (it MUST be a queryset) where the from_phone_numbers are unique AND the text message is the most recent text message. So for example if I had the text messages: **id**| **from_phone_num** | **to_phone_num** | **date_of_message**| **Message body** | 7;"19991112222";"19996667777";"2019-11-13 15:07:53.726911-07";"dupe message 2"; 4;"19993334444";"19996667777";"2019-11-13 13:50:05.921257-07";"dsfsdfsf"; 3;"19992222222";"19995552323";"2019-11-13 13:49:18.503679-07";"TEST123"; 5;"19991112222";"19996667777";"2019-11-13 15:07:21.834347-07";"dupe message 1"; the queryset returned would be: **id**| **from_phone_num** | **to_phone_num** | **date_of_message**| **Message body** | 7;"19991112222";"19996667777";"2019-11-13 15:07:53.726911-07";"dupe message 2"; 4;"19993334444";"19996667777";"2019-11-13 13:50:05.921257-07";"dsfsdfsf"; 3;"19992222222";"19995552323";"2019-11-13 13:49:18.503679-07";"TEST123"; This is the query I have already tried: TextMessage.objects.order_by('date_of_message','from_phone_number').distinct('date_of_message', 'from_phone_number') but it didn't work. Any help would be appreciated! -
Displaying a message as a popup/alert in Django?
I have a form that, upon submission it just redirects to itself again. I'm trying to display a message that says "You have entered (work_area)." Currently, I only got the displaying part without the variable in it, but it shows within the html after the user submits it. I would like it to be a popup or alert message that the user can close after they see it, but I don't understand how this would work in Django. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm #success_message = "You have logged into %(work_area)s" def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(station_number=station)).update(time_in=datetime.now()) messages.info(self.request, "You have entered") return HttpResponseRedirect(self.request.path_info) enter_exit_area.html {% extends "base.html" %} {% block main %} <form id="warehouseForm" action="" method="POST" class="form-horizontal" novalidate > {% csrf_token %} {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <div> <div> <label>Employee</label> {{ form.employee_number }} </div> <div> <label>Work Area</label> {{ form.work_area }} </div> <div> <label>Station</label> {{ form.station_number }} </div> </div> <div> <div> <button type="submit" name="enter_area" … -
How can i get django to process media files on production?
How can i get django to process media files on production when DEBUG = False on heroku server? I know that it’s better not to do this and that this will lead to a loss of performance, but my application is used only by me and my cat, so I don't think that this will be unjustified in my case. -
Loading geojson data from data served through Django REST API to a bootleaf framework web page
I have customized the script as shown below, to load other layers from a different server which contain samples of 'copy pasted' geojson data files together with their icons for display. The problem is when I use the java script to load the geojson data served from the Django web client <script src='https://code.jquery.com/jquery-3.4.1.min.js'></script> <script> $.get( "https://websiteurl/geojsonfile/list/", function( data ) { console.log( data ); alert( "Load was performed." ); }); </script> The script works but only layers for the config script are displayed at the bootleaf framework. the console displays the error below -response on the web page displays "load was perfomed, but no display of the geojson data. at the console the error displayed is "Expected ‘none’, URL, or filter function but found ‘progid’. Error in parsing value for ‘filter’. Declaration dropped.", "Unknown property ‘-moz-osx-font-smoothing’. Declaration dropped","Error in parsing value for ‘-webkit-text-size-adjust’. Declaration dropped" among others. I will be grateful to know how to fix this issue! -
VueX actions not mapping. Message - [TypeError: Cannot read property 'dispatch' of undefined]
In my Vue code when attempting to run an VueX mapped Action I am receiving the below error message: [TypeError: Cannot read property 'dispatch' of undefined] Please refer the below screenshot for the error observed by me. Chrome Error Screenshot I am using Django, Webpack and Vue-Cli3. App.vue <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> | <router-link to="/product-list">Products</router-link> </div> </div> </template> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px; } #nav a { font-weight: bold; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } </style> main.js import Vue from 'vue'; import App from './App.vue'; import router from './router'; import store from './store'; import { mapState, mapGetters, mapMutations,mapActions } from 'vuex'; Vue.config.productionTip = false; new Vue({ router, store, methods: { ...mapMutations([ 'loadProducts', ]), ...mapActions([ 'retrieveProducts', 'saySomething', ]), testCall: () => { // Works here alert('You are in removeLink'); }, }, computed: { ...mapState([ 'products', 'products_images', ]), ...mapGetters([ ]), }, mounted() { alert('mounting now'); // Works here this.testCall(); // Works here this.retrieveProducts(); }, render: h => h(App), }).$mount('#app'); index.js ..\store import Vuex from 'vuex'; import axios from 'axios'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; export default … -
what parameter in username = request.data.get('username', '0')
A django rest framework tutorial,has a expression like this: username = request.data.get('username', '0') My question is what dose the parameter '0' mean in this expression? -
Django-Apache Web Server correct setup?
I am currently setting up a VPS web server using Ubuntu 16.04. I have installed all packages, Python3, PIP and Django etc I have set up my root directory such as root -venv -thesantaletter(project) -letter(app) My conf file is set up as following, however when I access this I receive a 403 forbidden error, I am unsure whether the issue lays on the way I have my folder architecture for the project as I have never needed to deploy a django application live before. <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html <Directory ~/santa/thesantaletter/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess santa python-path=~/santa/ python-home=~/santa/venv WSGIProcessGroup santa WSGIScriptAlias / ~/santa/thesantaletter/wsgi.py </VirtualHost> When I run the development server on port 8000, it runs fine, and with no issues - which leads me to believe that the issue is on the apache side (which isn't my strongest suit). I have searched and attempted numerous different conf and folder structures but to no avail, and this is my last resort. The file permissions of the folder can be seen -
Django firebase authentication without Django authentication framework
I have created a app authenticating user directly from google firebase, without any user model in the project. I'm using firebase authentication and python Admin sdk. The app is in github. So the idea is to make a custom login and logout views. Also a middleware to process the authentication for each requests. Also the user data can be binded as a python object to improve the usability. At the moment, the middleware logic is there in the home view. With the current logic, every request has to verify the cookies and which is a network request. As per the firebase documents, verification can be done without network requests. Verify session cookies using the Admin SDK verifySessionCookie API. This is a low overhead operation. The public certificates are initially queried and cached until they expire. Session cookie verification can be done with the cached public certificates without any additional network requests. But I couldn't figure out where the cached public certificates and how to use it? I'm using firebase web ui authentication and sending the token to the server and verifying it in the server as per the documents. Is it safe to use the the firebase app config on … -
How to correctly display data stored in an external model without refreshing the page?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. My page currently loads, but when I check the network using F12, there is never a call to the function/url that searches for the name to display it on the page. I'm not sure where I might be missing the part that connects these two areas of the code, but I … -
Django: Get Model of DetailView in init()
Hello I'm trying to access the Detail Views model in it's own init() method. I've got the following code so far: views.py class AccountDetailView(DetailView): model = Account template_name = 'account_detail.html' def __init__(self, **kwargs): super(AccountDetailView, self).__init__(**kwargs) timeline = kwargs.get('timeline') history = History.objects.filter(timeline=timeline).first() payHistory = history.topay_set.filter(payed=True, internal_source=self.object).order_by('-payDate') paginator = Paginator(payHistory, 10) The Problem is the "self.object" in the payHistory. How can I access the Account from the DetailView?