Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0 use ORM in Python script in parent directory of django folder
I have the following structure for my project: . βββ py_file_i_want_to_use_core_models_in.py βββ web_app βββ core β βββ __init__.py β βββ __pycache__ β βββ admin.py β βββ apps.py β βββ core_settings.py β βββ forms.py β βββ migrations β βββ models.py β βββ static β βββ templates β βββ tests.py β βββ urls.py β βββ views.py βββ web_app β βββ __init__.py β βββ __pycache__ β βββ settings.py β βββ urls.py β βββ wsgi.py βββ manage.py I want to access some models define in web_app/core/models.py from inside the python script py_file_i_want_to_use_core_models_in.py but I cant seem to get the code I am finding to work: Here is what I am trying: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web_app.web_app.settings") import django django.setup() But these imports give me the following error: ModuleNotFoundError: No module named 'core' Any ideas on how I can solve this issue? -
django2 - A like button per post. Ajax to submit the like button form but I have many forms with the same ID
In my template I'm looping through posts and for each post, a like button is placed for each post and this is working. I want the user to be able to like the post but I'm stuck and not really sure what to search for that might help solve this problem. I have a single ajax function, I want to be able to capture the submitted form so I can capture post ID values from that form. What seems to be happening is the first post works when I press the like button but the second post causes a page refresh and fails to fire the function. Thanks. <script type="text/javascript"> $(document).ready(function() { $("#like_toggle").submit(function(event){ event.preventDefault(); var id = $(this).attr('value'); $.ajax({ type: "POST", url: "/like" , data: { 'id': id, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function(){ $('#like-section').html("sent") } }); return false; }); }); </script> HTML <form method="POST" id="like_toggle"> {% csrf_token %} <div id="like-section"> <button id="like" value="{{ post.id }}" type="submit" class="btn btn-primary my-2 my-sm-0 btn-sm float-right">+Like<span class="badge badge-light ml-2">{{ post.likes }}</span></button> </div> </form> -
Nginx returning back (404 - Not found). Is this because of Gunicorn or Nginx?
So I am at a total loss with this. I am not sure where to start debugging this problem.I am not getting any nginx based logs. Following are the scripts that I am using for nginx and gunicorn This is the code that I introduced in the http section of nginx.conf upstream test_server { server unix:/home/ubuntu/venvfoo/fooWeb/run/gunicorn.sock fail_timeout=10s; } # This is not neccessary - it's just commonly used # it just redirects example.com -> www.example.com # so it isn't treated as two separate websites server { listen 80; server_name foo.com; return 301 $scheme://www.foo.com$request_uri; } server { listen 80; server_name www.foo.com; client_max_body_size 4G; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log warn; location /static/ { autoindex on; alias /home/ubuntu/venvfoo/fooWeb/static/; } location /media/ { autoindex on; alias /home/ubuntu/venvfoo/fooWeb/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://test_server; break; } } #For favicon location /favicon.ico { alias /var/www/test/test/static/img/favicon.ico; } #For robots.txt location /robots.txt { alias /var/www/test/test/static/robots.txt ; } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /var/www/test/ourcase/static/; } and this is the gunicorn script that I am running manually every time. I am not running this as a service currently (I'll do β¦ -
how to use model jsonfield in django 1.1
I was working on Django project using django version 2.0 but somehow I switched back to 1.1 because of my client requirements. I had used jsonfield in my django models in django version 2.0 but when I use this same field in django 1.1 it doesn't work. Instead it throw error like ImportError: No module named postgres.fields I tried to use https://github.com/dmkoch/django-jsonfield this project as well but it has updated my django to 2.0 again. Is there any way I can use jsonfield in django 1.1 -
django template to call js object
how to do this in django. <body onload="main_(1);"> </body>. I tried it with this. { load static } <body> {% if true %} <script src="{% static 'main/js/main_index.js' %}" ></script> <script> main_(1); </script> {% endif %} </body> No luck so far. is there an easier way. -
Django looping formsets cause ValidationError in management form
I am trying to output two same forms and save them to database with different prefix. I used this post https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ as an example. However I get validation error that management form is being tampered with. Could you please kindly advise how to solve it? Thank you. Also is it possible to filter database by the prefix in this case if i want to retrieve the data later for analysis. VIEWS.PY from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions model_names = ['Form1', 'Form2'] def get_assumptions(request): AssumptionsFormset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) if request.method == 'POST': formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names] if all([formset.is_valid() for formset in formsets]): for formset in formsets: for form in formset: form.save() else: formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names] return render(request, 'assumptions.html', {'formsets': formsets}) ASSUMPTIONS.HTML <div class="form"> <form action="" method="post"> {% csrf_token %} {% for formset in formsets %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <h1>{{formset.prefix}}</h1> <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %}"> {% for field in form.visible_fields β¦ -
installation of pipenv causes pip3 unusable
I installed pipenv using $ pip3 install pipenv which gives me the error ImportError: cannot import name 'main' in order to solve this error I followed these instruction sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall now pip3 command is working on terminal. now I install pipenv using pip3 install pipenv it installed succesfully but when i tried to execute pipenv on termnal it gave me pipenv: command not found at this point pip3 also gives ImportError: cannot import name 'main' error in order to solve this i followed these instruction PYTHON_BIN_PATH="$(python3 -m site --user-base)/bin" PATH="$PATH:$PYTHON_BIN_PATH" at this, point pipenv is working but pip3 is not working . How can I make both pip3 and pipenv work at the same time? -
Modify database in django
I am a beginner in django. Following is my Attendance Management App. This is my models.py. from django.db import models class Subject(models.Model): subject_name = models.CharField(max_length=20) #attendance = models.ForeignKey(Attendance, on_delete = models.DO_NOTHING) attendance = models.IntegerField(default=0) def __str__(self): return self.subject_name class Section(models.Model): section_name = models.CharField(max_length=20) subject = models.ManyToManyField(Subject) def __str__(self): return self.section_name class Student(models.Model): rollno = models.IntegerField() name = models.CharField(max_length=20) section = models.ForeignKey(Section, on_delete = models.DO_NOTHING, default=0) def __str__(self): return str(self.rollno) + self.name class Teacher(models.Model): #teacher_name = models.CharField(max_length=20) section = models.ForeignKey(Section, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) #section_name = models.CharField(max_length=10) #subject_name = models.CharField(max_length=30) def __str__(self): return self.section.section_name+' '+self.subject.subject_name class TeacherList(models.Model): teacher_name = models.CharField(max_length=20) teacher = models.ManyToManyField(Teacher) def __str__(self): return self.teacher_name The line below is not working in views.py student = models.Student.objects.get(rollno = sroll) student.section.subject.get(subject_name = 'java').attendance += 1 student.save() This view is called from a template when a button is clicked to add attendance of a student. The attendance in above code is not modified. Please help me out. -
can't receive ajax data in django views
I am trying to implement ajax in my django form but when i try to access that data in django views i get an error saying IntegrityError at /community/ NOT NULL constraint failed: user_poll.user_poll_title I am following This Tutorial views.py elif 'new_poll' in request.POST: user_poll_title = request.POST.get('title') user_poll_description = "poll_description" #yes this is a string for testing user_poll_records = "poll_record" #yes this is a string for testing poll_save_form = UserPollForm(request.POST) if poll_save_form.is_valid(): user_poll = poll_save_form.save(commit=False) user_poll.user_poll_title = user_poll_title user_poll.user_poll_description = user_poll_description user_poll.user_poll_user_id = request.user.id poll_save_form.save() for record in user_poll_records: add_record_form = UserPollRecordForm(request.POST) user_poll_record = add_record_form.save(commit=False) user_poll_record.user_poll_record_title = record user_poll_record.user_poll_record_poll = user_poll user_poll_record.user_poll_record_count = 0 add_record_form.save() return redirect('com_index') main.js // Submit post on submit $('#poll_creation').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check create_post(); }); // AJAX for posting function create_post() { console.log("create post is working!") $.ajax({ url:'/', type: "POST", data: {title: 'poll_title'}, // data sent with the post request // handle a successful response success : function(json) { $('#post-text').val(''); // remove the value from the input console.log(json); // log the returned json to the console console.log("success"); // another sanity check }, // handle a non-successful response error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ β¦ -
Saving users mysql queries
We are writing a custom data analysis and visualisation tool that will allow users to pick a certain data range, set of data streams and perform aggregation functions on top of the filtered data. For each new query, we would like to give an option to the user for saving the query for later analysis. That means, we need to store several parts of the query, such as, columns, date ranges, aggregation functions (count, avg.) etc. Is there a Django/python library for this? -
How to server HTTP/2 Protocol with django
I am planing to deploy my django project with HTTP/2 protocol but I unable to find the proper way how can I server my django based website with HTTP/2, the only thing that I find is hyper-h2. I read the documentation but unable to setup the connections. If anybody know how to server django on HTTP/2. -
LeaveApplyForm' object has no attribute 'save'
I want to save a leave in database applied from employee but when i was submit i faced this error ----LeaveApplyForm' object has no attribute 'save'--- **models.py** class All_Leaves(models.Model): leave_types = models.ForeignKey(Leave_Types, on_delete=models.CASCADE, related_name="all_leave") user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name="all_leave") reason = models.CharField(('Reason'), max_length=120) start_date = models.DateTimeField(('Start Date'),auto_now = True) end_date = models.DateTimeField(('End Date'),auto_now = True) class Meta: verbose_name = ("All Leave") verbose_name_plural = ("All Leaves") **View.py** def apply_leave(request): print("user",request.user) print("data",request.POST) leave_type_data = Leave_Types.objects.all() if request.method =="POST": form = LeaveApplyForm(request.POST, None) print("form status",form.is_valid()) if form.is_valid(): form.save(leave_types=request.POST['leave_types'], user=request.user) print("form in") return render(request, 'dashboard.html',{"var_leave":"false","leave_type_data":leave_type_data}) else: print("form errors",form.errors) return render(request, 'dashboard.html',{"var_leave":"false","leave_type_data":leave_type_data,"form":form}) forms.py class LeaveApplyForm(forms.Form): start_date = forms.DateTimeField(required=True, error_messages={'required': 'Please Choose Start Date.'}) end_date = forms.DateTimeField(required=True, error_messages={'required': 'Please Select End Date.'}) reason = forms.CharField(required=True, error_messages={'required': 'Please Enter Your Reason.'}) class Meta: model = All_Leaves fields = ('start_date','end_date','reason') -
Can't Connect Django To Custom WYSIWIG Editor
I have created a custom WYSIWIG editor for Django. My form works on all of the other fields, but I can't quite figure out how to connect the field in question to the form. I am getting field is required, but I can't seem to figure out how to associate the field with the WYSIWIG editor. Here is my code: HTML <!DOCTYPE html> {% extends "base1.html" %} <title>{% block title %} Create Information {% endblock %}</title> {% block body_block %} <form method="POST" enctype="multipart/form-data" autocomplete=off> {% csrf_token %} <style> div#textEditor{ margin: 0 auto; width: 750px; height: 300px; } div#theRibbon{ border-bottom: none; padding: 10px; background-color: rgb(40,110,89); color: white; border-radius: 8px 8px 0px 0px; } div#richTextArea{ border: 2px solid rgb(40,110,89); height: 100%; width: 746px; background-color: white; } iframe#theWYSIWYG{ height: 100%; width: 100%; } div#theRibbon > button { color: white; border: none; outline: none; background-color: transparent; cursor: pointer; } div#theRibbon > button:hover{ background-color: rgb(20,90,70); transition: all 0.3s linear 0s; } input[type="color"]{ border: none; outline: none; background-color: transparent; } </style> <script> window.addEventListener("load",function(){ var editor = theWYSIWYG.document; editor.designMode = "on"; boldButton.addEventListener("click", function(){ editor.execCommand("Bold", false, null); },false); italicButton.addEventListener("click", function(){ editor.execCommand("Italic", false, null); },false); supButton.addEventListener("click", function(){ editor.execCommand("Superscript", false, null); },false); subButton.addEventListener("click", function(){ editor.execCommand("Subscript", false, null); },false); strikeButton.addEventListener("click", function(){ β¦ -
TemplateDoesNotExist, registration/login.html Django
Am using Django Authentication Model. The problem is when i visit /accounts/login, i get TemplateDoesNotExist: registration/login.html error message. Now the problem is i already specified a template for the LoginView. Here is my accounts/urls.py file 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('join/', views.SignupView.as_view(), name='join'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), ] The login template is located at accounts/templates/accounts/login.html And here is the TEMPLATES TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
How to include a template inside a template in django?
I have a home page "home.html" which extends a base template "base.html". I am rendering home.html. And in my home.html I have included another template "nav.html" with {% include "qa/nav.html" %}. but it isn't including the navigation bar items which are inside nav.html How do I include this template? -
Installing Django+MySql on mac
I have been trying to install Django and mysql on my mac for days and it is driving me crazy :) I have successfully installed Django on 2 of my other mac machines but I canβt manage to do that on MacBook Pro with latest os. I have installed Python 3.6 in Anaconda virtual environment. Then I installed mysql using brew install mysql@5.7, I have installed Django using pip install django==2 and even pip install mysqlclient When i try to run python manage.py i am getting: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I have tried to install mysql@5.6 with brew but i have uninstalled it. Can somebody please help -
Django Template - How to pass formset as an include variable
I am using a lot of formsets, so it is only natural not to copy paste a lot of template codes. To factor the commonality out, I made a add_formset.html file that renders the formset. This template works fine on its own. But, when I send a formset to it, it does not render the formset: Generic add_formset.html: <div class="container"> <div class="row pt-3"> <form method="post" action="" class="col-sm-12 col-md-9 col-lg-9">{% csrf_token %} {{formset.management_form }} {% for form in formset %} <div class="container"> <div class="col-sm-12 col-md-12 col-lg-12"> {% include 'card.html' with card_form=form %} </div> </div> {% endfor %} </form> </div> <div class="row"> <div class="col-6 p-2 ml-5" style="border: 0px solid cyan !important;"> <button type="submit" class="btn btn-primary ">Submit</button> </div> </div> </div> Using the generic formset template, I am passing the specific formset to it: {% extends 'base.html' %} {% load extra_template_tags %} {% block body %} {% include 'add_formset.html' with formset=unit_price_formset %} {% endblock %} I have also trie to replace formset=unit_price_formset with formset={{unit_price_formset}}, but it does not work. Any idea to solve this? -
How to call Python script from another directory
Django project folder structure project (source root) -->apps ---->**app1** ----->admin.py ----->init.py ----->apps.py ----->models.py ----->urls.py ----->views.py ----->callscript2.py ----->**myscipt-folder** ------>script1.py ------>script2.py ------>__init__.py ---->**app2** ----->admin.py ----->init.py ----->apps.py ----->models.py ----->urls.py ----->views.py ----->sample.py(must be able to call the script2 from app1, myscript folder) ---->**app3** When I call the file from sample.py from apps.app1.myscipt-folder import script1 I get the following error from apps.app1.myscipt-folder import script1 ModuleNotFoundError: No module named 'apps.app1'; 'apps' is not a package But when I test it inside the callscript2.py it works fine. What do you think I do wrong here? -
Django and jquery: Dynamically adding multiple formsets in one page - how to differentiate?
Im trying to have two formsets in one page and have the functionality of adding/removing form fields for both of the formsets with jquery. When I add a form to the first formset - it adds a form field to the second formset. Can anyone help me on how to differentiate the two formsets? (the second formset is working fine) Thanks a lot! <script type="text/javascript"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex,replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input').each(function () { var name = $(this).attr('name') if(name) { name = name.replace('-' + (total - 1) + '-', '-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); } }); total++; $('#id_' + prefix + '-TOTAL_FORMS').val(total); $(selector).after(newElement); var conditionRow = $('.form-row:not(:last)'); conditionRow.find('.btn.add-form-row') .removeClass('btn-success').addClass('btn-danger') .removeClass('add-form-row').addClass('remove-form-row') .html('-'); return false; } function deleteForm(prefix, btn) { var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); if (total > 1){ btn.closest('.form-row').remove(); var forms = $('.form-row'); $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length); for β¦ -
Error: No module named messages Django 1.1.3
I was working on django project on version 2.0 but my client was unhappy about it, he wants that project must be made on django 1.1.3 so I switched back to old version and tried to setup the project on that version but unable to do so. But after that I created a new project on django 1.1.3 and created django app too. Tried to run command python manage.py syncdb but I got this error message: Error: No module named messages What 's the issue. I am not finding django 1.1.3 documentation though. -
Unknown field(s) (password1, password2) specified for CustomUser
Internal Server Error: /admin/account/customuser/add/ Traceback (most recent call last): File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\options.py", line 642, in get_form return modelform_factory(self.model, **defaults) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\forms\models.py", line 543, in modelform_factory return type(form)(class_name, (form,), form_class_attrs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\forms\models.py", line 252, in new raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (password2, password1) specified for CustomUser During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\options.py", line 544, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\views\decorators\cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\sites.py", line 211, in inner return view(request, *args, **kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 63, in bound_func return func.get(self, type(self))(*args2, **kwargs2) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 63, in bound_func return func.get(self, type(self))(*args2, **kwargs2) File "C:\Users\Andriken\AppData\Local\Programs\Python\Python35\Lib\contextlib.py", line β¦ -
Django Graphene, Passing a json or dict as Input for Mutation
Hi everyone I have the following situation: I have a User, each user have a Inventory. IΒ΄struggling to declare the userΒ΄s inventory in the Mutation "CreateUser". Here is the following mutation for creating the user: mutation Create{ addUser(UserData:{name:"Shibunika",age:21} } IΒ΄m trying to declare the userΒ΄s inventory in this mutation, I expected something like mutation Create{ addUser(UserData:{name:"Shibunika",age:21,inventory:{'item1':45,'item2':25} } this number are the quantity of each item. How do I define this inputs in graphene? Would you gently showme a schema for this? -
cannot install django 2.0.6 using pipenv
following the author's step, saw this command $ pipenv install django==2.0.6 in a book Django for beginners it seems to have been working for the author but when I try to execute it on the terminal it gives me following error. sysadmin@R902R6HD:~/Desktop/helloworld$ pipenv install django=2.0.6 /usr/local/lib/python2.7/dist-packages/pipenv/vendor/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown. warnings.warn(warning, RequestsDependencyWarning) Installing django=2.0.6... β WARNING: Invalid requirement, parse error at "u'=2.0.6'" ABORTING INSTALL... You will have to reinstall any packages that failed to install. You may have to manually run pipenv lock when you are finished. /usr/local/lib/python2.7/dist-packages/pipenv/_compat.py:113: ResourceWarning: Implicitly cleaning up <TemporaryDirectory '/tmp/pipenv-67QFfh-requirements'> warnings.warn(warn_message, ResourceWarning) sysadmin@R902R6HD:~/Desktop/helloworld$ pipenv install django==2.0.6 /usr/local/lib/python2.7/dist-packages/pipenv/vendor/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown. warnings.warn(warning, RequestsDependencyWarning) Installing django==2.0.6... Collecting django==2.0.6 Error: An error occurred while installing django==2.0.6! Could not find a version that satisfies the requirement django==2.0.6 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, β¦ -
Custom Django Usermodel
i just tryd to create my own custom Django usermodel but it fails at a specific point :( the error i get is: django.core.exceptions.FieldError: Unknown field(s) (username) specified for User First i created a new Django App "accounts" then i've added the following to models.py of the accounts app: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) #User Model Manager class UserManager(BaseUserManager): def create_user(self, username, password=None): """ Creates and saves a User with the given username and password. """ if not username: raise ValueError('Error: The User you want to create must have an username, try again') user = self.model( username=self.normalize_username(username), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, username, password): """ Creates and saves a staff user with the given username and password. """ user = self.create_user( username, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, username, password): """ Creates and saves a superuser with the given username and password. """ user = self.create_user( username, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): user = models.CharField( verbose_name='username', max_length=30, unique=True, ) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the β¦ -
Postgres not responding with high waiting time
I am using Django with Postgres. My site servers half a million pages without any issue and everything works fine. However I am using an API system and it works like below: First party calls my site with API, my site gets data from third website using API. My site extracts some data and pass it to First party. It works perfectly. In this cycle I have to check my Postgres whether data is already present or not. Everything works fine. But if third party API does not respond or there is any server issue with third party it takes long time to respond with 404 error, my postgres just dies and I have to run service postgresql restart command everytime to site work. What could be the issue? How do I check why Postgres is dying?