Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return a python list to Django
What I want to do is get the user to enter some information via HTML and it passes that as an argument to a python script, and then that python script will return a list which i can then pick apart with Jinja and display with html. I'm using Django and have seen many pages offering solutions but not found one that has worked. Below is a simple version of what my code does - which is that it returns a list: def return_list(arg): list_ = [arg, 1, 2, 3] return list_ return_list("argument") I can figure out how to get input from user another day but my main problem is passing it information and getting it to display something from within Django -
Tornado with Django authentication
Here's my idea: have a Django Website that receives / send JSON information so that I can create a JavaScript client for a Webbrowser, or a Unity / UE client I want a new functionality only for Unity / UE client: realtime chat. I'd like to use a tornado server on a specific port, let's say 8666. Here's what I've done so far: authenticate on the Django web site make everything work on the Django web site Now I'd like the client to connect to the port 8666 (pure TCP) and to send its cookie so that I can see on the tornado web server whether the client is authenticated. I didn't find any documentation about that. Do you know how to handle this? Any example, or if I'm not on the right track what should I do then? -
How can I set/replicate in a (model)form, a Model Choice Field that should be hidden?
How can I set/replicate in a (model)form, a Model Choice Field: document_type = models.CharField(max_length=100, choices=DOC_CHOICES, default=DOC_TYPE_DATASHEET)` I don't need the field in the form, because I will be set from the code base on rules. I tried, blocked on queryset: document_type = forms.ModelChoiceField(widget=forms.MultipleHiddenInput, ) or should I just don't add it in the form, and override form def save ? -
How to user Django REST serializer do validation on reserved key?
It might a simple question with eye blink workaround. But I can not be able to get it done. I am now creating the webhook endpoint. And stuck at serializer class My class can not use from as a class property @pytest.fixture def like_object(): """LIKE object response from Facebook""" return { "object": "page", "entry": [{ "changes": [{ "field": "feed", "value": { "item": "reaction", "verb": "add", "reaction_type": "like", "created_time": 1516183830, "post_id": "1331351323541869_1844740022202994", "from": { "name": "Elcoie Sieve", "id": "1639217166122728" }, "parent_id": "1331351323541869_1844740022202994" } }], "time": 1516183830, "id": "1331351323541869" }] } serializers.py class FacebookReactionSerializer(serializers.Serializer): """ value serializer the inner most of the payload """ item = serializers.CharField() verb = serializers.CharField() reaction_type = serializers.CharField() created_time = serializers.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(4086831600)] ) # Limit the maximum epoch to 2099 July 4th 7:00AM post_id = serializers.CharField(max_length=40) from = FromSerializer() parent_id = serializers.CharField() def validate(self, attrs): """ `from` is a python reserved word the add _ to distinguish it from them :param attrs: :return: """ from_ = attrs.get('from') pass def create(self, validated_data): pass def update(self, instance, validated_data): pass Question: What is your workaround when from(reserved word) is a key and that key is a python class property? -
Django: LDAP E-Mail Authentication
I am trying to authenticate against the e-mail adress of a ldap-user by creating a LDAPbackend class. This is my settings.py: AUTH_LDAP_SERVER_URI = "ldap://192.168.1.18" AUTH_LDAP_BIND_DN = "Test" AUTH_LDAP_BIND_PASSWORD = "Password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=ch", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=ipa-users,cn=users,DC=domain,DC=com", "is_staff": "CN=ipa-users,cn=users,DC=domain,DC=com", "is_superuser": "CN=ipa-users,cn=users,DC=domain,DC=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTH_LDAP_E_USER_SEARCH = LDAPSearch("dc=sbvg,dc=ch", ldap.SCOPE_ONELEVEL, "(mail=%(user)s)") AUTH_LDAP_E_USER_ATTR_MAP = AUTH_LDAP_USER_ATTR_MAP AUTH_LDAP_E_ALWAYS_UPDATE_USER = AUTH_LDAP_ALWAYS_UPDATE_USER AUTHENTICATION_BACKENDS = ( #'django_auth_ldap.backend.LDAPBackend', #'django.contrib.auth.backends.ModelBackend', 'accounts.backends.LDAPEmailBackend', ) And this is the backend (backends.py): class LDAPEmailBackend(LDAPBackend): settings_prefix = "AUTH_LDAP_E_" def get_or_create_user(self, email, ldap_user): """ Use the Posixuser uid field as username instead of form value (email). This must return a (User, created) 2-tuple for the given LDAP user. username is the Django-friendly username of the user. ldap_user.dn is the user's DN and ldap_user.attrs contains all of their LDAP attributes. """ model = self.get_user_model() username_field = getattr(model, 'USERNAME_FIELD', 'username') kwargs = { username_field + '__iexact': ldap_user.attrs['uid'][0], 'defaults': { username_field: ldap_user.attrs['uid'][0].lower(), 'email': email } } return model.objects.get_or_create(**kwargs) If I try to lofin with the right credentials this is the … -
Adding custom pages to django admin
I am developing a website with its back end powered by Django. I am very new to Django. What I need is to add custom pages (HTML,CSS, js) to Django admin panel so admin can make changes to models which will then be reflected onto the website say changing images or text on the website. I tried adding pages to Django admin urls but since the pages contains references to CSS and JS files so it does not work properly. How can i solve this problem? -
Django modeltranslation - can't get original values
I'm trying to use django-modeltranslation in my project. For now, just for Tag model with one field - name. I've created and registered TranslationOptions, then makemigrations and migrate. Now I can't access the original name text. It seems to be replaced with '' (empty string) but it isn't: In [6]: Tag.objects.first() Out[6]: <Tag: > In [7]: Tag.objects.first().name Out[7]: u'' In [8]: Tag.objects.first().__dict__ Out[8]: {'_state': <django.db.models.base.ModelState at 0x7fc96ad41710>, 'id': 1, 'name': u'Sport', 'name_cs': None, 'name_de': None, 'name_en': None, 'name_es': None, 'name_fr': None, 'name_ru': None, 'name_sk': None} In [9]: Tag.objects.first().name Out[9]: u'' Do you know how to access the field/s? -
What is the best way to time django query in shell?
I have sometimes to optimize my django queries and want to compare the speed of different queries in django shell. Of course, I can use django-debug-toolbar or smth similar, but I prefer to do it in shell. For now, I use %timeit in django shell_plus. But maybe there is a better way? -
ImportError: No module named 'project.app'
Getting this error whenever I use python manage.py test. It fails to import all of my apps. Here's an example: ImportError: No module named 'project.profiles' My project tree is: /project /project /profiles ... /bin /lib /include Any idea what the problem is? -
Create a post with content djangocms-blog
I would like to keep a series of articles creating new posts in an automated way. Creating a post is relatively easy: Post( title='Title', abstract='<p> Body </p>', app_config=BlogConfig.objects.all()[0] ....) But for the content is not the same as the abstract and to add content you have to create a placeholder, and add a text plugin, with a specific text. From the frontend it was very easy, but I would like to know if someone has experience doing it from the shell, to be able to automate it. -
Generate and download file with Django and Nginx
My problem is: I need to generate a csv file from the data I have in the database and then download it. Seems easy, but I cannot find a solution that will allow me to do it in the background so the user won't be redirected anywhere. What I need is user clicking a button and the download starting immediately with the user staying on the same page. Something like a simple html download attribute, but with actually generating a file first. I cannot generate file in advance as the data changes all the time and I need to output the most recent version of it, also, user may specify some filters for the data, so I need to take it into account. I use Django with Nginx as a production server. Django should always return a response, so I'm not sure I would be able to do what I want at all. Is there any different way to do it then? I've searched for a long time, but unable to find anything similar to my request. Thanks everyone! -
How model objects are sorted in Django
What is performed behind the scenes for the following code: sorted(MyModel.objects.all())? Is it __lt__? How is it defined? Thank you. -
OSError when trying to register in Django
I am trying to submit 2 forms at a time to create my student user in Django. I have been struggling for a while now, but I think I'm finally closing to an end on how to manage 2 forms at a time for my users to register. But when I fill in the data from my view, I get the error: [Errno 22] Invalid argument: "C:\\Users\\danny\\Desktop\\Projects\\bachelor_thesis\\eve\\templates\\{'form1': <UserForm bound=False, valid=Unknown, fields=(username;email;first_name;last_name;password)>, 'form2': <StudentForm bound=False, valid=Unknown, fields=(phone;student_ID;photo)>}" Here are my files: @csrf_protect def student_register(request): if request.method == 'POST': form1 = UserForm(request.POST, prefix="user") form2 = StudentForm(request.POST, prefix="profile") if form1.is_valid() and form2.is_valid(): # create initial entry for user username = form1.cleaned_data["username"] password = form1.cleaned_data["password"] new_user = User.objects.create_user(username, password) new_user.save() # create entry for UserProfile (extension of new_user object) profile = form2.save(commit=False) profile.user = new_user profile.save() return HttpResponseRedirect("index") else: form1 = UserForm(prefix="user") form2 = StudentForm(prefix="profile") c = { 'form1': form1, 'form2': form2, } c.update(request) return render(request, "student_signup_form.html", c) class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password') class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('phone', 'student_ID', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be … -
Django rest serializer create override no validated_data
I've 2 models, the WO_r is referenced by foreignkey from MyModel, now I need to create multiple MyModel from a POST request. class WO_rSerializer(serializers.ModelSerializer): """ the reference for new MyModel """ class Meta: model = WO_r fields = ('pk',) class MyModel_Serializer(serializers.ModelSerializer): """ should create many MyModel instances as WO_r data passed by POST """ wo_r = WO_rSerializer(many=True) def findit(self,wo_r): ovr = WO_r.objects.get(pk=wo_r['pk']) #r=self.data['wo_r'] new_ovt, created = MyModel.objects.get_or_create(wo_r=ovr) return new_ovt def create(self, validated_data): try: data = self.context['request'].data for x in data: x = json.loads(x) if x['wo_r']: print(x) for x in x['wo_r']: y=self.findit(x) except Exception as ex: raise serializers.ValidationError(ex) return y[0] class Meta: model = MyModel fields = ( 'id', 'wo_r', ) with these actually the MyModel objects are created but create result in: /.virtualenvs/backled3/lib/python3.5/site-packages/rest_framework/serializers.py", line 660, in to_representation self.child.to_representation(item) for item in iterable TypeError: 'WO_r' object is not iterable I don't get why data from POST is actually a queryset: <QueryDict: {'{"wo_r":[{"pk":"17635"},{"pk":"11332"}]}': ['']}> From shell I've tried : data = {'wo_r':[ {"pk": "17629"}, {"pk": "17630"},{"pk": "17631"} ]} x= MyModel_Serializer(data=data) x.is_valid() Out[4]: False x.data Out[13]: ReturnDict([('wo_r', [{'pk': '17629'}, {'pk': '17630'}, {'pk': '17631'}])]) ----> 1 x.create(data) /mnt/DB/dj/backled3/label_app/serializers.py in create(self, validated_data) 98 y=self.trova_ordine(x) 99 except Exception as ex: --> 100 raise serializers.ValidationError(ex) 101 102 … -
Django access form errors excluding non_field_errors in template
In a django template I'd like to show all form errors on top of the form, the easiest way is by doing so: {{ form.errors }} The problem is that this also shows the form.non_field_errors, these are the entries contained in form.errors['__all__']. I want to show these special errors separately, so I've tried to loop over the dict and check if the key existed: {% for err in form.errors %} {% if not err.__all__ %} {# print error #} {% endif %} {% endfor %} but apparently this is not possible because in the template we cannot access dictionary keys starting with underscore (doc). Question: is there a built-in way to access (and possibly print) the standard field errors and separately the non_field_errors? -
How can i attach pdfs and mp4s in .epub while creating it with python
I want to create a .epub with musics, videos, gifs, images while this all i want to work on all platforms like ibooks also one that i have made doesn't work videos on ibooks.please provide me a better solution -
Mysql GroupBy need it for HAVING brakes query
I have an SQL, and to use HAVING in need to GroupBy by that field. The problem is grouping by that field, brakes my query. How can I extract the comparison inside the HAVING and put it in the WHERE clause? SELECT `city`, `state`, `country_code`, `class`, Count(`id`) AS `count_ips` FROM `changemyip_ip` GROUP BY `city`, `state`, `country_code`, `class` `server_proxy_settings`.`max` HAVING `server_proxy_settings`.`max` > ( Count(DISTINCT CASE WHEN `order`.`service` = 2 THEN `user_product`.`id` ELSE NULL end) ) ORDER BY `count_ips` DESC -
Nesting django Q objects to filter relations
I am using Django 2.0 and am generating a rather complex filter from user input that I want to store in the database. Suppose I have the following models: class Car(models.Model): brand = models.CharField(...) doors = models.PositiveIntegerField(...) class Tire(models.Model): car = models.ForeignKey(Car, related_name="tires") radius = models.FloatField(...) color = models.CharField(...) I now would like to create filters both for Car and for Tire before evaluating or setting up any querysets, i.e., I only want the complete Q() object: my_filter = Q(brand__startswith='Volks') & Q(doors=4) my_tire_filter = Q(radius__range=(1.0, 2.0) & Q(color=black)) How can I now create another Q object for the Car model, giving me cars that fulfill my_filter and have tires fulfilling my_tire_filter? Something like my_car_filter = my_filter & Q(tires=my_tire_filter) the_cars = Car.objects.get(my_car_filter) I want to store these Q() objects serialized in the database, that's why I need the pure Q filter without any datasets. Is that possible? -
Testing in python a part of a class method
here's my problem. I'm new to python testing (testing in general) and i'm working with Python 3.x and Django 2.0. I have a class which has the goal of starting a synchronization between two DBs. It has a method for the synch, and this method is composed in different parts: Send an HTTP Request to the other server (it tries to send the request for a certain amount of attempts, then it stops); Check the result (response received or number attempts exceeded); Check the Response (Status code, format, response content (It's a JSON), ...) After that, it starts again doing this, while there's nothing to synchronize. Now, i need to test this different parts separately, but i don't know how because, as i said, this ops are all in the same method. I thought a solution would be separate this operation in different "sub" methods (only for testing purpose) or execute those parts of code in different tests. Is there a better solution? -
Combine two querysets
I have 2 querysets from 2 different models like this: qs1=[username, lastname, firstname] qs2=[username, email] I need to combine them to one and sorted by username. So it becomes like this: qs=[username, lastname, firstname, email] qs1 and qs2 are querysets with multiple entries. I have code in view.py like this: usernames = C.objects.values('username') for username in usernames: try: qs1=A.objects.filter(username=username).values('username','lastname',' 'firstname') qs2=B.objects.filter(username=username).values('username','email') How do I combine qs1 and qs2 to qs? -
Call Django on HTML button click
I'm trying to make a basic sort function for a Django project, but I don't know how to call the sort function when I click the 'sort' button Django view: def sort_btn(request): if request.GET.get('sort-btn'): cits = Citizen.objects.all().order_by('name') return render_to_response(request, 'civil_reg/index.html', {'cits': cits}) HTML button: <button name="sort-btn" id="sort-btn">sort</button> -
Returning Hex UUID as default value for Django model charfield
I tried to create a model with identifier generated from uuid4. But what I want instead of regular uuid, I want identifier has hex uuid format (without "-"). Here is what I tried: class Model(models.Model): identifier = models.CharField(max_length=32, primary_key=True, default=uuid.uuid4().hex, editable=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.identifier class Meta: abstract = True instead of returning unique id every time inherited class instantiated, it returns the same id because of uuid4(). I tried to change the default value from uuid.uuid4().hex to uuid.uuid4.hex but it seems the hex is not callable from uuid4 directly. So what is the possible way to produce default value for my identifier from uuid with hex format? -
I need an example for update_or_create using JsonField
I need an example using update_or_create for JsonField (I didn't found an example in docs) I found only for "normal" fields: Prod.objects.update_or_create(type=type_key, parent_id=parent_id, prod_id=prod_id, defaults={'ol': new_path}) So if a key exist, update the key if not create it. -
django apps : operational error
i make cart app for ecommerce site to handle users sessions this is the cart model it give me an error in the admin page when clicking on carts section from django.db import models from django.conf import settings from django.urls import reverse from products.models import product user=settings.AUTH_USER_MODEL class cart(models.Model): user = models.ForeignKey(user, null=True, blank=True) products = models.ManyToManyField(product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) def __unicode__(self): return str(self.id) -
How to upload a folder to django database through form
I want to upload a folder containing few files, and save those files to the database. I was successful in uploading a file, but facing problem while trying to upload a folder. The files does not get stored in the database. Can someone please tell me where am I going wrong. models.py class Document(models.Model): report_id = models.CharField(max_length=50, blank=False) description = models.CharField(max_length=255, blank=False) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) is_diagnoised = models.BooleanField(default=False) uploaded_by_doc = models.CharField(max_length=20, default="") downloaded_by_rad = models.CharField(max_length=20, default="") forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('report_id', 'description', ) views.py def index(request): if request.user.is_authenticated: uid = request.user.id usern = request.user.username if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): for afile in request.FILES.getlist('document'): new_file = Document(document = afile) post = form.save(commit=False) post.uploaded_by_doc = usern post.document = form.cleaned_data.get('new_file') post.save() return HttpResponseRedirect('index') else: form = DocumentForm() return render(request, 'upload.html', context) upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="file" name="document" multiple = "true" webkitdirectory="true" directory = "true"/> <button type="submit">Upload</button>