Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django mysql setup error on mac os [duplicate]
This question already has an answer here: Python3.4 can't install mysql-python 4 answers ]mitwas-MacBook-Air:mytestsite Mitwa$ pip3 install MYSQL-python Collecting MYSQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/9l/9zjr811503367lfnybnyqlqc0000gn/T/pip-build-fk08ytxi/MYSQL-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/9l/9zjr811503367lfnybnyqlqc0000gn/T/pip-build-fk08ytxi/MYSQL-python/setup_posix.py", line 2, in from ConfigParser import SafeConfigParser ImportError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/9l/9zjr811503367lfnybnyqlqc0000gn/T/pip-build-fk08ytxi/MYSQL-python/ I am getting this error while setting up Django MYSQL for python. Anyone have idea how to solve it? -
Removing a single item from Django cart
trying to create a shopping cart application and currently stuck trying to remove a single item from a cart. I can't seem to work out how to remove a single product as currently it removes all of a product ID using the remove function. This is cart.py file: from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __len__(self): """ Count all items in the cart. """ return sum(item['quantity'] for item in self.cart.values()) def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: … -
Django templates: make child loop inside of a nested loop to do certain number of iterations
I have two lists: list1 = ['a','b','c','d'] list2 = [1,2,3,4,5,6,7,8,9,10,11,12] I want to render them into the template as follows: a 1 2 3 b 4 5 6 c 7 8 9 d 10 11 12 So the first column with the letters (list1) is row indexes. Each row consists of 3 cells populated from list2. Template structure is the following: <div class="row"> <div class="row-index">row index from list1</div> <div class="cell">cell1 from list2</div> <div class="cell">cell2 from list2</div> <div class="cell">cell3 from list2</div> </div> Obviously it is not enough to do a simple nested nested loop here (for list1 and list2): {% for row_index in list1 %} <div class="row"> <div class="row-index">{{ row_index }}</div> {% for cell in list2 %} <div class="cell">{{ cell }}</div> {% endfor %} </div> {% endfor %} This will render 4 rows (which is right!) but each row will have 12 cells instead of 3 per row. Unfortunately, zip_longest(list1, list2) won't help since it adds extra 'None' elements to list1 to make it of equal length with list2. Result is 4 actual row indexes, followed by 8 empty ones. And the cells rendered are all the same for each individual row, e.g. "a 1 1 1", "b 2 2 2", … -
Update for Serializers with many=True only create is supported in django api
I am using many in my serializer for creating new fields . I need to implement update in order to add the new fields coming and leave the existing ones as it is. Mycode is given below. models.py class Device(models.Model): device_id = models.CharField(max_length=200) auth_token = models.CharField(max_length=100) class ThirdPartyApps(models.Model): auth_token = models.ForeignKey(Device, on_delete=models.CASCADE) app_name = models.CharField(max_length=100) serializers.py class AppSerializer(serializers.ModelSerializer): class Meta: model = Apps fields = ('app_name', 'auth_token_id') def create(self, validated_data): if "auth_token_id" in self.context: id1 = self.context["auth_token_id"] instance = self.Meta.model(**validated_data) user_id = id1 if user_id is not None: instance.auth_token_id = user_id instance.save() return instance views.py @api_view(['POST']) def add_apps(request): data = request.data auth_token = request.META.get('HTTP_AUTHTOKEN', '') auth_tok = Device.objects.get(auth_token=auth_token) a_id = auth_tok.id serializer = AppSerializer(ThirdPartyApps, data=data, context={"auth_token_id": a_id}, many=True) if serializer.is_valid(): serializer.save() content = collections.OrderedDict( [('status', True), ('message', "Third party apps are saved")]) return Response(content, status=status.HTTP_200_OK) else: return Response(serializer.errors) I tried to use the update support of django by giving the model name while passing it to serializer to call the update method. But it says that when many=True , update is not supported only create method is supported . It is suggesting to use a ListSerializer class and override `.update() in my serializers. I am unable to understand how to … -
Default/logical directory structure for Django
I have gone through a number of tutorials, built a few apps, and even read the book by one of the creators of Django. But I am mystified by the 'proper' directory structure. One always seems to get a tree that looks like this (with a virtual environment at the top): venvdir | +---manage.py | +---mysitedir | +--settings.py | +--urls.p | +--staticfiles (where collectstatic puts everything) | +---myapp1dir | +--views.py | +--models.py | +--staticdir | +---static-objects-tree... What I find confusing is that os.path.abspath(__file__) points to 'mysitedir' (the references say it always points to the dir with settings.py in it). Presumably the idea is that a whole 'site' has one or more 'apps' under it, though I have never seen that done as such. First, is that correct? Second, is there some compelling reason (or am I doing it wrong) such that the 'apps' don't slot in below 'mysitedir'? That would seem to make more sense and maintain modularity. It seems odd the way Django does things like going through the whole tree looking for static files. It also seems illogical that you list the 'apps' in settings.py, and - once again - Django needs to go traversing up and back … -
I am attempting to add a field to my model that allows for multiple photos to be uploaded at once but they do not show up in the admin or my form
I am trying to add functionality to be able to upload multiple "products" at once to a model. Each needs to have a picture, price, and description and will have a many to one relationship to a "Partner". I know that formsets are the way to go but I can't seem to get the implementation correct. When I migrate, I can see that the Products class is created but it doesn't show up in the admin. Here is my views.py file def partner_create(request): ProductFormSet = modelformset_factory(Products, form=ProductsForm, extra=3) if request.method == 'POST': partnerForm = PartnerForm(request.POST) formset = ProductFormSet(request.POST, request.FILES, queryset=Products.objects.none()) if partnerForm.is_valid() and formset.is_valid(): partnerForm = partnerForm.save(commit=False) partnerForm.user = request.user partnerForm.save() for form in formset.cleaned_data: image = form['image'] photo = Images(partner=partnerForm, image=image) photo.save() messages.success(request, "Successfully Created") return HttpResponseRedirect("/") else: print partnerForm.errors, partnerForm.errors else: partnerForm = PartnerForm() formset = ProductFormSet(queryset=Products.objects.none()) return render(request, 'partner_form.html', {'partnerForm': partnerForm, 'formset': formset}, context_instance=RequestContext(request)) Here is my models.py file: class Partner(models.Model): name = models.CharField(max_length=120) logo = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") banner_image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") mission = models.TextField() vision = models.TextField() height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) # text = models.TextField() website_link = models.CharField(max_length=120) fb_link = models.CharField(max_length=120) twitter_link = models.CharField(max_length=120) ig_link = models.CharField(max_length=120) slug … -
Django Python str() argument 2 must be str, not int
I have a 12x12 dictionary with values, which are 0 for all. matchfield = {} for i in range(12): for j in range(12): matchfield[str((i, j))] = 0 I want to set some values to 1 with the following snippet (it checks whether the surrounding fields are free): length = 4 m = randint(1, 10-length) n = randint(1, 10) for x in range(m-1, m+length+1): for y in range(n-1, n+1): if not matchfield[str((x, y))]: for k in range(length): matchfield[str((m+k, n))] = 1 if I test this in python console, all works and the 4 selected values are set to 1, but in my Django view function I got an TypeError on the following line: matchfield[str((m+k, n))] = 1 Environment: Request Method: GET Request URL: https://www.maik-kusmat.de/schiffeversenken/start/ Django Version: 1.11.5 Python Version: 3.5.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'accounts', 'home', 'contact', 'kopfrechnen', 'braces', 'ckeditor', 'ckeditor_uploader', 'battleship', 'hangman'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'] Traceback: File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/pi/Dev/mkenergy/src/battleship/views.py" in battleship_start … -
django delete object with html button
I have a simple site project in Django and I have movies lists in man page and movies details in the second page. I want to add a delete button on movies details tab where user can delete the movies object. views.py def movies_list(request): return render(request, 'dataset.html',{'movies':movies.objects.all()}) def movies_details(request,slug): movies_details=MyModel.objects.all() det=get_object_or_404(movies_details, slug_name=slug) return render(request, 'dataset_details.html',{'movies_details':movies_details,'det':det}) what is the better method to do that ? something like this using new view : def delete(request, id): note = get_object_or_404(Note, pk=id).delete() return HttpResponseRedirect(reverse('movies_details.views.movies_details')) urls.py url(r'^delete/(?P<id>\d+)/$','project.app.views.delete'), or some like this ? if request.POST.get('delete'): obj.delete() or use some Django form ? -
Django Form Returning Invalid
I'm trying to implement a form that has checkbox options for a field, and a user can select multiple checkboxes for that specific field in the form and all the check-marked values should be sent in the POST request. But views.py is saying that the form is invalid when I try to submit the form. The reason it is invalid is this Select a valid choice. [&#39;top&#39;, &#39;mid&#39;] is not one of the available choices. I get a similar error when I only select one checkbox. Here is my partial models.py from django.db import models LEAGUE_ROLES = ( ('top','Top'), ('mid','Mid'), ('jungle','Jungle'), ('bottom','Bottom/ADC'), ('support','Support'), ) class CreatePosting(models.Model) createPostingOpenRoles = models.CharField(max_length = 10, choices=LEAGUE_ROLES, default=None) def __str__(self): # __unicode__ on Python 2 return self.title Here is my partial forms.py class TeamPostingCreateForm(ModelForm): class Meta: model = CreatePosting widgets = { 'createPostingOpenRoles': forms.CheckboxSelectMultiple(), } fields = '__all__' def __init__(self, *args, **kwargs): super(TeamPostingCreateForm, self).__init__(*args, **kwargs) Here is my partial views.py def createposting(request): UserTeamPostingCreateForm = TeamPostingCreateForm() if request.method == "POST": UserTeamPostingCreateForm = TeamPostingCreateForm(request.POST) if UserTeamPostingCreateForm.is_valid(): logger.error("valid form") else: #print form error logger.error(UserTeamPostingCreateForm.errors) variables = { 'form': UserTeamPostingCreateForm } return render(request, 'createposting.html', variables) And in my template, I have this for the form field {{ form.createPostingOpenRoles }} … -
Cant save form data in data base -Django
I am trying to create a simple form which takes name and email as user input. But after I submit,its not getting saved in database manage.py dumpdata shows [] i.e empty row. Please help! models.py class EmpD(models.Model): name = models.CharField(max_length=100) email=models.CharField(max_length=100) forms.py class SubmitF(forms.ModelForm): name = forms.CharField() email= forms.CharField() class Meta: model = EmpD fileds = '_all_' views.py def get(self, request): form= SubmitF() return render(request, 'emp/home.html', {'form': form}) def post(request): if request.method == 'POST': form = SubmitF(request.POST) if form.is_valid(): obj = EmpD() obj.name = form.cleaned_data['name'] obj.email = form.cleaned_data['email'] obj.save() return render(request, self.template_name,{'form':form}) def index(request): return render(request, 'emp/home.html') html containing form: <form action='' method="post" > {% csrf_token %} {{ form }} <table border="0" cellpadding="5" cellspacing="0"> <tr> <td style="width: 50%"> <label for="Name"><b>First name *</b></label><br /> <input name="Name" type="text" maxlength="50" style="width: 260px" /> </td> <td style="width: 50%"> </td> </tr> <tr> <td colspan="2"> <label for="Email_Address"><b>Email *</b></label><br /> <input name="Email_Address" type="text" maxlength="100" style="width: 535px" /> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="Submit Data" /> </td> </tr> </table> </form> -
What types of requests make good candidate for `@transaction.non_atomic_requests`?
A common way to handle transactions on the web is to wrap each request in a transaction. In Django, you can set ATOMIC_REQUESTS to True in the configuration of each database for which you want to enable this behavior. It works like this. Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django rolls back the transaction. While the simplicity of this transaction model is appealing, it also makes it inefficient when traffic increases. Opening a transaction for every view has some overhead. For requests that do not need to be wrapped in transactions, you can apply the @transaction.non_atomic_requests decorator. Given a Django view.py with several View classes and request methods. How might I go about deciding which requests would make good candidates for the non-atomic decorator? What "gotchas" might be lurking? I could see POST methods not making good candidates or anything with a .save(), but what else should I look out for? -
how to access data from extended user model django
Been through as many of the examples on here and I cannot find a solution. I have extended the Django user model, I have login and saving working fine. However I cannot retrieve the additional user information that I want to display on a profile page. See code below: views.py - Registration form. class UserFormView(View): form_class = UserForm template_name = 'crw/reg_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] user.set_password(password) user.save() user_profile = freelanceUser(user=user, contactNum=form.cleaned_data['contactNum'], jobTitle=form.cleaned_data['jobTitle'], homeLoc=form.cleaned_data['homeLoc'], startRate=form.cleaned_data['startRate']) user_profile.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('crw:profile') return render(request, self.template_name, {'form': form}) User Profile View: class UserDetail(generic.ListView): context_object_name = 'object_list' template_name = 'crw/profile.html' def get_queryset(self): return self.request.user @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) Models.py class freelanceUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contactNum = models.CharField(max_length=100) jobTitle = models.CharField(max_length=100) homeLoc = models.CharField(max_length=100) startRate = models.CharField(max_length=100) profile.html {% extends "crw/base.html" %} {% block body %} <section class="detail-section"> <div class="row"> <div class="small-8 small-centered colum"> <h1>Welcome: {{ object_list.first_name }} {{ object_list.last_name }}</h1> <p>We have the following information stored … -
I can not connect laravel as django is already in my pc
I installed django on my pc.but i want to instal laravel also.but my localhost didn't connect.Whenever i want to connect laravel in localhost it gives error like "Laravel development server started: [Thu Oct 5 01:41:01 2017] Failed to listen on 127.0.0.1:8000 (reason: An attempt was made to access a socket in a way forbidden by its access permissions." .Please give me solution .thanks -
Import Error on Flask Blueprint
I am attempting to build a simple CRUD webapp in Python using Flask and Flask-Blueprint(following this tutorial: https://scotch.io/tutorials/build-a-crud-web-app-with-python-and-flask-part-one) (I am using python 3.6.1 and attempting to translate the post from python 2.7) When I try to run the app right now I get the following error: File "/anaconda/lib/python3.6/site-packages/flask/cli.py", line 90, in locate_app import(module) File "/Users/gordonread/Dropbox/Programs/InventoryServer/run.py", line 6, in app = create_app(config_name) File "/Users/gordonread/Dropbox/Programs/InventoryServer/app/init.py", line 38, in create_app from .auth import auth as auth_blueprint ImportError: cannot import name 'auth' Here is the code causing the problem: def create_app(config_name): #other code from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint, url_prefix='/admin') from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .home import home as home_blueprint app.register_blueprint(home_blueprint) return app Here is the code I am trying to import: from flask import Blueprint admin = Blueprint('auth', __name__) from . import views And finally here is the relevant file structure: └───inventory ├── app │ ├── __init__.py │ ├── admin │ │ ├── __init__.py │ │ ├── forms.py │ │ └── views.py │ ├── auth │ │ ├── __init__.py │ │ ├── forms.py │ │ └── views.py │ ├── home │ │ ├── __init__.py │ │ └── views.py │ ├── models.py │ ├── static │ └── templates ├── config.py … -
pass field value to a function .extra()
After trying for hours, I am coming here. I have the following model: class Items(models.Model): date=models.DateField() giver=models.IntegerField() Class Givers(models.Model): name=models.CharField(max_length=25) Basically, an item could be given by donators from Givers model or it could be bought by user. If given, giver field stores id from Givers model. Else, it is 0. Now I want a query that will list out my items. If giver>0, I need to show the name of the giver. I can't create relationships here. This query has brought me so close and works like a charm on literal values but I want to provide the 'giver' field instead: data=Items.objects.all().extra(select={'giver_name':giver_name(1,False)}).values('giver_name','id','date') It works like a charm even if given any number (exists or not exists). But I want to do something like this but it fails cos field is not found or undefined: data=Items.objects.all().extra(select={'giver_name':giver_name(giver,False)}).values('giver_name','id','date') giver_name is a function that accepts id of a giver and a boolean value and returns a name. -
Max rows a django model can retreieve via model.objects.all()
In of my models, there exist 2 million rows and I query this based on a date range. When setting a limit to around 100-1000 rows, the query runs but when the number of rows is e.g. 100k then the query doesnt seem to run. My question is, is there a limit to how many queries a django model can make and if so what is it? queryset = Overall.objects.all()[:1000] ## works queryset = Overall.objects.all() ## doesnt work serializer = OverallSerializer(queryset, many=True) data = serializer.data -
Vagrant randomly refusing connections with Django project
I've been having a weird issue with Vagrant running a Django project. One day, it'll be working fine, and I'm humming along with API development with Postman. Next day, after executing vagrant up with zero configuration changes, the box will refuse any connections whatsoever. If I ssh into the box and execute curl with the same API URL request, it executes fine. Needless to say, this is highly frustrating. Unfortunately, I don't know Docker and don't have the time to learn, or I'd jump ship. In the meantime, any help is appreciated. Vagrant version 1.9.8 OSX 10.11 Vagrantfile: Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" config.vm.network "forwarded_port", guest: 8080, host: 8080 config.vm.network "private_network", ip: "10.0.0.151" config.vm.synced_folder ".", "/home/vagrant/project" config.vm.provider "virtualbox" do |vb| vb.memory = "6096" vb.name = "local-work" end config.vm.provision "shell", path: "provision/install.sh" end In Postman, if I do http://10.0.0.151:8080/path/to/resource, it'll hang and return connection error. Same when accessing Django app on a different URL. -
Matching query doesn't exit in django
Here I am getting an error, matching query doesn't exist. Its is working in my local machine but when i am running it in docker i am getting this error, -
Django/unittest run command at the end of the test runner
I'm using the Django test runner to run my unit tests. Some of these tests use factories which create TONS of files on my local system. They all have a detectable name, and can be removed reasonably easily. I'm trying to avoid having to either A) Keep a file-deleting cron job running, or B) Change my custom image model's code to delete the file if it detects that we're testing. Instead, I'd like to have a command run once (and only once) at the end of the test run to clean up all files that the tests have generated. I wrote a small management command that deletes the files that match the intended convention. Is there a way to have the test runner run call_command on that upon completion of the entire test suite (and not just in the tearDown or tearDownClass methods of a particular test)? -
Django query for foreign key relationship
Let's say, I have Three models in Django User name username Dog name owner ForeignKey(User) Cat name owner Foreignkey(User) Now my question is - count how many owner have dogs and cats, with django orm? or total number of owners who have dogs and cats. What kind of joining it will be? -
KeyError when unittesting Django views/URLs
I'm trying to test a URL/view in Django 1.11 and keep getting some errors that appear to be related to URL namespaces. The namespace as defined in the projects main URLs file and the local URL name as defined in the app's URLs file match what I put in the test and all looks fine in the template as well. I've tried a few things from looking at the docs and have no idea what's going on. Would appreciate any help, thank you. My test for the URL/view: from django.test import TestCase, Client from .models import Course, Step from django.utils import timezone from django.core.urlresolvers import reverse, resolve ... ... class CourseViewsTests(TestCase): def setUp(self): self.course = Course.objects.create( title="Python Testing", description="Sample description" ) self.course2 = Course.objects.create( title="New Course", description="New course description" ) self.step = Step.objects.create( title="Intro to Doctests", description="Learn to write tests in your docstrings", course=self.course ) # self.client = Client() def test_course_list_view(self): resp = self.client.get(reverse('courses:list')) self.assertEqual(resp.status_code, 200) self.assertIn(self.course, resp.context['courses']) self.assertIn(self.course2, resp.context['courses']) My root urls.py: from django.conf.urls import url from django.contrib import admin from . import views from django.conf.urls import include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^courses/', include('courses.urls', namespace="courses")), url(r'^admin/', admin.site.urls), url(r'^$', views.home, name="home"), ] urlpatterns += staticfiles_urlpatterns() My urls.py … -
django install failed in runnung dockerfile on ubuntu
Greeting, I followed the docker compose quickstart example at https://docs.docker.com/compose/django/, using my docker environment in CentOS VM and Ubuntu VM. The example works in CentOS, but not in Ubuntu. The failure happens in RUN pip install -r requirements.txt The error is as Step 6/7 : RUN pip install -r requirements.txt ---> Running in 7ed9830cea5f Collecting Django (from -r requirements.txt (line 1)) Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12ff70470>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12ff70438>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12ff706a0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12f4fe5f8>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fe12f4fea58>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Could not find a … -
always getting "This field is required" error on Django form
Hi I had a form with some field and it was working fine. And then I added one new field in the model and migrated it. Now when I run the program and click on submit then it shows error for that newly added field that This field is required although I am providing data for this field in the form. Model.py class UserInformation(models.Model): firstName = models.CharField(max_length=128) lastName = models.CharField(max_length=128) userName = models.CharField(max_length=128) institution = models.CharField(choices = [("@xyz.org","XYZ"), ("@abc.edu","ABC")], max_length=128) userEmail = models.CharField(default="N/A", max_length=128) phoneNumber = models.CharField(max_length=128) orchidNumber = models.CharField(max_length=128) PI = models.CharField(max_length=128) PIUsername = models.CharField(max_length=128) PIInstitution = models.CharField(default="N/A",choices = [("@xyz.org","XYZ"), ("@abc.edu","ABC")], max_length=128) PIEmail = models.CharField(default="N/A", max_length=128) PIPhoneNumber = models.CharField(max_length=128) In this model PIEmail is the field which I have added. forms.py class UserInformationForm(ModelForm): firstName = forms.CharField(max_length=254, widget=forms.TextInput({ 'class': 'form-control', })) lastName = forms.CharField( widget=forms.TextInput({ 'class': 'form-control', })) userName = forms.CharField( widget=forms.TextInput({ 'class': 'form-control', })) institution = forms.ChoiceField( choices = [("@xyz.org","XYZ"), ("@abc.edu","ABC")] ,widget=forms.Select({ 'class': 'form-control', })) phoneNumber = forms.CharField( required=False, widget=forms.TextInput({ 'class': 'form-control', })) orchidNumber = forms.CharField( required=False, widget=forms.TextInput({ 'class': 'form-control', })) PI = forms.CharField( widget=forms.TextInput({ 'class': 'form-control', })) PIUsername = forms.CharField( widget=forms.TextInput({ 'class': 'form-control', })) ctsaPIInstitution = forms.ChoiceField( choices = [("@xyz.org","XYZ"), ("@abc.edu","ABC")] ,widget=forms.Select({ 'class': 'form-control', })) PIPhoneNumber = forms.CharField( … -
Django Interactive lists based on Database query and user selection
I would like to create 2 lists in Django. The first one lists all results returned from a db query (external query). The second pane is blank until a selection is done. This is single selection drop down Once the user selects an item in the first drop down a list of all results for that selection is displayed (based on another db query). This selection is multi select. I am not sure what elements allow multi select in Django Example. Select City in first list, get a list of all centres in second list, select multiple centres in second list and submit The information being queried is from an external db, I could also use API, but my difficulty is not in the query but how to create the elements and update them based on selection. I am also using django-bootstrap3 -
MySQL giving various connection errors on linux, even on the same machine
I'm getting a bunch of errors trying to access my MySQL database, which seem related, but which kick in at different times. So I had a Django/Celery (using RabbitMQ) framework running machine learning jobs distributed across three different computers with a MySQL database to store the results in, and I all of the sudden couldn't access any of my data from Django. I tried to access the database directly as well, but no luck. When I ran sudo service mysql status it said it was stopped, so I restarted the service and then the computer with no luck. The big issue is that I seem to be getting inconsistent and intermittent errors, and I can't seem to piece them together into one problem. For example, sometimes when I run mysql -u root -p or mysqldump commands (to at least try and save the data I've collected), I get a ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111) Although I've checked, and that socket is there at that path, and that's the same path that my /etc/mysql/my.cnf file specifies under socket. According to answers at here and elsewhere, I've also tried to change permissions, and change …