Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to put valid input in a ModelChoiceField widget that inherits TextInput widget
This form is updated by a generic view: models.py: class CustomUser(User): user_bio = models.TextField(blank=True, null=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.username class SafeTransaction(models.Model): trans_recipient = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'trans_Recipient',null = True) trans_recipient_email = models.CharField(max_length = 1000, blank=True, null=True) trans_sender = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'safe_Transactions', null = True) date = models.DateTimeField(auto_now_add=True, blank=True) subject = models.CharField(max_length = 1000, blank = True) #trans_type = models.CharField(choices=(1,'Buildingwork'))#DROPDOWN BOX trans_unread = models.BooleanField(default = True) arbitrator_name = models.CharField(max_length=1000,blank=True, null=True) payment_condition = models.TextField(blank=True, null=True) amount_to_pay = models.DecimalField(blank=True, null=True, max_digits=50, decimal_places=2) is_finalised = models.BooleanField(default=False) views.py: class SafeTransUpdateView(UpdateView): ''' This view lets the user Update a SafeTransaction receipt ''' form_class = SafeTransactionForm model = SafeTransaction template_name = "myInbox/safeTrans_update.html" forms.py : class SafeTransactionForm(forms.ModelForm): ''' SafeTranSactionForm ''' #version one of trans recipient trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput()) #version two of trans_recipient #trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'})) def clean_trans_recipient(self): data = self.cleaned_data['trans_recipient'] try: return CustomUser.objects.get(username=data) except CustomUser.DoesNotExist: raise forms.ValidationError("No user with this username exists") class Meta: model = SafeTransaction fields = [ 'trans_recipient', 'trans_recipient_email', 'subject', 'arbitrator_name', 'payment_condition', 'amount_to_pay'] So in the forms, I'm mainly trying to inherit a TextInput widget from a ChoiceField. Upon actually submiting the form with this version : trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput()) I am told that … -
Not Found url in django class based view with ajax
I have a problem with "like" functionality. I want to make it possible to like the post, without overloading the whole page. So I used CBV django connected to ajax. My problem is that it receives: Not Found: /like/ by pressing the "Like" button. My view: class PostLikeView(generic.View): def post(self, request): post = get_object_or_404(Post, id=request.POST.get('id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), } if request.is_ajax(): html = render_to_string('post/like_section.html', context, request=request) return JsonResponse({'form': html}) Below is jquery code: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault; var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: "{% url 'post:post_like' %}", data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('#like-section').html(response['form']) console.log($('#like-section').html(response['form'])) }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> url to view: url(r'^like/$', login_required(PostLikeView.as_view()), name='post_like'), code in html: <form action="{% url 'post:post_like' %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button> {% endif %} </form> I would like the button to work on the principle of not reloading the whole page. -
Django: how to store a lot of data between requests if I don't have a database
I am writing an app that will visualize Strava (social site for athletes) user's activities in various ways. The user is required to authenticate with his Strava account, and then my app downloads his activity data from Strava API. As there will be no user accounts in my app - just the Strava authentication - I have decided to not use a database. Therefore, I would need to store the activity data in memory. The data would be quite big: for example, I have 800 activities on Strava, each being a longish JSON. Would storing the data in session like session['activities'] = some_downloaded_activities be suitable for this? I would then set up API endpoints that would query this session data, filter it as required by the front end of my application and return it. My other idea is to use a database only to store the JSON file, but delete the data immediately after the user session is done - but it seems like an overkill. Or is there a better approach? -
if condition on large querysets are very slow
I am using Python 2.7 and Django 1.9.2 I am trying to do a condition where if queryset is not empty, there will be a functionality. I realized something as my queryset has gone large up to 56,000 records. A simple condition with that queryset takes almost 5 seconds but if I added .exists() with the queryset it is just so fast. Please check snippet bellow from record.models import Record records = Records.objects.filter(result=0) if records: # this takes almost up to 5 seconds with 56,000 records # do stuff here With .exists(): from record.models import Record records = Records.objects.filter(result=0) if records.exists(): # very fast abd just takes milliseconds # do stuff here Any explanation why the first one is so slow? I'm beginning to think that the first one loops the value of the records variable when doing an if -
Invalid template library specified. ImportError raised when trying to load 'src.myapp.templatetags.custom_tags' cannot import 'custom_tags'
I have deployed my django project over windows 2012 IIS. After the setup sometimes its failing to load the template tag libraries. With the template tag loading error i am also receiving an error like below in my chrome firebug console. Mixed Content: The page at 'https://10.***.***.**/site/new_site/list/?id=4' was loaded over a secure connection, but contains a form that targets an insecure endpoint 'http://dpaste.com/'. This endpoint should be made available over a secure connection. I searched my entire code i cannot see any mix uup code between http and https. Also i tried to put SECURE_SSL_REDIRECT = True in my settings.py file, but as i am not using a any secure connection its failed to load the site. I tried this but its does not resolve my issue. I am not that much aware of this IIS+django settings. Should i do any separate settings in order to load the template tag libraries. But i am not getting this error message often. Any help would be greatly appreciated. Thanks. I am also attaching the error messages i am getting . -
Gitlab CI Runner, staging and production, DigitalOcean and Docker Compose
What i’m trying to achieve is that I wrote a ci/cd config file and added two digital ocean’s server using GitLab runners to my repository. Now I want that whenever I push to my repo it automatically push to the staging url and then manually push my code to the production url. Now the issue is my staging url working correctly but my code is not getting pushed to the production url. https://codebeautify.org/yaml-validator/cbecc958 Above link is copy of my gitlab-ci.yml Point my errors and correct me, where i'm wrong -
How to fix "Not Found: /oauth2callback" error in python
I'm using Python and Django for accessing Gmail using Gmail API after authentication completed it is showing the following error Not Found: /oauth2callback I'm using python 3.6, Django 2.0.7, google-api-python-client 1.7, oauth2client==4.1.2, from django.shortcuts import render import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from oauth2client import client from django.http import HttpResponseRedirect SCOPES = 'https://mail.google.com/' redirect_uri='http://127.0.0.1:8000/oauth2callback' def accesmail(request): creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: FLOW = client.flow_from_clientsecrets('credentials.json', SCOPES,redirect_uri) authorize_url = FLOW.step1_get_authorize_url() #with open('token.pickle', 'wb') as token: # pickle.dump(creds, token) return HttpResponseRedirect(authorize_url) I expect after authentication completed redirecting to my own HTML page, and access Gmail inbox messages, and I expecting to store credentials in database -
Django 2.1.4 - filter - Why my filter not catch specified year?
I defined Article model at models.py. And I defined created by models.DateTimeField in Article class. I want to get articles by specified year value but I can not catch it by one of my case. But case of other approach is fine. Why ? models.py class Article(models.Model): created = models.DateTimeField(auto_now_add=True) python manage.py shell >>> Article.objects.filter(created__year=2014).all() <QuerySet []> >>> for el in Article.objects.all(): ... if el.created.year == 2014: ... print('2014') ... 2014 >>> -
nameerror model post not defined
problem i created a model for my project after making it when i register it in admin.py file it throughs a name error.says 'post' not defined error NameError: name 'Post' is not defined class Post(models.Model): user=models.ForeignKey(User,related_name='posts', on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now=True) message=models.TextField() message_html=models.TextField(editable=False) group=models.ForeignKey(Group,related_name='posts', null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html=misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs= {'username':self.user.username,'pk':self.pk}) class meta: ordering=['-created_at'] unique_together=['user','message'] -
Cannot import name environment
Traceback: File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/template/utils.py" in getitem 66. return self._engines[alias] During handling of the above exception ('jinja2'), another exception occurred: File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sitharthan/Documents/sasana/books/views.py" in login 99. return render(request, 'books/login.html', {'form': form}) File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/template/loader.py" in render_to_string 61. template = get_template(template_name, using=using) File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/template/loader.py" in get_template 12. engines = _engine_list(using) File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/template/loader.py" in _engine_list 66. return engines.all() if using is None else [engines[using]] File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/template/utils.py" in all 90. return [self[alias] for alias in self] File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/template/utils.py" in 90. return [self[alias] for alias in self] File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/template/utils.py" in getitem 80. engine_cls = import_string(backend) File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/utils/module_loading.py" in import_string 17. module = import_module(module_path) File "/home/sitharthan/Documents/lucy/lyca/lib64/python3.6/importlib/init.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "" in _gcd_import 994. File "" in _find_and_load 971. File "" in _find_and_load_unlocked 955. File "" in _load_unlocked 665. File "" in exec_module 678. File "" in _call_with_frames_removed 219. File "/home/sitharthan/Documents/lucy/lyca/lib/python3.6/site-packages/django/template/backends/jinja2.py" in 1. import jinja2 File "/home/sitharthan/Documents/sasana/jinja2.py" in 17. from jinja2 import Environment Exception Type: ImportError at /login Exception Value: cannot import name 'Environment' -
integrating django with aiohttp/asyncio
i want to integate django with aiohttp/asyncio for asynchronous programming and for websockets handling, i know django has celery & django-channels to do asynchronous task and websocket server respectively but aiohttp is having both asynchronous and websocket server pre built in it and i found that framework more scalable and easy when compared to celery/django channels while creating a function to webscrapping(i don't know if webscrapping can be possible in celery i havent tried it yet ) and it also supports async and await perfectly but my question is how can we implement both django and aiohttp in a project instead using django's development server can we use aiohttp server to serve the site and can we able to integrate django with aiohttp function (like lets take an example if i want to scrap a website of user submmited input to my database can i use this await calls in my function while fetching the website and posting the following website to my django database or post the function results to another django function) and i want to know the disadvantages of integrating ,if any ?? and while posting your answer please could you post a sample practical example of … -
Django rest framework and getting serializer values using source keyword
I have two models, one is just the base User model and the other is Profile model that is used to extend the User model and keep more details. Here's what the UserSerializer looks like: from django.contrib.auth.models import User from profiles.models import Profile from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): reputation = serializers.IntegerField( read_only=True, source='profile.reputation' ) class Meta: exclude = ('password',) model = User def create(self, validated_data): password = validated_data.get('password') user = User.objects.create(**validated_data) user.set_password(password) user.save() Profile.objects.create(user=user) return user As you can see, this overrides the create method so it can make a profile record with each create. There is also a reputation field being added to the serializer so when I get the User it comes with its reputation from the profile. That reputation field is defined on the Profile model. This got me thinking, is it possible to override create in such a way that allows me to send data to one endpoint and create profiles in one go? For instance, right now if I want to create users and I just send a POST request to my endpoint with: { "username": "sethen", "password": "password" } And I get back the correct profile. If I were to add a bio … -
Django: Problem in integrating get_form_kwargs in inline formset
I want to make a queryset in my forms.py for an object being specific to user and company. I have done this for normal forms but failed to do in the form which comes in the formset. I have used the get_form_kwargs function to accomplish in normal django forms but cannot integrate get_form_kwargs in my inline formset. I have done this in my views.py class Payment_createview(LoginRequiredMixin,CreateView): form_class = PaymentForm success_message = "%(account)s is submitted successfully" template_name = 'Payments/payment_form.html' def get_success_url(self,**kwargs): company_details = get_object_or_404(company, pk=self.kwargs['pk']) selectdatefield_details = get_object_or_404(selectdatefield, pk=self.kwargs['pk3']) return reverse('accounting_double_entry:paymentcreate', kwargs={'pk':company_details.pk, 'pk3':selectdatefield_details.pk}) def get_context_data(self, **kwargs): context = super(Payment_createview, self).get_context_data(**kwargs) company_details = get_object_or_404(company, pk=self.kwargs['pk']) context['company_details'] = company_details selectdatefield_details = get_object_or_404(selectdatefield, pk=self.kwargs['pk3']) context['selectdatefield_details'] = selectdatefield_details if self.request.POST: context['payments'] = Payment_formSet(self.request.POST) else: context['payments'] = Payment_formSet() return context def form_valid(self, form): form.instance.User = self.request.user c = company.objects.get(pk=self.kwargs['pk']) form.instance.Company = c context = self.get_context_data() payments = context['payments'] with transaction.atomic(): self.object = form.save() if payments.is_valid(): payments.instance = self.object payments.save() return super(Payment_createview, self).form_valid(form) def get_form_kwargs(self): data = super(Payment_createview, self).get_form_kwargs() data.update( User=self.request.user, Company=company.objects.get(pk=self.kwargs['pk']) ) return data And in my forms.py: class PaymentForm(forms.ModelForm): class Meta: model = Payment fields = ('date','account','total_amt') widgets = { 'date': DateInput(), } def __init__(self, *args, **kwargs): self.User = kwargs.pop('User', None) self.Company = kwargs.pop('Company', None) … -
Django static files not loading even with STATICFILES_DIR set to correct path
I've looked at so many similar questions on Stack overflow and other websites but I cant seem to figure out why my static files aren't loading. I have created my base template based on a tutorial online, and it should work like magic. But my static files arent rendering with the view. When I go to the developer console on chrome I see that the css and js files are not found. the exact error is: > 127.0.0.1/:8 GET http://127.0.0.1:8000/static/css/bootstrap.min.css net::ERR_ABORTED 404 (Not Found) > 127.0.0.1/:117 GET http://127.0.0.1:8000/static/js/jquery-3.3.1.min.js net::ERR_ABORTED 404 (Not Found) > 127.0.0.1/:118 GET http://127.0.0.1:8000/static/js/popper.min.js net::ERR_ABORTED 404 (Not Found) > 127.0.0.1/:119 GET http://127.0.0.1:8000/static/js/bootstrap.min.js net::ERR_ABORTED 404 (Not Found) Here is my base template: {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}Django Forms{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> {% block stylesheets %} {% endblock stylesheets %} </head> <body> {% block body %} <nav class="navbar navbar-expand-sm navbar-dark bg-dark" > <div class="container" > <a class="navbar-brand" href="{% url 'home' %}">Blog App</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mainMenu" aria-controls="mainMenu" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon" ></span> </button> <div class="collapse navbar-collapse" id="mainMenu" > <ul class="navbar-nav ml-auto" > <li class="nav-item dropdown" > <a class="nav-link dropdown-toggle" href="#" … -
Datetime field in Django 2
I'm working on a project in which I need to use a few DateTime fields, I have defined DatetimeField in my model and then in the template, I'm using the https://tempusdominus.github.io/bootstrap-4/ plugin but when I submit the form there's two issues comes on: 1): Django says Enter a valid date/time for all DateTime Fields 2): Select a valid choice. ['corn_oil'] is not one of the available choices. Here's what I have tried: From models.py: choices = ( ('CO2 SCRUBBER', 'CO2 SCRUBBER'), ('corn_oil', 'CORN OIL'), ('DRYERS', 'DRYERS'), ('ENVIRONMENTAL', 'ENVIRONMENTAL'), ('UTILITIES', 'UTILITIES'), ('LAB', 'LAB'), ('SIEVES', 'SIEVES'), ('GRAINS & MILLING', 'GRAINS & MILLING'), ('SEPARATION', 'SEPARATION'), ('AIR & GAS', 'AIR & GAS'), ('COOK', 'COOK'), ('EVAPORATION', 'EVAPORATION'), ('WATER', 'WATER'), ('STORAGE', 'STORAGE'), ('BOILER', 'BOILER'), ('FERMENTATION', 'FERMENTATION'), ('DISTILLATION', 'DISTILLATION'), ('BUILDING AND FACILITIES', 'BUILDING AND FACILITIES'), ('CHEMICAL', 'CHEMICAL'), ) class ExperimentModel(models.Model): user = models.ForeignKey(User, related_name='experiments', on_delete=models.CASCADE) name = models.CharField(max_length=255) start_date = models.DateTimeField() change_date = models.DateTimeField() end_date = models.DateTimeField() assets = models.CharField(max_length=450, choices=choices) goals = models.CharField(max_length=255, blank=True) comments = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now=True) From forms.py: class ExperimentForm(forms.ModelForm): choices = ( ('CO2 SCRUBBER', 'CO2 SCRUBBER'), ('corn_oil', 'CORN OIL'), ('DRYERS', 'DRYERS'), ('ENVIRONMENTAL', 'ENVIRONMENTAL'), ('UTILITIES', 'UTILITIES'), ('LAB', 'LAB'), ('SIEVES', 'SIEVES'), ('GRAINS & MILLING', 'GRAINS & MILLING'), ('SEPARATION', 'SEPARATION'), ('AIR & GAS', 'AIR … -
Django installation issue
I've just begun learning Django. I ran the following command to install Django: 1. download and unpack Django-2.1.5.tar.gz in /u01 2. cd /u01/Python-3.7.2/bin 3. ./python3 -m venv ./python3 -m venv /u01/django 4. source /u01/django/bin/activate 5. cd /u01/django/bin 6. ./pip3 install -e /u01/Django-2.1.5 Obtaining file:///u01/Django-2.1.5 Collecting pytz (from Django==2.1.5) Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe464ed25c0>, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytz/ ... Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe464ed2278>, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytz/ Could not find a version that satisfies the requirement pytz (from Django==2.1.5) (from versions: ) No matching distribution found for pytz (from Django==2.1.5) Anyone would point out what I did incorrectly? -
Payment method by paypal and Google pay on django
I want to create a website for a NGO who wants donation by paypal, netbanking, google pay etc -
Django Jquery TypeError: $(...).draggable is not a function
I have a Django application with Jquery being used on the frontend, however some Jquery functions are not working. The code works as expected outside of a Django application when the HTML/CSS is run separately. I have included the Jquery and javascript like this: <script language="JavaScript" type="text/javascript" src="{% static 'blog/static/jquery-3.2.1.min.js'%}"></script> <script language="JavaScript" type="text/javascript" src="{% static 'blog/static/mememaker.js'%}"></script> <script language="JavaScript" type="text/javascript" src="{% static 'blog/static/main.js'%}"></script> Here is my javascript file $(document).ready(function () { console.log("mememaker working!"); //setting default font var fontSize = "24px"; var sizeNumber = 24; var fontFamily = "Arial"; var fontColour = "Black" //Choose meme picture $('#fry').click(function () { console.log("add fry") $('#meme-bg-target img').attr('src', "{% static 'blog/static/Fry.png'%}"); $('#meme-bg-target img').width(550); // Units are assumed to be pixels $('#meme-bg-target img').height(420); }); $('#spongebob').click(function () { console.log("spongebob") $('#meme-bg-target img').attr('src', "{% static 'blog/static/Spongebob.png'%}"); $('#meme-bg-target img').width(550); // Units are assumed to be pixels $('#meme-bg-target img').height(420); }); $('#leow').click(function () { $('#meme-bg-target img').attr('src', "{% static 'blog/static/LeoW.png'%}"); $('#meme-bg-target img').width(550); // Units are assumed to be pixels $('#meme-bg-target img').height(420); }); //Upload function //Textbox area //Preview function $('.btn-prvw').click(function () { $('#meme-canvas-container').css({ 'display': 'block' }); }); //Close the preview $('.btn-close').click(function () { $("#meme-canvas-container").css({ 'display': 'none' }); }); //Canvas function copyToCanvas(htmlElement, font) { var canvas = document.getElementById("meme-preview"); var ctx = canvas.getContext("2d"); // ctx.font = font; // … -
User Login not working with default django's Authentication
I am new to Django and I am trying to make user Login to my App using the Django's user Authentication The signup is working Fine, so there is no problem with my model or signup view(Using class based views). i tried to import LoginView and LogoutView from Django.contrib.auth.views and post method has been set in my logout template. Cant figure out what i am missing here. The user wont simply Login, but signup works good. This is accounts/urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"),name = "login"), path('logout/', auth_views.LogoutView.as_view(),name = "logout"), path('signup/', views.SignUp.as_view(), name = "signup") ] This is urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomePage.as_view(), name = "Home"), path('accounts/', include('accounts.urls', namespace = "accounts")), path('accounts/', include('django.contrib.auth.urls')), path('test/', views.TestPage.as_view(), name = "Test"), path('thanks/', views.ThanksPage.as_view(), name = "Thanks"), ] This is login template inside accounts app (accounts/templates/accounts/login.html) {% extends "base.html" %} {% load bootstrap3 %} {% block mainContent %} <div class = "container"> <h1> Hello! Lets Login </h1> <form method = "POST"> {% csrf_token %} {% bootstrap_form form %} <input type = "submit" … -
mysql connection error (base file-> get_new_connection() )
Using 'ENGINE': 'django.db.backends.mysql' gives .../django/db/backends/mysql/base.py", line 276, in get_new_connection conn.encoders[SafeBytes] = conn.encoders[bytes] KeyError: <type 'str'> -using ubuntu, python, django -all python, mysql and pip installs -mysql server running and credentials work. I've refreshed django and mysqlclient installs, and downgraded django versions When I removed DATABASES is works, when I use sqlite3 it works, when I use DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '***' } } When I runserver or migrate I get Error: Unhandled exception in thread started by <function wrapper at 0x7fd14e618cf8> Traceback (most recent call last): File "/home/tree/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/tree/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 127, in inner_run self.check_migrations() File "/home/tree/.local/lib/python2.7/site-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/tree/.local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/tree/.local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/tree/.local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 210, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/tree/.local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/tree/.local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/tree/.local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/home/tree/.local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/home/tree/.local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/tree/.local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/home/tree/.local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 276, in … -
Django extend AbstractBaseUser Admin Login Page Error
Today I tried to change the UserModel, So I did everything that was supposed to be needed : create the class class User(AbstractBaseUser, PermissionsMixin): With something like that inside : phone = PhoneNumberField(unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(_('active'), default=True) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] def is_staff(self): return self.is_admin The UserManager : class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone, password, **extra_fields): """ Creates and saves a User with the given phone and password. """ if not phone: raise ValueError('The given phone must be set') user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, phone, password=None, **extra_fields): extra_fields.setdefault('is_admin', False) return self._create_user(phone, password, **extra_fields) def create_superuser(self, phone, password, **extra_fields): extra_fields.setdefault('is_admin', True) if extra_fields.get('is_admin') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(phone, password, **extra_fields) The CustomUserAdmin class : class CustomUserAdmin(UserAdmin): # The forms to add and change user instances # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference the removed 'username' field fieldsets = ( (None, {'fields': ('phone', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, … -
Do django is needed for every virtual environment?
Is it necessary to install separate django for each project? if yes then why? and if no then when i check for django version when virtualenv is not activated their is no error as below E:\web\python\django_1>python -m django --version 2.1.4 And when i activate virtual env i get error as below (django_1-Gx7XQ45n) E:\web\python\django_1>python -m django --version C:\Users\usr_name\.virtualenvs\django_1-Gx7XQ45n\Scripts\python.exe: No module named django Why this is happening? -
My project uses the Google+ API to login,which is deprecated now, need tips/advice to update
I have a project currently deployed, in production, which uses the google+ API and the python social core (Django) (social_core) to login almost all users, now the google+ apis are deprecated and I need to update the authentication system. Any tip, documentation or tutorial I can follow to make it? I followed this tutorial to make the initial login but now that won't work in the near future. This is a school project so I'm pretty much the only developer working with this, any help provided will be much appreciated :D -
get_queryset vs manager in Django
As far as I know, we bring the database by model managers right? e.g. queryset = Model.objects.all() But sometimes, I see some code that seems almost same thing but is a bit different, post = self.get_queryset() which also fetches database but not by manager. What's the difference between fetching database by manager and get_queryset() and their usage? -
ModuleNotFoundError in Django Crontab Command
I have a number of django custom commands which work. However, when I have tried to automate them using crontab, my error log records the following error: ModuleNotFoundError: No module named 'sanct' I have added the virtualenv path to crontab command path. I have a test command which just creates a log file every minute and this seems to execute properly. I'd like the crontab commands to execute. My crontab commands are as follows: job = cron.new(command='/home/arch/myprojectdir/myprojectenv/bin/python /home/arch/myprojectdir/sanct/management/commands/cong_dl.py >>/tmp/out.txt 2>&1')