Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django check if exists ManyToMany relation
There is a Translator model in my project. This model has ManyToManyField languages_verified (verbose_name='users_languages_verified') and languages_not_verified. I want to get all Language objects which are at at least one languages_verified set. So if translator x and y: x.languages_verified = ['FR','EN'] x.languages_not_verified = ['RU','SK'] y.languages_verified = ['RU'] y.languages_not_verified = ['SK','CZ'] Then the output would be ['FR','EN','RU'] (not 'SK' nor 'CZ' because they are not in at least one languages_verified set) It would be possible to do that for example this way: lang_ver_set = [] for language in Language.objects.all(): for translator in Translator.objects.all(): if language in translator.languages_verified(): lang_ver_set.append(language) break But I'm not sure if this is a most efficient way how to do that. Django has many magic filter tricks like verbose_name__in... which could be probably faster but I can't find the solution. -
django.db.utils.OperationalError: server closed the connection unexpectedly
Not able to solve what is the error. django.db.utils.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. I keep on getting the Trace when i run any of the command below python manage.py makemigrations python manage.py runserver Unhandled exception in thread started by <function wrapper at 0x0000000003DAC4A8> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check_migrations() File "C:\Python27\lib\site-packages\django\core\management\base.py", line 437, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 52, in __init__ self.build_graph() File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 203, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 65, in applied_migrations self.ensure_schema() File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 204, in _cursor self.ensure_connection() File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "C:\Python27\lib\site-packages\django\db\backends\postgresql\base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "C:\Python27\lib\site-packages\psycopg2\__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: server closed … -
Reading what you have wrote in a <input> in django
I don't quite understand what Django is, or how it works, but I would quite like to know if it would be possible to read what the user has written in a <input> HTML element. Also, I have Googled Django and it came up with a load of python code, which I also don't understand. Many thanks in advance. -
user.groups.add(group) or group.user_set.add(user), Which is better and why ? or difference between them
I am trying to extend django.contrib.auth and came accross adding a user into a group, which can be done in 2 ways. I was just wondering why is it like so, and what are the advantages of one over the other. -
Drop Down Search Field in Django
Does anyone know of some way to create a text box in Django where when you begin typing in the box, suggestions that contain those letters from a list begin to appear underneath the text box? Similar to Google's autocomplete. For example in a box where I type in "Br" results underneath the text box may be "Bread", "Bran", "Abraision" -
Django channels http.disconnect
I've been exploring using Channels to return a long-running HttpStreamingResponse. I would would expect that if the client closes the request connection that a message would be sent on the http.disconnect channel, but this only seems to happen when the server closes the response. This is my setup: consumers.py from time import sleep from channels import Group from channels.handler import AsgiHandler from django.http import StreamingHttpResponse def channel_name(message): _, _, channel_name = message.reply_channel.name.partition('!') return channel_name def fib_stream(): x = 0 y = 1 while x < 35000: print x yield unicode(x) + '\n' x, y = y, x + y sleep(0.5) def fib_stream_endpoint(message, **kwargs): response = StreamingHttpResponse(fib_stream()) name = channel_name(message) group = Group(name) print 'New Group with "%s" name' % name group.add(message.reply_channel) for chunk in AsgiHandler.encode_response(response): group.send(chunk) def http_disconnect(message): # import pdb; pdb.set_trace() name = channel_name(message) print 'Disconnected form "%s" Group' % name Group(name).discard(message.reply_channel) routing.py from channels.routing import route from apps.builds import consumers channel_routing = [ route('http.request', consumers.fib_stream_endpoint, path=r'/api/v1/applications/(?P<application_id>[0-9]+)/builds/log$', method=r'^GET$'), route('http.disconnect', consumers.http_disconnect), ] Opening a shell session I can kick off the streaming response with: import requests channels_url = 'http://localhost:8000/api/v1/applications/1/builds/log' resp = requests.get(channels_url, stream=True) However, if I do resp.close() or resp.raw.close(), Channels does not call the http_disconnect callback. Http_disconnect is only … -
Django cache display image issue
I'm picking random ImageField from database and saving its result in cache for 10 seconds and display it in one of my templates. For some reason after 10 second I don't see a different image, which is my goal. I'm using memcache. Part of my get_context_data(self, **kwargs) from Class Based View: ... dummy_images = DummyImage.objects.all() dummy_images_counter = DummyImage.objects.all().count() random_image = get_object_or_404(DummyImage, pk=dummy_images[random.randrange(0, dummy_images_counter)].id) cache.set('image', random_image, 10) context = {'width': width, 'height': height, 'img': cache.get('image')} Template: {% load static %} <img src="{% static "dummy_images/images/" %}{{ img.image.url }}" width="{{ width }}" height="{{ height }}"> What am I doing wrong? -
Setting up Vagrant for django tutorial
I have found a django beginner+ tutorial. However, I encountered an issue I can't resolve by myself. First I changed all precise64 to precise32, because even if I run 64 bit Xubuntu 16.04, my potato processor does not support VT-X technology, and had to download 32 bit version of Vagrant. Then, I run vagrant up and got error: mixlib-shellout requires Ruby version >= 1.9.3. Even if my Ruby is 2.3.1p112. I found this question similar to my problem. However, when I added lines posted by user Queenvictoria, I got this error message (I paste most of it, but I think bottom part is most important): ==> default: Running provisioner: shell... default: Running: inline script ==> default: stdin: is not a tty ==> default: Reading package lists... ==> default: Building dependency tree... ==> default: Reading state information... ==> default: The following extra packages will be installed: ==> default: dpkg-dev fakeroot g++ g++-4.6 libalgorithm-diff-perl ==> default: libalgorithm-diff-xs-perl libalgorithm-merge-perl libdpkg-perl libruby1.9.1 ==> default: libstdc++6-4.6-dev libyaml-0-2 make patch ruby1.9.1 ==> default: Suggested packages: ==> default: debian-keyring g++-multilib g++-4.6-multilib gcc-4.6-doc libstdc++6-4.6-dbg ==> default: libstdc++6-4.6-doc make-doc diffutils-doc ruby1.9.1-examples ri1.9.1 ==> default: graphviz ==> default: The following NEW packages will be installed: ==> default: build-essential dpkg-dev fakeroot … -
How to access class instance from within the inline declaration?
I think this is best understood with an example: Pizzas and Toppings have a many to many relationship. I want to display a Pizza's toppings in a TabularInline. class ToppingInlineAdmin(admin.TabularInline): model = Pizza.toppings.through fields = ('topping',) extra = 0 if not model.topping.count(): classes = ['collapse'] As you can see, I only want to collapse the tabular inline if there are no toppings on the pizza. The code model.topping.count() does not work though. The error is: AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'count' Do you know how I can accomplish if no toppings on the pizza, collapse the tabular inline? Thank you. -
Django extended user model doesn't have extended attributes
I am extending the default User model in this way models.py from django.db import models from django.contrib.auth.models import User class Profile(User): city = models.CharField(max_length = 60) company = models.CharField(max_length = 100) def __str__(self): return self.username I am registering the user with the following view. class ProfileFormView(View): form_class = UserForm template_name = 'register.html' # Display empty form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # Process user data and add to DB. def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit = False) # clean form data. username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.city = form.cleaned_data['city'] user.company = form.cleaned_data['company'] user.set_password(password) user.save() # returns User object if credentials are correct user = authenticate(username= username, password = password) if user is not None: if user.is_active: login(request, user) return render(request, 'profile.html', {}) return render(request, self.template_name, {'form': form}) as you can see I redirect to profile.html once Submit is pressed on the registration page the view function I call in the form's action is as follows def home(request): all_users = Profile.objects.all() city = request.user.city # this line throws error return render(request, 'profile.html', {'city': city,'login_user': request.user, 'all_users': all_users}) Exception Value: 'User' object has no attribute 'city' but I am not … -
Add a relationship to pre-existing models in Django
I have a bad model schema that looks like this but need to make the best of it. class Model1(models.Model): id = models.ForeignKey('Model2', to_field='id', null=True) condition = models.FloatField(null=True) class Model2(models.Model): id = models.CharField(max_length=10, unique=True) first_name = models.CharField(max_length=10, blank=True, null=True) class Model3(models.Model): id = models.CharField(max_length=10) last_name = models.CharField(max_length=10, blank=True, null=True) I would like to change the id in Model2 to be a foreign key linking to the existing ids in Model3 but am having some serious issues. The models share the id variable but it is not linked between Model2 and Model3 in any way. The eventual goal is to be able to do perform a queryset as below Model1.objects.filter(condition=num, id__id__last_name="Brown") Any help would be greatly appreciated. -
Django migrate tables to new database
I originally had a django project with a single app and all models were defined in that app. The project, when initiated only used the default database. It has now become an unwieldy app that I'm trying to break down into smaller apps. Doing so, I want to use different databases for the different apps. I've setup new databases and a router in the settings.py file. However, I'm confused about how to migrate existing tables to the new databases. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'db_user_name', 'PASSWORD': 'password', 'HOST': 'hostname', 'PORT': '3306', }, 'db2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name2', 'USER': 'db_user_name2', 'PASSWORD': 'password2', 'HOST': 'hostname2', 'PORT': '3306', } } I would want an app (e.g. app1) to be moved from default to db2. The router already knows to specify app1 to db2 but running migrations is doing nothing. Any ideas? -
Count data from a table excluding duplicates
I need to count elements from a table. The problem is that I do have a solution for this, but I'm using a function that deletes duplicates from the table and then I can get the count without issue (but it takes a while to process) This is an example of my model/table: If I do a count from this I will get the following result: 3 Shipped, 4 allocated, 2 No status, 1 Loaded. What I need is to get the following result: 2 Shipped (ignoring 1 duplicate), 1 Allocated (ignoring 3 duplicate), 2 No status(There is no duplicate), 1 Loaded. Thanks for your time, -
Validating the form without required field in django 1.8
My django modelform is letting the user submit the form without raising error even when the user hasn't submitted appropriate form, here it lets the user keep the email field blank.It doesn't save into the database because of is_valid() but the page refreshes and form goes blank again... Here is the code models.py from django.db import models class MainForm(models.Model): text = models.CharField(max_length=100) email = models.EmailField(blank=False) name = models.CharField(max_length=100,blank=False) def __unicode__(self): return self.email forms.py from django import forms from .models import MainForm,new_model class form_MainForm(forms.ModelForm): class Meta: model = MainForm fields = '__all__' views.py def view_MainForm(request): context = { "form": form_MainForm } if request.method == 'POST' : form_instance = form_MainForm(request.POST or None) if form_instance.is_valid(): form_instance.save() return render(request,'done.html',{'text':form_instance.cleaned_data.get('email')}) return render(request,'main_form.html',context) template ->main_form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Main Form</title> </head> <body> <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> </body> </html> -
uWSGI restarts attached processes without stopping old ones
I have a web app that requires several custom consumer scripts to run in parallel with the main Django app. Since I am already running Django app using uWSGI, I figured that I would use emperor mode and attach-daemon config to start my other processes at the same time as the main app. It works fine for every process except one. The difference between this process and others is that this process forks several worker threads that pick jobs from a queue that the master process fills. The relevant code looks like this def worker(q): while True: item = q.get() ... do things with the item ... q.task_done() def heartbeat(): the_queue = Queue() # create the thread pool for n in range(NUMBER_OF_THREADS): t = threading.Thread(target=worker, args=(the_queue,)) t.setDaemon(True) t.start() while True: # mark the start time start_time = datetime.utcnow() # use Django ORM to get a list of devices for device in Device.objects.all(): the_queue.put(device) # wait for workers to deal with things the_queue.join() # mark the end time end_time = datetime.utcnow() time.sleep(SOME_CALCULATED_AMOUNT) if __name__ == "__main__": heartbeat() My uWSGI config for this process looks like this [uwsgi] master = true enable-threads=true chdir=somedir uid=ubuntu gid=ubuntu pidfile=somepath daemonize=somepath env=DJANGO_SETTINGS_MODULE=settings attach-daemon2 = cmd=python3 heartbeat/heartbeat.py,control=true … -
django rest framework does not PATCH in IE11
jquery: 1.7.2 django rest framework: 3.0.5 django: 1.5.5 I have successful jquery ajax calls that hit the DRF endpoint and PATCH my records in every browser except IE11. IE just times out. js: values = {'value':'update'}; $.ajax({ url: '/api/path/', type: 'PATCH', data: values, timeout: 1000, success: function(e){ console.log(e); }, error: function(e){ console.log(e); }, complete: function(e){ console.log(e); } }); When I run this code in Chrome, it patches just fine. IE11 will timeout and return an error object: statusText: "timeout" What might be the cause of the ajax call timing out in IE? -
Django - Render view based on search query from search view
I have what is probably a very basic question. I have read through Django forms docs but am still missing something here. I want to have a search bar in one template (search.html) and return the search query in another template (results.html). I have the following so far, using this SO answer as a guide, which returns the following error. Thanks for any help. Exception Value: results() missing 1 required positional argument: 'search_id' urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^landing/', views.search, name='search'), url(r'^results/', views.results, name='results'), ] forms.py from .models import Apartment class Apt(forms.ModelForm): class Meta: model = Apartment fields = ('name', 'neighborhood') views.py def search(request): if request.method == 'POST': #the form has been submitted form = Apt(request.POST) #bound form if form.is_valid(): #validations have passed name = form.cleaned_data['name'] u = Apt.objects.create(name=name) #REST query will go here. #commit to database u.save() return redirect('results', search_id=u.name) else: #create an unbound instance of the form form = Apt(initial={'name':'name'}) #render the form according to the template, context = form return render(request, 'search/landing.html', {'form':form}) def results(request, search_id): search_id = request.POST.get('name') query = get_object_or_404(Apt, pk=search_id) return render(request, 'search/results.html', {'query':query} ) landing.html {% extends "base_simple.html" %} {% block title %}Look up your name{% endblock %} {% block main_content … -
Django Server Connection Aborted on Local server automatically
I am having bit of issue that my Django server is being aborted automatically. I've searched in detail and couldn't find any solution. I've disabled my anti-virus software, I am not behind firewall and there is no trace of any hindering application that could cause this issue. All I did was that I upgraded from pip 8 to pip 9 on Windows. Following is the error I am getting on my terminal. Exception happened during processing of request from ('127.0.0.1', 51530) Traceback (most recent call last): File "C:\Python27\Lib\SocketServer.py", line 599, in process_request_thread self.finish_request(request, client_address) File "C:\Python27\Lib\SocketServer.py", line 334, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Mudassar\dcom8\lib\site-packages\django\core\servers\basehttp.p y", line 102, in __init__ super(WSGIRequestHandler, self).__init__(*args, **kwargs) File "C:\Python27\Lib\SocketServer.py", line 657, in __init__ self.finish() File "C:\Python27\Lib\SocketServer.py", line 716, in finish self.wfile.close() File "C:\Python27\Lib\socket.py", line 279, in close self.flush() File "C:\Python27\Lib\socket.py", line 303, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 10053] An established connection was aborted by the software in yo ur host machine I am not communicating with any server side api for now its a simple local app. Please advise. -
Display all b tags inside p tag with BeautifulSoup
I have app in django and I have to display text in specific way. This is my html code: <p class="name"> <b>Name of person</b> City, Country</p> <p class="name"> <b>Name of person</b></p> I want to get bolded Name of person and City and Country in normal text, for example: **Name of person** City, Country **Name of person** But I can get only b, how can I get all p and b inside p? My code in BeautifulSoap: people = self.concattexts.filter(code='Active') for p in people: soup = BeautifulSoup(p.text_html, 'html.parser') all_people = [b.get_text(separator=' - ', strip=True) for b in soup.find_all('b')] return all_people -
Badgr server crashing after installation
System information: Operating system: Ubuntu 16.04 Browser & version: Firefox URL of the page where you encountered this issue: http://localhost:8000/accounts/login Problem: We are trying to run the openbadges server locally and we just finished the instructions on creating a local development environment. However, whne we try to access the local url, the server crashes and we receive the following error: ImportError: No module named django_auth_lti.middleware We've tried to fix the issue ourselves but we weren't capable of fixing it. These are the error messages we get when the server starts crashing: http://pastebin.com/nP6dd17h -
ImportError: No module named encodings when installing with pip / easy_install
I tried installing importchecker with pip and with easy_install: sudo easy_install importchecker sudo pip install importchecker And i get the following error: Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in from pip import main File "/usr/lib/python2.7/dist-packages/pip/init.py", line 4, in import locale File "/usr/lib/python2.7/locale.py", line 13, in import encodings ImportError: No module named encodings I tried this, but it didn't work either: export PYTHONHOME=/usr/local/lib/python2.7 export PYTHONPATH=/usr/local/lib/python2.7 Most of the answers I've found refer to this, is there any solution? -
Extended User Patch Request updating full user instance in django rest
I have a user profile model with extended User model. I want to update certain field for this user profile model. but it shows some error. user already exist. password field should not empty. model.py class UserProfile(models.Model): user = models.OneToOneField(User,unique=False) department = models.CharField(max_length=50, choices=DEPARTMENT_CHOICES,default='technology') role = models.CharField(max_length=50, choices=ROLE_CHOICES,default='manager') serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ('username','password','first_name','last_name') class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer(partial=True) class Meta: model = UserProfile fields = ('user','department','role') def create(self, validated_data): user_data = validated_data.pop('user') user_pass = user_data.pop('password') user = User.objects.create(**user_data) user.set_password(user_pass) user.save() userprofile = UserProfile.objects.create(user=user, **validated_data) return userprofile view.py class RegisterUser(viewsets.ModelViewSet): permission_classes = (AllowAny,) serializer_class = UserProfileSerializer queryset = UserProfile.objects.all() I want to update User Profile department and role individually. i tried to implement update() in serializer or perform_update() in view but didn't work for me. please suggest the best way make the paritial update using viewset. -
Django: How To Call ModelAdmin.save_model()
I need to write a method in my ModelAdmin class that calls ModelAdmin.save_model(), without the user actually clicking on save. (The reason I want to do this is that I set up some custom buttons in my Django Admin object view. They work but any modified form data is lost, I want to save the data in the form before running the actions connected to the button.) Here's my code: from django.contrib import admin from .models import Object class ObjectAdmin(admin.ModelAdmin): def action_method(self, request, object): self.save_model(request=request, obj=object, form=self.form, change=True) admin.site.register(Object, ObjectAdmin) This doesn't raise any errors but also doesn't save my data. I'm guessing my problem might be to do with the form. Any help? -
dJango order by list of conditions
Let's say I have a list of 3 conditions: conditionA, conditionB, conditionC. I want to be able to sort my queryset so that items matching conditionA & conditionB & conditionC appears first, then conditionA & conditionB, then conditionA & conditionC etc. Is there a way to do this? -
How to obtain value for simple tags Django
Hi everyone I create my first simple_tag passing a value, but I have problem to obtain the value in my template I have this, the value that I have to pass is a string "footer1" {% render_footer "footer1" %} now, my function is like this def render_footer(footer_opc): home = Page.objects.get_home() return home.homeextension.footer_opc in that case I supposed that footer_opc = "footer1" so the return has to be home.homeextension.footer1, but don't work, y try this too def render_footer(footer_opc="footer1"): home = Page.objects.get_home() return home.homeextension.footer_opc But I obtain the same result.. the code return home.homeextension.footer_opc , this no exist... but I don't know to obtain the value of footer_opc. I try to return this to return home.homeextension.+ footer_opc but the same result. Any idea! Thanks in advance!