Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Django ArrayField from unicode
I have an array field in PostgreSQL (Table name is group): users TEXT [] I used a 3rd party tool to migrate my data in a read-only DB, and that has converted my array to unicode. Now, I want to use this array data in Django and was using Django's ArrayField for this. Is there any way, I can convert that unicode data to Array in the model class? My model is something like: class Groups(models.Model): id = models.TextField(primary_key=True) users = ArrayField(blank=True, null=True, base_field=models.TextField()) When I print the object's user field, I get this output: u'{pradeep.kumar}' -
Multiple Integer Arguments in Django Rest Framework Router URL
I'm setting up a url using Django Rest Framework viewsets and routers, and I'm trying to get the url to accept two values: first, to filter objects by a user id, and then by the object's id. (In my case, the objects are from a model called Request.) For example, mysite.com/api/requestsbyuser/1/ would return all Request objects for user 1, and mysite.com/api/requestsbyuser/1/23/ would return Request object with pk=23 for user 1. Right now I have: # urls.py from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(prefix=r'requestsbyuser/(?P<user_id>.+)', viewset=views.RequestsByUser, base_name='request') urlpatterns = [ url(r'^', include(router.urls)), ] # views.py class RequestsByUser(viewsets.ModelViewSet): serializer_class = RequestsSerializer def get_queryset(self): u_id = self.kwargs['user_id'] return Request.objects.filter(user_id=u_id) This works well for listing all Request objects when the url is passed in only the user_id. But when I try to go to mysite.com/api/requestsbyuser/1/23/, I get the error: invalid literal for int() with base 10: '1/23'. Django debugging says that the following four url patterns are in my URLConf: ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/$ [name='request-list'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)\.(?P<format>[a-z0-9]+)/?$ [name='request-list'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/(?P<pk>[^/.]+)/$ [name='request-detail'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='request-detail'] Am I missing something? I thought the DRF router would handle url paths with individual object primary key values, … -
data did'nt validate error django
Can anyone please help me..... I keep on getting "data didn't validate" error when saving data from a ModelForm. Everything worked fine for me until I added some CSS and JS for the frontend, used form widgets and manually displayed the form field on the template. Here are the codes: forms.py from django import forms from .models import List_of_Res class fordtp(forms.Form): month_choices=( ('JAN','January'), ('FEB','February'), ('MAR','March'), ('APR','April'), ('MAY','May'), ('JUN','June'), ('JUL','July'), ('AUG','August'), ('SEP','September'), ('NOV','November'), ('DEC','December'), ) day_choices=[] for ddd in range(1,32): day_toS=(str(ddd),str(ddd)) day_choices.append(day_toS) year_choices=[] for yyy in range(1990,2100): year_toS=(str(yyy),str(yyy)) year_choices.append(year_toS) month = forms.ChoiceField(choices = month_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) year = forms.ChoiceField(choices = year_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) day = forms.ChoiceField(choices = day_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) class ResearchForm(forms.ModelForm): class Meta: model = List_of_Res fields={ 'prog_title', 'proj_title', 'stud_title', 'prog_lead', 'stud_lead', 'co_res', 'res_site', 'campus', 'category_res', 'classif_res', 'amt_granted', 'date_started', 'res_status', 'date_completed', 'res_SF', 'res_pubstat', 'res_JN', 'res_JV', 'date_pub', 'res_iprstat', 'apptype', 'date_appl', 'date_pprv', 'app_pending', 'res_abs' } widgets = { 'prog_title': forms.TextInput(attrs={'class':'form-control'}), 'proj_title': forms.TextInput(attrs={'class':'form-control'}), 'stud_title': forms.TextInput(attrs={'class':'form-control'}), 'prog_lead': forms.TextInput(attrs={'class':'form-control'}), 'stud_lead': forms.TextInput(attrs={'class':'form-control'}), 'co_res': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter 1 name per line'}), 'res_site': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter 1 site per line'}), 'campus': forms.Select(attrs={'class':'form-control'}), 'category_res': forms.RadioSelect(attrs={'class':'form-check-input'}), 'classif_res': forms.Select(attrs={'class':'form-control'}), 'amt_granted': forms.TextInput(attrs={'class':'form-control'}), 'date_started': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_status': forms.RadioSelect(attrs={'class':'form-check-input'}), 'date_completed': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_SF': forms.CheckboxSelectMultiple(attrs={'class':'form-check-input'}), 'res_pubstat': forms.RadioSelect(attrs={'class':'form-check-input'}), 'res_JN': forms.TextInput(attrs={'class':'form-control'}), 'res_JV': forms.TextInput(attrs={'class':'form-control'}), 'date_pub': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_iprstat':forms.RadioSelect(attrs={'class':'form-check-input'}), 'apptype':forms.RadioSelect(attrs={'class':'form-check-input'}), 'date_appl':forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'date_pprv':forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'app_pending': forms.RadioSelect(attrs={'class':'form-check-input'}), 'res_abs': forms.Textarea(attrs={'class':'form-control'}) } (views.py): from … -
Combining multiple Regex
im looking to combine multiple regexes using a AND condition. For example, the following words should not be matched (starting of string): database audit index analysis extract good bad The strings that start with these strings will not be matched. Similarly, words such as others, error will be matched. I have done a regex that is able to filter for each word but has not been successful at filtering out the list of words to be not matched. #This will only match those that do not start with database r'(^((?!database).+)' While trying to combine, it has failed to check both conditions. r'(^((?!database).+)(^((?!audit).+)))' Note: This regex is to be used in the django framework, urls.py file -
Unable to connect to gunicorn via Ingress
I'm trying to deploy a Django application on Kubernetes. I'm using Gunicorn to serve the Django application. Gunicorn accepts connections when running at 0.0.0.0:8000, but not 127.0.0.1:8000. Can anyone help explain why? Kubernetes service.yaml ... spec: type: NodePort ports: - protocol: TCP port: 80 targetPort: 8000 ... Kubernetes deployment.yaml ... spec: containers: - name: app image: <img> livenessProbe: httpGet: path: /healthz port: 8000 initialDelaySeconds: 10 ports: - protocol: TCP containerPort: 8000 env: ... Dockerfile ... CMD python manage.py makemigrations && \ python manage.py migrate && \ gunicorn -w 3 app.wsgi:application Django app/settings.py ... DEBUG = True ALLOWED_HOSTS = [os.environ.get('ALLOWED_HOSTS')] ... Container startup logs No changes detected Operations to perform: Apply all migrations: <migrations 1..n> Running migrations: No migrations to apply. [2018-01-25 06:35:30 +0000] [9] [INFO] Starting gunicorn 19.7.1 [2018-01-25 06:35:30 +0000] [9] [INFO] Listening at: http://127.0.0.1:8000 (9) [2018-01-25 06:35:30 +0000] [9] [INFO] Using worker: sync [2018-01-25 06:35:30 +0000] [12] [INFO] Booting worker with pid: 12 [2018-01-25 06:35:30 +0000] [13] [INFO] Booting worker with pid: 13 [2018-01-25 06:35:30 +0000] [14] [INFO] Booting worker with pid: 14 Error message when going through an Ingress mapped to a domain name (eg. curl example.com) <html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>502 Server Error</title> </head> <body text=#000000 … -
Django Pagination "Page not found"
I'm currently having issues with my Django pagination. I have a query set of 9 objects and am paginating one object to a page. So I should have 9 pages total. Paginator is showing that I have 9 pages, but when I click the "next" page button my (Always on the last/last two pages) my url turns to: http://127.0.0.1:8000/forum/1?page=7 Then I get a 404 page not found error along with "Invalid page (7): That page contains no results" Here is my class code: class DirectoryClass(generic.ListView): template_name = "forum_directory.html" model = Directory paginate_by = 1 def get_context_data(self, **kwargs): context = super(DirectoryClass, self).get_context_data(**kwargs) directory = Directory.objects.filter(pk=self.kwargs['directory_id']) context['page'] = 'forum' context['name'] = directory.first().name context['user'] = self.request.user topic_set = directory.first().topic_set.all().order_by('-last_post') print(topic_set.all()) paginator = Paginator(topic_set, self.paginate_by) page = self.request.GET.get('page') try: topic_set = paginator.page(page) except PageNotAnInteger: topic_set = paginator.page(1) except EmptyPage: topic_set = paginator.page(paginator.num_pages) context['topics'] = topic_set context['page'] = page return context What am I doing wrong here? I'm completely lost. Thank you! -
Django model property with parameter
I've the following models in Django. class User(models.Model): name = models.CharField(max_length=50) ... ... @property def get_info(self, key=None): value = self.name if key else 'Hello World' return value But when I try to execute the code in Django shell, I'm getting the following error. n [4]: user = User.objects.get(id=1) n [5]: user.get_info(key='test_key') --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-f7b917070aee> in <module>() ----> 1 user.get_info(key='test_key') TypeError: _get_info() takes exactly 2 arguments (1 given) -
nginx+uwsgi+django emperor mode not working
I am doing multi-application nginx+uwsgi setup in django. I am following this documentation to set up emperor mode for my project. It works fine when I run "uwsgi --ini myproject_uwsgi.ini" but I am not able to deploy emperor mode following this documentation. I have researched many docs but not able to find relevant information related to emperor mode setup. My nginx.conf file:(angularJS frontend) server { listen 80; server_name 192.168.xx.xx; root /home/user/Myspace/workspace/Myproject_frontend/dist; } My "etc/uwsgi/vassals/uwsgi.ini" file looks like: [uwsgi] #Django-related settings #Django's wsgi file wsgi-file = /home/user/Myspace/workspace/myproject/myproject/wsgi.py http = 192.168.xx.xx:8080 virtualenv = /home/user/Myspace/VENV_MYPROD Also, i have created a uwsgi.service file in "/etc/systemd/system/uwsgi.service" to start emperor mode service and it looks like: [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals/ RuntimeDirectory= uwsgi Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target Please provide help on setting up uwsgi emperor mode. -
django-import-export specify id in order from ‘1’
Hi,When I import data from excel, I find the default id is random: ID NAME 5 A 9 B I want to like below when I import data "NAME: A, NAME: B" from excel : ID NAME 1 A 2 B How should I do?