Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set the "value" in Select ModelChoiceField from ORM data
I'm using a ModelChoiceField and populating it directly from the ORM, but would like to specifically set the "VALUE" attribute. I create my form object as such: dog_breed = forms.ModelChoiceField( queryset=Breeds.objects.all(), label='', widget=forms.Select(attrs={ 'id': 'dog-breeds', 'class': 'select-standard' })) NOW: Returns the following when rendered: <option value="1">Black Lab</option> <option value="2">Golden Retriever</option> GOAL: How can I set the "value" attribute so it renders as such: <option value="Black Lab">Black Lab</option> <option value="Golden Retriever">Golden Retriever</option> -
MYSQL query to Django
Hi guys I want to get this query in Django and cant seem to get the results I want SELECT DISTINCT herramienta_id,sum(cantidad) FROM inventario_transaccion WHERE carrito_id = 1 and herramienta_id = 1; this query return in MYSQL Workbench herramienta_id cantidad +--------------+---------+ | 1 | 5 | +--------------+---------+ What I'm trying to do is get all tools with carrito_id = pk , and get all distinct values and sum the cantidad of each -
Django query many objects in many
Is there a query way of doing the following in Django models like joining in SQL? result = [] for f in self.Functions.all(): result = result + list(f.Properties.all()) return result -
django working with url parameters in views and templates
I am using Django 2.1+, with Python 3.6+. in my urls.py, I have this url: url('^member/(?P<username>[\w\-]+)/$', views.Member, name='member_data'), Alone this works: However from both the view: def login(request): email = request.POST['email'] password = request.POST['password'] username = User.objects.get(email=email) user = authenticate(request, username=username.username, password=password) if user is not None: auth_login(request, user) # Redirect to a success page. return reverse('member_data', {'username': username.username}) else: # Return an 'invalid login' error message. return redirect('login_page', {'error': 1}) and from the template (of note, this is a hardcode username to attempt to get the template the work): <a href="{% url 'member_data' username='cheng' %}"><i class="ion ion-person"></i>My Service Record</a> Results in a bad parameter error, in which I cannot resolve. As such, Any wisdom here would be greatly appreciated. Is there a way this is supposed to read for both links? -
Django signals created kwargs is true while updating
I think I am missing something here, but here it goes. I have a model, and it is a sender for a post_save signal. class Book(models.Model): ... created_at = models.DateTimeField(default=timezone.now) bought = models.BooleanField(default=False) @receiver(post_save, sender=Book) def create_sold_log(sender, instance, **kwargs): if kwargs['created'] and instance.bought: print('created and instance.bought') print('k* created', kwargs['created']) elif kwargs['created']: print('created only') print('k* created', kwargs['created']) else: print('else...') Now everytime a book object is saved, the above signal will fire. So from the below data, after the serializer is saved while the Bought is True, kwargs['created'] is True. data = { "...": "...", "bought": True } serializer = CustomSerializer(data=data) if serializer.is_valid(): serializer.save() And suppose, from the below data, if the bought=False and I save the serializer, the kwargs['created'] is True. data = { "...": "...", "bought": False } serializer = CustomSerializer(data=data) if serializer.is_valid(): serializer.save() But, suppose, later if I update the book object to Bought=True and save it, the kwargs['created'] is still True. ticket.bought = True ticket.save() What am I missing here? Can someone please help me understand. Thank you -
How to use a list passed with {% include with %} in jQuery script?
So I am including template with jQuery script and pass there a list of some values. {% block content %} {% include 'path/foo.html' with key=val_list %} {% endblock %} This is the foo.html {% load staticfiles %} <script src="{% static 'jquery-ui/jquery-ui.js'%}"></script> <script> var availableTags = [ "some", "values", "here" ]; </script> I want to fill availableTags with list from my key. I can access elements from that list before script using: {% for k in key %} {{ k }} {% endfor %} But can't do that inside script. I think I know why but I don't know how to make this work. -
Django nested relation with a serializer or hyperlinkedRelatedField
In Django REST Framework I want to be able to read nested data of a ForeignKeyRelated field but retain the ability to select a new relation. When I link the related field to a serializer I get the data I want, but it then when I try to post to endpoint it expects the required fields of the related field too. So I made it read only and now I'm not sure how to update the relation. Can someone help me work out how to handle these relations? Current hyperlinked relation, I have the hyperlink relation but not the nested data. class ProjectSerializer(serializers.ModelSerializer): company = serializers.HyperlinkedRelatedField( many=False, view_name='company-detail', queryset=model.objects.all() ) class Meta: model = Project fields = '__all__' Trying this to nest company field, I have the data but have lost the ability to select a company. class ProjectSerializer(serializers.ModelSerializer): company = CompanySerializer(many=False) class Meta: model = Project fields = '__all__' The related serializer class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name', 'url', 'clients', 'addresses') -
Django group by does not work properly
here is my class class Tizz(models.Model): key = models.PositiveIntegerField(default=0) name = models.CharField(max_length=20) value = models.CharField(max_length=500) my query qs = Tizz.objects.values('primary_key').annotate( hand=Concat(Case(When(column_name='hand', then=F('value'))), Value(''), output_field=CharField()), maintain=Concat(Case(When(column_name='maintain', then=F('value'))), Value(''), output_field=CharField()), pkey=Count('primary_key') ) str(qs.query) give me wrong sql SELECT "app_celltizz"."key", COALESCE(CASE WHEN "app_celltizz"."name" = hand THEN "app_celltizz"."value" ELSE NULL END, ) || COALESCE(, ) AS "hand", COALESCE(CASE WHEN "app_celltizz"."name" = maintain THEN "app_celltizz"."value" ELSE NULL END, ) || COALESCE(, ) AS "maintain", COUNT("app_celltizz"."key") AS "pkey" FROM "app_celltizz" GROUP BY "app_celltizz"."primary_key", COALESCE(CASE WHEN "app_celltizz"."name" = hand THEN "app_celltizz"."value" ELSE NULL END, ) || COALESCE(, ), COALESCE(CASE WHEN "app_celltizz"."name" = maintain THEN "app_celltizz"."value" ELSE NULL END, ) || COALESCE(, ) Always adding others CASE WHEN after the GROUP BY, I don't know why. Please help. -
How to create a PointField Django 2 Form Field
I want to create a PointField from user click event on openlayers map using Django 2 which i want to store in the database. I have made the forms.py, but i don't quite understand how a PointField can be automatically populated from a user click event instead of manually entering from map click event. I have heard of widgets but no idea how they work. Can you please give an example of forms.py or how widgets work in Django 2? -
Wagtail: Nested Inline Panels
I would like to place an Inline panel into an Inline panel, and place that Inline panel into a Snippet. According to these links, Wagtail has not supported nesting Inline panels in the past: https://groups.google.com/forum/#!msg/wagtail/3i-THVOV7AI/zCo58xfu1IEJ https://groups.google.com/forum/#!topic/wagtail/sJbFVc5gvmw Since these are a few years old, does anyone know if Wagtail can handle nested Inline panels now? If not, is there a newer workaround for implementing a nested Inline panel into a Snippet? -
Django: 1215, 'Cannot add foreign key constraint' on model with only one field
I have a model that is only this: class Salad(models.Model): some_field = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) Nothing else No matter how I call the class, the single field, what models I put instead of Profile, or whichever on_delete option I choose. I systematically get the error: django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') It's driving me completely crazy! Any idea what is happening? The error log: Traceback (most recent call last): File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute Applying playerdata.0053_auto_20180724_1943... return self.cursor.execute(sql, params) File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute return self.cursor.execute(query, args) File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 247, in execute res = self._query(query) File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 411, in _query rowcount = self._do_query(q) File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query db.query(q) File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 292, in query _mysql.connection.query(self, query) _mysql_exceptions.IntegrityError: (1215, 'Cannot add foreign key constraint') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2017.3.2\helpers\pycharm\django_manage.py", line 52, in <module> run_command() File "C:\Program Files\JetBrains\PyCharm 2017.3.2\helpers\pycharm\django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "C:\Users\Div-o\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 96, in … -
Django intersect count annotate for sorting
In this question, we were given a solution to sort a query based on the intersection of two many to many fields. While it's a great answer, the restriction is that you have to filter first. Say I have the same two models. Is there a way to annotate all results by count of intersection, so that I can display all Questions regardless of location, but still sorted by location? class Location(models.Model): name = models.CharField(max_length=100) class Profile(models.Model): locations_of_interest = models.ManyToManyField(Location) class Question(models.Model): locations = models.ManyToManyField(Location) I wish I could do something like this: from django.db.models import Count matching_profiles = Profile.objects.all().annotate( locnom=Count('locations_of_interest__in=question.locations.all()') ) Any ideas? Do I just have to make two queries and merge them? -
Annote the occurances of a field value across all arrayfields
I have a complicated Django model that can be represented, in a very simple form, for this question by the following model. class Person(models.Model): name = models.CharField(max_length=20) friends = ArrayField(models.CharField(max_length=20)) It has a name and a list of people that the person considers to be their friends. This relationship may not go both ways. The data that populates this model is collected on the fly and someone might state that they have a friend who is not already entered in the model yet. This means that a many-to-many relationship can not be used. I want to find a pure database query using the Django ORM that can annotate a queryset with the number of times a person is entered in another persons friend list. I could do this in memory with the following code; >>> people = Person.objects.all() >>> friended_count = [] >>> for person in people: >>> friends = people.filter(friends__contains=[person.name]) >>> friended_count.append({'name': person.name, >>> 'friend_count': friends.count()}) I could make this more memory efficient by paginating the queryset, but I feel like there must be a way to do this with a annotation query that would work better for large sets of data. Any thoughts? -
Is django channels better than django&tornado to make a chat application
I'm wondering if django channels is better to solve the instant messaging problem than using a tornado backend to serve django? -
Angular 6 HTTP JSON POST Requset parser
I need to send 4 types of data to django server as json when user is registering, but i've got an array of data. How do I sort different types to send'em separately? When I do like: this.userService.register(this.registerForm.value) I've got the following response from django server: {'phone': '1', 'name': '1', 'username': '1', 'password': '111111'} <class 'NoneType'> <class 'NoneType'> <class 'NoneType'> <class 'NoneType'> Here is my code: create-user.component.ts: ngOnInit() { this.registerForm = this.formBuilder.group({ phone: ['', Validators.required], name: ['', Validators.required], username: ['', Validators.required], password: ['', [Validators.required, Validators.minLength(6)]] }); } // convenience getter for easy access to form fields get f() { return this.registerForm.controls; } onSubmit() { const userStr = JSON.stringify(this.registerForm.value) this.submitted = true; // stop here if form is invalid if (this.registerForm.invalid) { return; } this.loading = true; this.userService.register(JSON.parse(userStr)) .pipe(first()) .subscribe( data => { this.alertService.success('Registration successful', true); this.router.navigate(['/login']); }, error => { this.alertService.error(error); this.loading = false; }); } user.service.ts: register(user: User) { return this.http.post(`/create_user/`, user); } user.ts: export class User { name: string; username: string; password: string; phone: number; } -
python routing regex
Struggling with urls.py Error : [pylint] E0602:Undefined variable 'patterns' In code : from django.conf.urls import * from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', 'notes.views.home', name='home'), url(r'^admin/', include(admin.site.urls)), ) following tutorial on link : Django Tutorial: Building a note taking app Problem number 2. Same problem in tutorial : Simple Django Web Application Tutorial from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'\^admin/', admin.site.urls), url(r'\^myrestaurants/', include('myrestaurants.urls', namespace='myrestaurants')), ] -
Using the delete button in the django admin change form redirects to admin page with warning but doesn't delete
Trying to upgrade from django 1.7 to django 1.11 On the change form in any model of my project, the delete button at the very bottom of the change form redirects me back to /admin/ with the message TABLE_NAME with ID 'object-pk/change' doesn't exist, perhaps it was deleted? But from the model change list page i can select and use the delete action to delete a row in the table. This works as expected, it takes me to a confirmation page, which then allows me to agree to the deletion of the row. What is particular strange is the addition of the '/change' to 'object-pk/change' in the warning Any help would be greatly appreciated. -
authenticate creates the user but without email
when I use 'user = authenticate(username=username, email=email, password=password)' the user is created but whitout the email. I have a old project where this code worked perfectly but now it doesnt work in any project. this is my views: from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login as django_login from django.contrib.auth.forms import UserCreationForm from .models import Profile def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST or None) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') user = authenticate(username=username, email=email, password=password) django_login(request, user) return redirect('profile/') form = UserCreationForm() context = {'form': form} return render(request, 'accounts/signup.html', context) this is the template: {% block content %} <main> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <p>Username:</p> <input type="text" name="username"> <p>Email:</p> <input type="text" name="email"> <p>Password:</p> <input type="password" name="password1"> <p>Repeat password:</p> <input type="password" name="password2"> <p><input type="submit" value="submit"></p> </form> </main> {% endblock %} -
How can I reset a Django test database id's after each test?
I have a django app and I am running some unit tests on it. So the problem I am having is not when one test inserts into the test db. It is the tests that come after. Since each test is not saving the transaction, the entry from a previous test is not there which is fine, although the auto increment id's are increasing as if there are still entries into the database. Which I need to fix because I am inserting more data where I cannot control the id's given to it and need to be able to grab this specific data for the test. If I hard code the code to grab the objects I will have to change the code for every time I add a new test, which is not ideal. I have a solution on how I can fix this on the actual database but not the test one. For mine I need to be able to connect to a docker container and run a psql command to reset the table_id_seq. docker exec -t $CONTAINER_ID psql --dbname=test_database_name -username=user -c "SELECT setval('modelName_appName_id_seq', 2, true)" This will go to the table and set the last id value … -
How to use use ws:// instead of wss:// with a page loaded over https:// | django channels
I'm using django-channels v1.0.2 and daphne. My website uses a ssl certificate. Since my website runs over ssl, the browser throws an error if I try connecting to websocket with ws://. Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS. And again if I try to connect with wss://: WebSocket connection to 'wss://example.com:8080/chat/stream/' failed: WebSocket opening handshake timed out Again.If I try connecting from the console itself: import websocket ws = websocket.WebSocket() ws.connect("wss://example.com:8080") conenction timeout But with: ws.connect("ws://example.com:8080") a handshake takes place and everything is fine. I read somewhere that daphne accepts only ws:// and we need to do something in order to convert wss:// after arrival to ws://. something like that. All I'm looking is for a way to make it work. Is there anyway to use ws:// while loading the page over https://? If it is. Then please explain in brief. I'm completely new here. If there is a way to communicate, by using something in between daphne and the socket through wss://. What is the process? What am I supposed to do? How? -
/ in search query causes 404.
In Django I have a data field where entries may or may not contain the url sensentive character "/". I was wondering if there was any way to escape this character as not to be parsed by Django. I have tried coverting it to hex but it still filters as if it were a "/" -
Django Web application publishing
How to publish django web application? what are the steps to be followed for publishing a django application? is there any free hosting for pulishing? thanks in advance -
SAML backdoor solution
We have a Django-based web portal which performs user authentication and authorization via SAML SSO. However, some administrative users in our organization also want to be able to access the portal as a client-independent administrative user to perform various administrative/maintenance tasks. In other words, the pushback is expected if our own user will need to be configured in the client's IdP. Currently SSO flow is implemented as a separate custom-made backend utilizing python-saml library for its authentication and overriding django.contrib.auth authentication mechanism with some proprietary mappings of groups supplied within the SAML message to Django's django.contrib.auth.models.User and django.contrib.auth.models.Group. In turn, normal Django admin application flow relies on presence of django.contrib.sessions.middleware.SessionMiddleware and django.contrib.auth.middleware.AuthenticationMiddleware and requires an application restart. What would be the possible alternatives in implementing such a SAML backdoor solution? We are thinking of several (least invasive, mainly configuration) possibilities, perhaps someone could suggest something better: Establish a user on the client IdP having all necessary groups necessary to do administrative tasks. Deploy our own IdP component aware of to Portal’s SP endpoint and then configure a user with necessary privileges on that IdP. Necessary administrative work is performed by that user. Designate a maintenance window agreed with the client … -
Trying to add custom font in three.js
Trying to add my own custom font, but nothing has been loaded at all, is there a way to get three.js to render my font: Custom Font "{%static "js/pink.json"%}" --> this is django's template tagging. var loader = new THREE.FontLoader(); var font = loader.load( "{%static "js/pink.json"%}", function ( font ) { var textGeo = new THREE.TextGeometry( "My Text", { font: font, size: 3, height: 3, } ); var textMaterial = new THREE.MeshPhongMaterial( { color: 0x000000 } ); var mesh = new THREE.Mesh( textGeo, textMaterial ); mesh.position.set( x, y, z ); scene.add( mesh ); -
Django admin search concerning checkboxes
Given generic model with BooleanField say A, how do I get that model returned in Django Admin if I want to know which models have A set to True? When it comes to CharFields etc you can simply add the fields to search_field in admin.py and it works pretty well. However, adding A to search_fields does not return any results. Like what exactly do I enter into the search bar of admin panel? Or is this something for which I will have to override the search method as shown here? Django admin search: how to override the default handler?