Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: RegisterUserView not saving to DB (or returning HttpResponse)
So I have a simple user registration form using: RegisterUserForm ModelForm and User Model Needs to: it is suppose to create an instance of the modelform and validate the form and save the user data to db. - return HttpResponse('User Registered') Issue: Register form displays, upon clicking submit button, doesn't do anything! Stays there (it should show a HttpResponse('User Registered') View.py from django.shortcuts import render from django.views.generic import CreateView from website.forms import RegisterUserForm # Create your views here. class RegisterUserView(CreateView): form_class = RegisterUserForm template_name = "account/register.html" # Overide dispatch func - check if the user is authenticated or return forbidden def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): retVurn HttpResponseForbidden() return super(RegisterUserView, self).dispatch(request, *args, **kwargs) # Overide form valid method behaviour def form_valid(self, form): # False commit - don't save to db, locally cleaning users password first user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save(); # Change to redirect - later one! return HttpResponse('User Registered') forms.py from django import forms from django.contrib.auth.models import User class RegisterUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) class Meta: # Connect to the user model and select which fields we want input for user model model = User fields = ['username', 'email'] # Validate password matched / and clean … -
django redis - i didn't call execute at pipeline but connect pipeline
REDIS 4.0.8 django 2.0.2 mac os 10.13 class redis_input(): r=[] def __init__(self): r= redis.Redis(connection_pool=REDIS_CONNECTION_POOL) def redis_multi_set(self,list): MyList = list (set to 1,2,3,4,5,6,7,8,9,10) p = self.r.pipeline() p.watch('count') p.multi() for value in MyList: result = redis_set(value,p) if result == False : return False p.execute() return True def redis_set(self,value,pipeline): if value >= 5: return False p = pipeline p.hset('setcount:'+value,'@@@@','####') p.incr('count') return True i call redis_input().redis_multi_set([1,2,3,4,5,6,7,8,9,10]) got returned False but already setcount:1 ~ 4 in REDIS i'm not call pipeline.execute why this data in REDIS?? -
Why is my url not changing to my render template name?
I'm new in django and I just follow a tutorials. I noticed that my url is not correct after login. Can someone help me and explain how to properly do it? login.html: <form class="form-horizontal" role="form" action="{% url 'ksvt:login_user'%}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="control-label col-sm-2" for="id_username"> Username: </label> <div class="col-sm-10"> <input id="id_username" maxlength="30" name="username" type="text"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="id_password"> Password: </label> <div class="col-sm-10"> <input id="id_password" maxlength="30" name="password" type="password"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> urls.py from django.conf.urls import url from . import views app_name = 'ksvt' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^register/$', views.register, name='register'), url(r'^login_user/$', views.LoginView.as_view(), name='login_user'), url(r'^logout_user/$', views.LogoutView.as_view(), name='logout_user'), ] views.py class LoginView(TemplateView): template_name = 'ksvt/index.html' def post(self, request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) locations = Location.objects.all() return render(request, self.template_name, {'locations': locations}) else: return render(request, self.template_name, {'error_message': 'Your account has been disabled'}) else: return render(request, 'ksvt/login.html', {'error_message': 'Invalid login'}) Output url: http://127.0.0.1:8000/login_user/ It must be: http://127.0.0.1:8000/ Please teach mo the proper way to do this. Thank you! -
How does the modify operator work in Django?
First of all, here is an example for a typical modify operation in Django: # import class and constants from ldap3 import Server, Connection, ALL, MODIFY_REPLACE # define the server s = Server('servername', get_info=ALL) # define an unsecure LDAP server, requesting info on DSE and schema # define the connection c = Connection(s, user='user_dn', password='user_password') c.bind() # perform the Modify operation c.modify('cn=user1,ou=users,o=company', {'givenName': [(MODIFY_REPLACE, ['givenname-1-replaced'])], 'sn': [(MODIFY_REPLACE, ['sn-replaced'])]}) print(c.result) # close the connection c.unbind() I pasted this in a "modify.py"-file and ran "python modify.py runserver". The connection and operater worked perfectly. But my question is: Is it possible to make this a general function for all users? My webapp is GUI-based and I do not want to run "python modify.py runserver" for every single user. If yes, how do I bind it to my programm? For my setting.py I used the python-auth-ldap library. If you have any idea or questions to me, do not hesitate to post it. Thanks in advance. -
How to give multiple parameters to django's url in various patterns
I use Django 1.11. I'm thinking about url design like this I want to use the part surrounded by {} as a parameter. v1/ v1/{param1} v1/{param1}/category/{param2} v1/category/{param2} I tried to make the url pattern as below url(r'^v1/?$', some_view.SomeClass.as_view()), url(r'^v1/(?P<param1>.*)/?', some_view.SomeClass.as_view()), url(r'^v1/(?P<param1>.*)/category/(?P<param2>.*)/?', some_view.SomeClass.as_view()), url(r'^v1/category/(?P<param2>.*)/?', some_view.SomeClass.as_view()), After accessing v1/param1/category/param2. Then param1/category/param2 will come in the argument {param1} How do I get it done? -
The current path, login, didn't match any of these
Using the URLconf defined in project10.urls, Django tried these URL patterns, in this order: ^admin/ ^regandloginapp The current path, login, didn't match any of these. Using the URLconf defined in project10.urls, Django tried these URL patterns, in this order: ^admin/ ^regandloginapp The current path, login, didn't match any of these. Using the URLconf defined in project10.urls, Django tried these URL patterns, in this order: ^admin/ ^regandloginapp The current path, login, didn't match any of these. myproj10\urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^regandloginapp',include('regandloginapp.urls')), ] regandloginapp\urls.py from django.conf.urls import url from . import views app_name = 'regandloginapp' urlpatterns = [ url(r'^$',views.home,name='home'), url(r'^reg$', views.reg,name='reg'), url(r'^login$',views.login,name='login') ] models.py from __future__ import unicode_literals from django.db import models class Reg(models.Model): user = models.CharField(primary_key=True,max_length=20) pwd = models.CharField(max_length=20) fname=models.CharField(max_length=10) lname=models.CharField(max_length=10) dob=models.DateField() mobno=models.IntegerField() views.py from django.shortcuts import render from django.http import HttpResponse from .models import Reg from .forms import LoginForm from .forms import RegForm def reg(request): if request.method == 'POST': form = RegForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponse('reg success') else: print(form.errors) return HttpResponse("error") else: form = RegForm() return render(request,'reg.html', {'form': form}) def login(request): if request.method == "POST": MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): un =MyLoginForm.cleaned_data['user'] pw=MyLoginForm.cleaned_data['pwd'] dbuser = Reg.objects.filter(user=un,pwd=pw) if not dbuser: … -
Connection aborted., error(104, 'Connection reset by peer') in Django
I have created an API in Django and inside that calling a third party API which accepts XML data. With 30 rows of XML it is working fine, for more rows throwing the error "Connection aborted.', error(104, 'Connection reset by peer')". The third party also provided a UI so I can test that up to 5000 rows they are accepting and returning proper result. The connection is not getting closed from either of the APIs. What issue can it be? Expected Result The post request should work properly for more data in the request as it is working fine for fewer data. Actual Result ConnectionError at /v1/send-sms/ ('Connection aborted.', error(104, 'Connection reset by peer')) Request Method: POST Request URL: http://example.com/v1/send-sms/ Django Version: 1.11 Exception Type: ConnectionError Exception Value: ('Connection aborted.', error(104, 'Connection reset by peer')) Exception Location: /home/user-135/sandbox/venv/local/lib/python2.7/site-packages/requests/adapters.py in send, line 490 Python Executable: /home/user-135/sandbox/venv/bin/python Python Version: 2.7.12 Python Path: ['/home/user-135/public_html/MyProject', '/home/user-135/sandbox/venv/lib/python2.7', '/home/user-135/sandbox/venv/lib/python2.7/plat-x86_64-linux-gnu', '/home/user-135/sandbox/venv/lib/python2.7/lib-tk', '/home/user-135/sandbox/venv/lib/python2.7/lib-old', '/home/user-135/sandbox/venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/user-135/sandbox/venv/local/lib/python2.7/site-packages', '/home/user-135/public_html/MyProject', '/home/user-135/public_html/MyProject'] Server time: Wed, 7 Mar 2018 10:55:19 +0530 Reproduction Steps import requests recievers = '' url = 'https://example.com/sms/' for x in xrange(0, len(users)): y = x + 1 body_content = body phone = mobile_no recievers = recievers + … -
How can I create 'not_analyzed' index on string field using django-haystack
I am trying to index a table with employee details and I need to index employee names as it is (including the spaces and special characters in the name). Is there a way to do that using django-haystack?. -
Python Django. How can I build correct DataTable with two querysets?
I want to create DataTable with sort and some features. I tried to do this task like 8 hours in a row, but still don't know how to do it and how to do it better. Seems i have 2 queries, buy i don't know how to concate or work with them. Im trying to loop throw each, but first for loop is looping my second one. I cant use zip(), i tried. Finally i wanna get the table i can sort with fields from two different tables. How can I rewrite SQL to Django to get id, fio and sum of total_price from different model? SELECT site_users_db.id, fio, sum(total_price) total_price FROM site_users_db, buh_order WHERE buh_order.customer_id = site_users_db.id GROUP BY site_users_db.id; I have views.py @group_required('buhgalter') def index(request): qs = request.GET or dict() flag = True if (u'' in set(qs.values()) and len(set(qs.values())) == 1) or (len(set(qs.values())) < 1): flag = False if flag: f = ClientFilter(qs, queryset=Client.objects.all()) o = OrderFilter(qs, queryset=OrderItem.objects.all()) else: o = OrderFilter(qs, queryset=OrderItem.objects.none()) f = ClientFilter(qs, queryset=Client.objects.none()) message = request.session.pop('message', None) query = request.GET.get('query', None) context = {'query': query, 'message': message, 'filter': f, 'ordfilt': o} return render(request, 'buhgalt/clients.html', context) Models: class OrderItem(models.Model): ... customer_id = models.ForeignKey('Client', models.PROTECT, db_column='customer_id', … -
Django: one variable has different values in template
Like the title says, I'm passing a variable to a django template called 'old_link' as such: {% if type_disp == 'charts' %}<li class="active">{% endif %}<a href="{% url 'matching:analytics' action=action type_disp='charts' %}?{{old_link}}" class="text-primary"><i class="fa fa-fw fa-bolt"></i>Charts</a></li> {% if type_disp == 'tables' %}<li class="active">{% endif %}<a href="{% url 'matching:analytics' action=action type_disp='tables' %}?{{old_link}}" class="text-primary"><i class="fa fa-fw fa-calendar"></i>Table</a></li> The 'old_link' variable is supposed to get added to the end of the url, but it keeps giving me the wrong link. To test it I also posted the variable in another part of the template to see what it returns. You can see the correct value above the 'number of companies' section in the picture below. The value where it's posted in the sheet and the value where it's posted in the url are completely different and I'm not sure why. In the picture below you can see the url portion where the variable is supposed to be applied, it shows 'http://127.0.0.1...' instead of the 'year_min...' value that it should. Here's the full template code: <div class="item col-md-8 col-xs-12"> <div class="panel panel-default"> <div class="panel-body"> <div class="row"> <div class="col-xs-6"> <h4 class="text-headline margin-none">{{company_amount}}</h4> <p class="text-light"> <i class="fa fa-circle-o text-success fa-fw"></i> Total Funding </p> </div> <div class="col-xs-6"> <h4 … -
How do I give permission for wsgi to operate in my directory?
Apache and wsgi now have permissions problems accessing the directory in which my Django project is stored. I think I need to get back to having wsgi run as user (or maybe just group) kevin. I had this working, and I don't know what I did to stop it working, but now I get an permissions error as soon as I get past logging into my app. Unfortunately, I don't have the apache config under version control. I'm pretty sure that's where the problem is because restoring a backup of the project from when it was working didn't change anything, but tweaking permissions on the database and the root directory of the project has altered the particulars of the error message. I wasn't going to give o+w to the whole works, nor did I feel like giving an ACL to every single file or directory. Background: apache 2 as delivered with Ubuntu 16.04 LTS. Django 1.11. Python 3.5. libsqlite3.0 3.11.0 I thought that what I had in the tail of /etc/apache2/apache2.conf took care of this, in particular the line WSGIProcessGroup kevin because all the files and directories are owned by kevin.kevin, and my evidence seems to indicate that when it … -
uWSGI will not run in mixed Python environment in order to operate correctly with nginx and run Django app
Environment: Ubuntu 16.04 (with system Python at 2.7.12) running in Vagrant/Virtualbox on Windows 10 host Python Setup: System python verified by doing python -V with no virtualenv's activated. Python 3.5 is also installed, and I've done pipenv --three to create the virtualenv for this project. Doing python -V within the activated virtualenv (pipenv shell to activate) shows Python 3.5.2. Additional Background: I'm developing a Wagtail 2 app. Wagtail 2 requires Django 2 which, of course, requires Python 3. I have other Django apps on this machine that were developed in Django 1.11/Python 2.7 and are served by Apache. We are moving to Django 2/Python 3 for development going forward and are moving to nginx/uWSGI for serving the apps. I have gone through many tutorials/many iterations. All Vagrant port mapping is set up fine with nginx serving media/static files and passing requests upstream to the Django app on a unix socket, but this is giving a 502 Gateway not found error because uWSGI will not run correctly. Therefore, right now I'm simply running the following from the command line to try to get uWSGI to run: uwsgi --ini /etc/uwsgi/sites/my_site.com.ini. This file contains: [uwsgi] uid = www-data gid = www-data plugin = … -
Join 2 tables with no ForeignKey link
I have a SQL query that joins 2 tables and I'm trying to replace it with Django ORM. The query: SELECT * FROM students r JOIN class_teachers c ON c.class_room_id = r.class_room_id Pretty simple. Purpose of it is to get all values from students and the Teachers ID from class_teachers table. I created 3 models that are using pre built tables in the db: class ClassRoom(models.Model): class_room = models.AutoField(primary_key=True) name = models.CharField(max_length=32) class ClassTeachers(models.Model): class_room = models.ForeignKey(ClassRoom) teacher = models.ForeignKey(Teachers) class Students(models.Model): class_room = models.ForeignKey(ClassRoom) name = models.CharField(max_length=32) But with this setup I can't figure out how to create a two table join like before. The closest I got was with this which is horrible... but works: dd = ClassTeachers.objects.filter( company_id=company_id, ).annotate( name=F('classroom__classteachers__name'), all_student_fields... ).values( 'teacher_id', 'name', all_student_fields... ) and it creates a 3 table join: SELECT st.*, ct.teacher_id FROM class_teachers ct INNER JOIN class_room cr ON (ct.class_room_id = cr.class_room_id) LEFT OUTER JOIN students st ON (cr.class_room_id = st.class_room_id) WHERE ct.class_room_id = '123'; Is there a way to create a 2 table join getting the teacher id and all student table fields without the need to join the ClassRoom table? -
Dynamic Datasets filters in Chart.js
I have a chart.js line chart displaying data for a year. The data is coming from Django view (apiview). I want the user to be able to select a range eg. 1 week, 1 month and so forth. So far I have the view as : class AcctReceivableData(APIView): def get(self, request, format = None): dt = [dates.dt for dates in FirstTest.objects.filter(variable = "Accounts receivable (days)", kpi_category = "Finance")] value = [values.value for values in FirstTest.objects.filter(variable = "Accounts receivable (days)", kpi_category = "Finance")] data = { "labels": dt, "default": value, } return Response(data) This is the html file: var endpoint = '/client/primarycare/acctreceivable/chart/data/' var defaultData = [] var target = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default target = data.target setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: ["January", "February", "March","April","May","June","July", "August","September","October","November","December"], datasets: [{ label: '# Actual', data: defaultData, backgroundColor: [ 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 159, 64, 1)' ], borderWidth: 5, fill: true }, { label: '# Target', data: target, backgroundColor: [ 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255, … -
Django admin form redirect to view
I have an admin form called UserCreationForm. There is no view that holds the form. The relative url of the form is admin/accounts/user/add/. I would like to permanently redirect any requests for this url to a view in another app (manage/add-user/). How can I do this? -
Is it possible to update a django context dictionary without reloading the page?
I'm trying to use AJAX to update a Django context dictionary so that it can display different assignments on a web page when a certain button is clicked. My view creates a different context dictionary based on either GET or POST methods used to request the page. The former is the default and the later occurs when the user clicks the button. Everything works, the AJAX sends the correct data and the view is able to find the correct corresponding assignments. My issue, however, is that the page content (the django template code) never changes updates with the response. What am I doing wrong? @login_required def assignments(request): terms = Course.objects.filter(students = request.user).values('term__season', 'term__year').distinct() courses = Course.objects.filter(students = request.user) assignments = Assignment.objects.filter(course__in=courses) if request.method == 'POST': # retrive ajax data data = request.POST course_subject = data['course_subject'] course_number = data['course_number'] course_section = data['course_section'] term_season = data['term_season'] term_year = data['term_year'] # get the associated course for the click course = Course.objects.filter(subject = course_subject, number = course_number, section = course_section, term__year = term_year, term__season = term_season) # get the assignments associated with that course assignments = Assignment.objects.filter(course = course) context_dict = { 'assignments': assignments, 'courses': courses, 'terms': terms, } return render(request, 'mainapp/assignments.html', context_dict) -
How to call aditional URL parameters from template in DJANGO
I'm passing a variable "referer" to my template that's a string of aditional url parameters using this code: {% if type_disp == 'charts' %}<li class="active">{% endif %}<a href="{% url 'matching:analytics' action=action type_disp='charts' %}{{referer}}" class="text-primary"><i class="fa fa-fw fa-bolt"></i>Charts</a></li> {% if type_disp == 'tables' %}<li class="active">{% endif %}<a href="{% url 'matching:analytics' action=action type_disp='tables' %}{{referer}}" class="text-primary"><i class="fa fa-fw fa-calendar"></i>Table</a></li> I've validated that "referer" is correct before passing, but it's not being referenced when I click on the buttons. How do I make it so the url contains the referer string as well? Thank you -
Dynamic variable value on HTML with Django
I'm looking to display a constantly-changing python variable (that's read from a websocket server) onto a HTML file, currently i'm using a Django tag as it follows: templatetags/mytag.py from django import template register = template.Library() current_value = 0 @register.filter def c_value(placeholder): return current_value #more code that modifies current_value reading from a websocket server index.html {% load mytag %} <script> function mytimer() { setInterval(function(){ $('#stuff').html( {{ placeholder|c_value }} ); } , 1000); } mytimer(); </script> #some code from the website <span id="stuff">Holder</span> However naturally '{{ placeholder|c_value }}' only outputs the first ever value of 'current_value', which is 0 in this case, and so the source code of index.html ends up being: source code after '{{ placeholder|c_value }}' <script> function mytimer() { setInterval(function(){ $('#stuff').html( 0 ); } , 1000); } mytimer(); </script> Which is not desired since we would like to print the changing-value of 'current_value' each second. What is the normal approach for these kind of dynamic texts? Many thanks! -
Python return in for loop not returning
@staticmethod def observation_for(region_name: str, date: datetime): snapshots = RegionSnapshot.objects.filter(ref_name=region_name).order_by('date').reverse() for r_snapshot in snapshots: if r_snapshot.date < date: triggered = True print('should return') if triggered: print('after triggered, still here for some reason') return r_snapshot raise RegionSnapshot.DoesNotExist('request epoch for {} does not exist in criteria'.format(str(date))) I'm using the above code, which should return when it get to the return r_snapshot line (at least, I believe). However, it doesn't seem to be returning. It throws the exception and prints the following which is consistent with it not returning. Is there anything that I'm doing incorrectly? should return after triggered, still here for some reason should return after triggered, still here for some reason -
Django 2.0 'post' is not a registered namespace
Im doing a udemy course but is it on django 1.11, and im trying to doit with 2.0. The exercise is do a social network clone with groups, users and posts, the exersize have 3 main apps, accounts, groups and posts. And this is the file path: - Django exercize - Django exercize - groups app - template - groups app - html files - urls.py - views.py - posts app - template - posts app - html files - urls.py - views.py - accounts app - template - accounts app - html files - urls.py - views.py At some point when i try to load 'Groups list' or 'Create new group' the server show this error: NoReverseMatch at /groups/ 'post' is not a registered namespace This is the views.py of create and list on group folder class CreateGroup(LoginRequiredMixin,generic.CreateView): fields = ('name','description') model = Group template_name = 'groups/groups_form.html' class ListGroups(generic.ListView): model = Group template_name = 'groups/groups_list.html' This is the urls.py on groups folder from django.urls import path from . import views app_name = 'groups' urlpatterns = [ path('',views.ListGroups.as_view(),name='all'), path('new/',views.CreateGroup.as_view(),name='create'), path('post/in/<slug:slug>',views.SingleGroup.as_view(),name='single'), path('join/<str:slug>/',views.JoinGroup.as_view(),name='join'), path('leave/<str:slug>/',views.LeaveGroup.as_view(),name='leave'), ] This is the urls.py on django main folder from django.contrib import admin from django.urls import path, include … -
model in django,how to change two value when I edit one in admin?
in models.py: class Projects(models.Model): # 项目名称 pro_name = models.CharField('项目名称',max_length=50) # 项目内容 # content = models.CharField('项目内容',max_length=200) content = models.TextField('项目内容', max_length=200) # 外键 person = models.ForeignKey(Person, on_delete=models.CASCADE) # 金额 sum_money = models.IntegerField('项目金额',default=0) # 付款 payed_money = models.IntegerField('已付金额',default=0) # 欠钱 owe_money = models.IntegerField('未付金额',default=0) # 是否欠钱 is_debt = models.BooleanField('是否欠账',default=True) # 发布日期 pub_date = models.DateTimeField('保存日期',default=timezone.now,) def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.pro_name class Meta: verbose_name = '项目' verbose_name_plural = '项目' admin screen capture: when I changed the 'payed_money(已付金额:)' the 'owe_money(未付金额:)' = sum_money - payed_money, and if sum_money == payed_money the is_debt = False what should I do? rewrite save() mehtod? -
If statement skipped in django view for authenticated user
Good evening, I have a view that works only if im logged as superuser, but not as "departmentsupervisor" def detail_employee(request, pk, employee_pk): department = get_object_or_404(Department, pk=pk) print(department.supervisor, request.user.username) if request.user.username == department.supervisor or request.user.is_superuser: employee = get_object_or_404(Employee, department__pk=pk, pk=employee_pk) review = get_object_or_404(Result, pk=pk) print(employee, review.id) return render(request, 'review_employee.html', {'employee': employee}) return redirect('dept_employees', pk=department.pk) Im validating with the print that user logged is == department.supervisor but the if statement is skipped, if im logged with superuser it works properly. Im trying to look what I did wrong here. Thanks -
Pycharm autocomplete doesn't work in conda env
I have python2/python3 env on my local machine. Python2 is installed in /usr/bin/python2.7, and python3 is installed with anaconda. I set up python3/Django2.0 project, set up isolated env for Django with anaconda. conda create --name Activated new env. source activate And installed dependencies with pip3 pip3 install -r requirements.txt Python, Django version: python --version: Python 3.6.4 :: Anaconda, Inc. django-admin.py version: 2.0.2 And, set python interpreter properly, as shown in the image. But, pycharm autocomplete is not working for me. Pycharm autocomplete doesn't work with pip installed packages in anaconda environment? Is this something you faced before? -
Django model QuerySet not returning when filtered
I'm not really sure what's happening here. I can see that I have a couple of emails in my database, but I can't seem to filter them. for example, when I run qs1 = EmailActivation.objects.all() >>> print(qs1) <EmailActivationQuerySet [<EmailActivation: a@yahoo.com>, <EmailActivation: b@gmail.com>]> however, when I run the following I get nothing qs2 = EmailActivation.objects.all().filter(email='a@yahoo.com') >>> print(qs2) <EmailActivationQuerySet []> my model looks like this: class EmailActivation(models.Model): user = models.ForeignKey(User) email = models.EmailField() I'd expect my qs2 to return 'a@yahoo.com' since it is in the database as seen by qs1. Does someone see what I'm doing wrong? Thanks, -
Django/python model form type error
I am getting a "quote_from_bytes() expected bytes" error when I am following the Django documentation for using Model form. It appears to write to the sqlite DB but every time I fill out the form it gives this error. forms.py from django.forms import ModelForm from .models import * class inputforms(ModelForm): class Meta: model = Inputform fields = ['auditid', 'audittask', 'responsibleperson', 'auditstatus', 'auditnotes', 'auditdate'] views.py def inputview(request): form = inputforms(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse, 'auditpage') args = {'form': form} # row = [str(s).encode() for s in {'form': form}] return render(request, 'auditentry.html', args) models.py class Inputform(models.Model): auditid = models.IntegerField(blank=True, null=True) audittask = models.TextField(blank=True, null=True) responsibleperson = models.TextField(blank=True, null=True) auditstatus = models.TextField(blank=True, null=True) auditnotes = models.TextField(blank=True, null=True) auditdate = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'inputform'