Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: CSRF verification failed. Request aborted. Form submition
I'm getting "CSRF Failed: CSRF token missing or incorrect." error while doing a POST request to a django api from my localhost machine. Trying to submit some easy form. Have problem with csrf token: CSRF token missing or incorrect. Here are View: def loginview(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(username = username, password = password) if user: login(request, user) return render(request, "menu/index.html") else: return render(request, "menu/login.html") Here is the Template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="{% url 'login' %}" method="post"> {% csrf_token %} <input name="username" type="text"> <input name="password" type="password"> <button type="submit">Login</button> </form> </body> </html> Here are Urls: urlpatterns = [ path("", views.place_order, name = "confirm"), path("signup/", views.signup, name = "signup"), path("login/", views.loginview, name = "login"), ] Thank you for any help -
How to pass detailView pk to FormMixin in Django?
In my detailView I have a form and I want to display only data that related to current detailView in my form. So I use get_context_data to get current detailView pk and pass it to the form and then inside my form class I used kwargs.pop to get the pk the do some queryset. I can render it to template but I can't make post request so I decided to use FormMixin but the problem is I don't know to pass pk to the form and pop it inside my form class. here is the first approach I used and couldn't make the post request class Class_detailView(LoginRequiredMixin, DetailView): login_url = '/' model = Class template_name = "attendance/content/teacher/class_detail.html" # get pk of current detail view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['attendance_form'] = AttendanceForm(current_class_pk=self.object.pk) return context class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student',] def __init__(self, *args, **kwargs): current_class_pk = kwargs.pop('current_class_pk') super(AttendanceForm, self).__init__(*args, **kwargs) current_student = Class.objects.get(id=current_class_pk) self.fields['student'].queryset = current_student.student here is the second approach, with this approach I couldn't render it to template bcuz it gave me an error class Class_detailView(FormMixin, DetailView): model = Class form_class = AttendanceForm template_name = "attendance/content/teacher/class_detail.html" def get_success_url(self): return reverse('class_detail', kwargs={'pk': self.object.pk}) def … -
Django - ListView with form, How to redirect back to the Form page?
So, I have a ListView with exercices list (paginated 1 per page). In each page I have few input the user need to fill up. I managed to find a solution to how to attached the ListView with the Form but i cant find a solution on how to stay on the same page after the submit. url's: urlpatterns = [ path('programs/', ProgramListView.as_view(), name='web-programs'), path('programs/<int:pk>/', ExerciseListView.as_view(), name='program-detail'), path('data/', views.add_data, name='data-submit'), views.py: class ExerciseListView(LoginRequiredMixin,FormMixin, ListView): model = Exercise context_object_name = 'exercises' form_class = DataForm paginate_by = 1 def get_queryset(self): program_num = get_object_or_404(Program, pk=self.kwargs.get('pk')) return Exercise.objects.filter(program=program_num) def add_data(request): if request.method == "POST": form = DataForm(request.POST) if form.is_valid(): form.save() # Data.objects.create(address=form.cleaned_data['form']) return redirect(?) template.html: {% extends "program/base.html" %} {% load crispy_forms_tags %} {% block content %} <h3> Program Exercises List </h3> {% for exercise in exercises %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> {% if user.is_superuser %} <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'exercise-update' exercise.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'exercise-delete' exercise.id %}">Delete</a> <p class="article-content">{{ exercise.name }}</p> {% else %} <p class="article-content">{{ exercise.name }}</p> {% endif %} </div> <div class="article-metadata"> <p class="article-content">{{ exercise.description }}</p> <p class="article-content">{{ exercise.breath_method}}</p> <p class="article-content">{{ exercise.recovery_method }}</p> <p class="article-content">{{ exercise.measure_method }}</p> <p … -
Gunicorn --workers 3 --preload
We are running a django web application via Gunicorn + NGNIX (on a linux server). We find that the jobs we are executing via APScheduler are being executed 3 times each (which is undesirable). We solved the problem on our local computers, however, the problem remains when being run via Gunicorn. This was the most informative thread: Make sure only one worker launches the apscheduler event in a pyramid web app running multiple workers Our problem (which would sound simple for someone with more experience than we have) is that we want to execute the following code: env/bin/gunicorn module_containing_app:app -b 0.0.0.0:8080 --workers 3 --preload, we are unsure about two things: We have a domain "example.com", should we adjust the code to be env/bin/gunicorn module_containing_app:app -b example.com --workers 3 --preload or does it not matter? We are trying to find the env/bin/gunicorn folder/path with no luck. We are also trying to understand what to replace module_containing_app:app with. We understand that this could seem like a simple problem, but we have very little experience thus far with gunicorn. Any help would be appreciated as we want to understand. Thank you -
Change table column name after search query in Django
I looking for a way to create a table according to the search query. The column name in the table should change after the search. Example: Step_1: search query for all models Step_2: find the query and creates a table with the associated data and column name. Step_3: table is displayed on the web interface. THX for the help Amoel -
I am not able to get the box in which the user can write his comment and view it.How to solve this error in django?
The html page which i have writen and include this in a or loop so that it can appear below every post is given below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>comment</title> </head> <body> <form method="post"> {{ comment_form.as_p }} <input type="submit" value="Submit" class="btn btn-outline-success"> </form> <div class="main-comment-section"> {{ comments.count }}PostComment{{ comments|pluralize }} {% for comment in comments %} <blockquote class="blockquote"> <p class="mb-0">{{ comment.content }}</p> <footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user|capfirst}}</cite></footer> </blockquote> {% endfor %} </div> </body> </html> I am only getting submit button writen below my every post and neither the comment count nor the the box where user can write the comment. The forms.py of my code is given below: class PostCommentForm(forms.ModelForm): class Meta: model = PostComment fields = {'content',} The models.py of code is given below: class PostComment(models.Model): mypost= models.ForeignKey(MyPost,on_delete=CASCADE, null=True, blank=True) user=models.ForeignKey(User,on_delete=CASCADE, null=True, blank=True) # reply = models.ForeignKey('Comment',) content= models.TextField(max_length=100,null=True, blank=True) # timestamp= models.DateTimeField(auto_now_add=True) cr_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.mypost.subject, str(self.user.username)) the views.py of code is given below: def post_detail(req,pk): post = MyPost.objects.get(pk=pk) comments = PostComment.objects.filter(post=post).order_by('-pk') if req.method == 'POST': comment_form = PostCommentForm(req.POST or None) if comment_form.is_valid(): content = req.POST.get('content') comment=PostComment.objects.create(post=post,user=req.user,content=content) comment.save() return HttpResponseRedirect(post.get_absolute_url()) else: comment_form= PostCommentForm() context = { 'post' : post, 'comments' : … -
Object of type WSGIRequest is not JSON serializable
I am trying to send request to jira in order to create new jira issue. To do it asynchronously I'm using django-background-tasks. When I Create issue in application and I get this error message: TypeError at /tickets/ Object of type WSGIRequest is not JSON serializable Here is my views.py def create_ticket(request): if request.method == 'POST': ticket_form = TicketForm(request.POST) tags_form = TagsForm(request.POST) attachments = AttachmentForm(request.POST, request.FILES) owner = User.objects.get(username=request.user) if ticket_form.is_valid() and attachments.is_valid() and tags_form.is_valid(): create_jira_issue(request, ticket_form, tags_form, owner) return redirect('/') else: ticket_form = TicketForm() tags_form = TagsForm() attachments = AttachmentForm(request.POST, request.FILES) return render(request, "client_interface/ticketform.html", {'ticket_form': ticket_form, 'attachments': attachments, 'tags_form': tags_form}) And tasks.py (I use it for background tasks) @background def create_jira_issue(request, ticket_form, tags_form, owner): jira = JIRA(server=JIRA_URL, basic_auth=(jira_user, jira_password)) new_issue = add_issue(jira, ticket_form, owner) add_attachments(request, jira, new_issue) set_tags(new_issue, tags_form) Without background tasks there wasn't any error, but page was reloading for ages. Does anybody know how to solve this problem (Or find different way to send async requests) ? -
Ajax not working- No change in the data and page will renderd when submit
Trying to make a submission with out rendering the page, But it's not working and the page will rendered when clicking the submit button. How can i update the details form the following field? Template something like this {% for i in userlist %} <form method="POST" id="profileUpdate"> {% csrf_token %} <input class="email" type="email" value="{{i.email}}" id="email"> <input class="dob" id="dob" type="text" value="{{i.date_of_birth}}" > <button type="submit" class="btn btn-primary">Save changes</button> </form> {% endfor %} Ajax script <script> $(document).on('submit', '#profileUpdate', function (e) { $.ajax({ type: 'POST', url: '{% url "profileUpdate" %}', data: { email: $('#email').val(), dob: $('#dob').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { alert("Success"); }, }); }); </script> views.py def profileUpdate(request): response_data = {} if request.get('action') == 'post': email=request.POST.get('email') dob=request.POST.get('dob') response_data['dob'] = dob ob=Employee.object.get(email=email) ob.date_of_birth= dob ob.save() return HttpResponse('') urls.py urlpatterns = [ path('registeredusers', registeredusers.as_view(), name="registeredusers"), path('profileUpdate', views.profileUpdate, name='profileUpdate'), ] -
django-heroku is not installing
Collecting django-heroku Using cached django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) Requirement already satisfied: django in /home/aksh/dadu/lib/python3.8/site-packages (from django-heroku) (3.1.1) Requirement already satisfied: whitenoise in /home/aksh/dadu/lib/python3.8/site-packages (from django-heroku) (5.2.0) Requirement already satisfied: dj-database-url>=0.5.0 in /home/aksh/dadu/lib/python3.8/site-packages (from django-heroku) (0.5.0) Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) Requirement already satisfied: asgiref~=3.2.10 in /home/aksh/dadu/lib/python3.8/site-packages (from django->django-heroku) (3.2.10) Requirement already satisfied: sqlparse>=0.2.2 in /home/aksh/dadu/lib/python3.8/site-packages (from django->django-heroku) (0.3.1) Requirement already satisfied: pytz in /home/aksh/dadu/lib/python3.8/site-packages (from django->django-heroku) (2020.1) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/aksh/dadu/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-a2qiah3p/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-a2qiah3p/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-xvu3w4ef cwd: /tmp/pip-install-a2qiah3p/psycopg2/ Complete output (6 lines): usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- ERROR: Failed building wheel for psycopg2 Running setup.py clean for psycopg2 Failed to build psycopg2 Installing collected packages: psycopg2, django-heroku Running setup.py install for psycopg2 ... error ERROR: Command errored out with exit status 1: command: /home/aksh/dadu/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-a2qiah3p/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-a2qiah3p/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-7sdx4nwd/install-record.txt --single-version-externally-managed --compile --install-headers /home/aksh/dadu/include/site/python3.8/psycopg2 … -
how to export current/ particular searched/sorted/filtered into excel in django?
i created a Django table applied necessary filter now i want to export the table following is my code- def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="alist.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('A') # this will make a sheet named Users Data # Sheet header, first row row_num = 3 font_style = xlwt.XFStyle() font_style.font.bold = True columns=['__all__'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() x=A.aid str(x) rows = A.objects.filter(user=request.user,).values_list() for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response i am facing a few issues - i am unable to download because its giving error- Unexpected data type <class 'uuid.UUID'> this is happening because my id field is- id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) then i tried creating x as string or exclude the id but rows = A.objects.filter(user=request.user,).exclude('id').values_list() but it showed many attributes lets say i have 10 rows in my table- i filtered and got 6 rows can i download as excel only those 6 rows or whatever is appearing on my screen. shall i alter or use the same code kindly help ! -
pass variable from ajax to external javascript from within django template
As i have a long (~20") job when users press submit, I manage to show the a loading gif while the process is running in the background as follow: within the django HTML template I put this piece of code: <script type="text/javascript"> $.ajax({ url: "{% url 'execute_request' %}", type: 'GET', data:{{data|safe}}, dataType: 'json', success: function(data){ var data1 = data.data1; var data2 = data.data2; $('.loading').hide();//hide the loading gif $('#showResult').show();//show the div with the result }, error: function(xhr){ alert(xhr.responseText); } }); </script> the ajax call to the view function within the view.py work perfectly and I got the data generated. this data needs to be passed to an external javascript file where it will generate svg graphs shown in the div mentioned above with id "showResult". I call the javascript as follow from the same html template: <script src="{% static 'resources/js/visualize_data.js' %}"></script> how can i pass the two variable data1 and data2 to the javascript visualize_data.js? Thanks you for your help -
Two 'POST' in Django REST framework, one HTTP 401
I have thwo POST in my Django Rest App: addRestaurant() { this.storeState.pictures = [] let endpoint = `/api/restaurant/`; let method = "POST"; let config = { maps: this.$route.params.maps, adress: this.$route.params.adress, name: this.$route.params.name }; apiService(endpoint, method, config) .then(data => { console.log("Restaurant added!" + data); this.addReview(); }) .catch(err => console.log(err)); }, addReview() { let endpoint = `/api/restaurant_review/`; let method = "POST"; let config = { maps: this.$route.params.maps, review_author: 1 } apiService(endpoint, method, config) .then(res => { this.review_id = res.id; }); }, So after addRestaurant() is done, addReview() is triggered. My issue is that the first API call is successful but I get an error for the second one like "Authentication information were not provided". I've changed my authentication to token authentication and since I've implemented this, I have this issue. Here is the apiService I use: let token = window.localStorage.getItem("user-token") function apiService(endpoint, method, data) { const config = { method: method || "GET", body: data !== undefined ? JSON.stringify(data) : null, headers: { 'content-type': 'application/json', 'X-CSRFTOKEN': token, }, } return fetch(endpoint, config) .then(handleResponse) .catch(error => console.log(error)) } export { apiService }; I know it's working because I use it in other functions that are working perfectly fine. Here is a screenshot of … -
Django annotate and aggregate with division
I have the following code: result = Training.current\ .annotate(per_training=ExpressionWrapper((Count('trainingregistration') / F('capacity')) * 100, output_field=FloatField()))\ .aggregate(Avg('per_training')) result = round(result['per_training__avg'], 2) print(f'Average occupancy per training: {result}') I have verified that the current model manager works on other aggregations. I want to calculate the average capacity per training by dividing the number of registrations (which have a ForeignKey to Training) by the training capacity, but this value always comes out to 0.00 and thus gets averaged to 0.00. What am I doing wrong here? -
Not able to send email overriding create method django rest framework
I got to know that we can override create method in order to send email but it's not working with my code. views.py: class FileUploadView(APIView): parser_class = (MultiPartParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) def create(self, request, *args, **kwargs): response = super(FileUploadView, self).create(request, *args, **kwargs) send_email() # sending mail return response def send_email(request): email = EmailMessage( 'Title', (FileSerializer.Fullname, FileSerializer.Email, FileSerializer.Contact), 'mymail@gmail.com', ['anothermail@gmail.com'] ) email.attach_file(FileSerializer.Upload) email.send() Help me in figuring out what's the problem here -
Unable to affect other objects in ListView aside from the first one, in Django
I am trying to create an upvote system in my Django site using ajax so it would not refresh when users click the upvote button. In my site's main page with the listview of all the posts, I am able to get the ajax and the upvote request to work, but only for the top post. No matter if I click on an upvote button from another post, it would only register the effect on the top post. Where did I go wrong? Below is my code. models.py User = settings.AUTH_USER_MODEL #this is the user model class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) #many to one relationship where many posts can be tied to one user content = models.TextField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='trade_images', blank=True, null=True) upvotes = models.ManyToManyField(User, blank=True, related_name='upvotes') total_upvotes = models.IntegerField(default='0') def get_absolute_url(self): return reverse('main:post-detail', kwargs={'pk': self.pk}) #returns the url for individual posts def __str__(self): return self.content class Upvote(models.Model): user = models.ForeignKey(User, related_name='upvoted_user', on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='upvoted_post', on_delete=models.CASCADE) def __str__(self): return str(self.user) + ':' + str(self.post) views.py # list of all posts class post_list_view(ListView): model = Post template_name = 'main/home.html' context_object_name = 'posts' # this is called from the html as 'for post in posts' … -
Django - 404 page handler template cannot load css when settings.DEBUG is set to False
I created a 404 page handler template and I want to add styles to it, but when I try to load the css file when settings.Debug is False, it logs this to the chrome console: Refused to apply style from 'http://localhost:8000/static/errors/404.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. But when settings.Debug is True, it loads the css file without logging any errors 🤔 Setup: If debug is set to true, the errors/404 route will display the 404 page. If debug is set to false, django will use the errors.handlers.handle404 handler to handle 404 errors. I'm telling django to use the handler in this file. I did this because django does not display the 404 page when debug is set to True, it loads the debug page with information on why the error happened Project folder: errors = Name of the app root = Name of the project Working Directory -- root ---- manage.py ---- root --------- __init__.py --------- asgi.py --------- settings.py --------- urls.py --------- wsgi.py ---- errors --------- migrations -------------- __init__.py --------- static -------------- errors ------------------- 404.css --------- templates -------------- errors ------------------- 404.html --------- __init__.py --------- apps.py --------- handlers.py … -
How to get the Foreign Key set on the URL and use it on django CreateView
Thanks for your time... If someone can help me to get the foreign key that shows on the URL and use it on Django CreateView. I am trying to create a simple app to organize legislation. For this, I have this relation on my database: Categoria has many Series and Series has many posts. I have made the one path of urls.py like this (...) path('nova-serie/<categoria>', NovaSerie.as_view(), name='nova_serie'), (...) I just want to pass get the value from the URL and save as the foreign key without the user have to type it again. view.py class NovaCategoria(CreateView): model = Categoria form_class = CategoriaForm template_name = 'nova_categoria.html' success_url = reverse_lazy('home') class NovaSerie(CreateView): model = Serie form_class = SerieForm template_name = 'nova_serie.html' success_url = reverse_lazy('home') models.py class Categoria(models.Model): categoria = models.CharField( max_length=200, verbose_name="Nome da categoria", help_text="colocar aqui o texto de ajuda") class Meta: verbose_name_plural = "Categorias" verbose_name = "categoria" def __str__(self): return self.categoria class Serie(models.Model): serie = models.CharField( max_length=200, verbose_name="Série", help_text="colocar aqui o texto de ajuda") categoria = models.ForeignKey(Categoria, default=1, on_delete=models.SET_DEFAULT) class Meta: verbose_name_plural = "serie" def __str__(self): return self.serie forms.py class SerieForm(forms.ModelForm): class Meta: model = Serie fields = ( 'serie', 'categoria', ) widgets = { 'title': forms.TextInput(), # attrs={class="title"} 'categoria': … -
React Js expression expected ts(1109)?
So basically I'm new to react js and im following a tutorial and i keep getting this error of "Expression expected. ts(1109)". Here is my code import React from 'react'; import { Layout, Menu, Breadcrumb } from 'antd'; const { Header, Content, Footer } = Layout; const CustomLayout = (props) => { return( <Layout className="layout"> <Header> <div className="logo" /> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']}> <Menu.Item key="1">nav 1</Menu.Item> <Menu.Item key="2">nav 2</Menu.Item> <Menu.Item key="3">nav 3</Menu.Item> </Menu> </Header> <Content style={{ padding: '0 50px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item>List</Breadcrumb.Item> <Breadcrumb.Item>App</Breadcrumb.Item> </Breadcrumb> <div className="site-layout-content"> {props.children} </div> </Content> <Footer style={{ textAlign: 'center' }}> Ant Design ©2018 Created by Ant UED </Footer> </Layout>, mountNode, ); (error occurs here on the ");" ) } export default CustomLayout; How can i fix this its been happening every time. I'm working in vs code if that helps but the same error occurred in Sublime text as well -
Changing language name and code Django LANGUAGES
I have overrode the LANGUAGES list in my settings.py as follows: LANGUAGES = [ ('en-us', _('American English')), ('en-gb', _('British English')), ] However, when I render the language switcher I found in Django's documentation (scroll down a little to see it at https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#the-set-language-redirect-view) the options of its select menu still are: English (en) British English (en-gb) Why is en-us being substituted with en, and American English being substituted with English? In the form in the link above the option tag for the select menu is as follows: <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> Should I change language.name_local and language.code to something different? -
Django ORM - MAx subqueryin filter
I am using postgres in combination with a django orm. Models: class Review(models.Model): STATUS_PENDING = 1 STATUS_DECLINED = 2 STATUS_CONFIRMED = 3 STATUS_CHOICES = ( (STATUS_PENDING, 'pending'), (STATUS_ACCEPTED, 'accepted'), (STATUS_DECLINED, 'declined'), ) doc = models.ForeignKey(Document, null=False, related_name="documents", on_delete=models.CASCADE) note = models.CharField(max_length=255, blank=True, null=True) status = models.PositiveSmallIntegerField(default=STATUS_PENDING, choices=STATUS_CHOICES) revision = models.PositiveIntegerField(default=1) class Document(models.Model): name = models.CharField(max_length=255, blank=False, null=False) # ... Sample Data, Document Table ID, Name 1, Doc1 2, Doc2 Review Table ID, document_id, status, revision, note 1, 1, 1, 1, null 2, 1, 1, 2, null 3, 1, 2, 3, "hello" 4, 2, 2, 1, "world" I want to write ORM query which will return review with max revision where note is not null. Raw sql query looks like this: select rs.* from reviews rs where rs.note is not null AND rs.revision = (select max(revision) FROM reviews where document_id = rs.id) I am not sure how to write similar query with django ORM. -
Apache + Python3.5 env + lxml + Interpreter Error
I'm using python3-saml library. With an Installation with APACHE + UWSGI + MYSOFTWARE it works fine. In an Installation with APACHE + WSGI + MYSOFTWARE I got this error: File ".../onelogin/saml2/auth.py", line 15, in <module> from defusedxml.lxml import tostring File ".../lib/python3.5/site-packages/defusedxml/lxml.py", line 15, in <module> from lxml import etree as _etree ImportError: Interpreter change detected - this module can only be loaded into one interpreter per process. Apache configuration is pretty standard: <Directory /usr/local/my-env/mysoftware> Require all granted </Directory> WSGIScriptAlias /mysoftware /usr/local/my-env/mysoftware/conf/wsgi.py process-group=mysoftware-wsgi-daemon WSGIScriptAlias / /usr/local/my-env/mysoftware/conf/wsgi.py process-group=mysoftware-wsgi-daemon WSGIDaemonProcess mysoftware-wsgi-daemon processes=2 threads=15 display-name=mysoftware-wsgi python-path=/usr/local/my-env/mysoftware:/usr/local/my-env/lib/python3.5/site-packages WSGIProcessGroup mysoftware-wsgi-daemon Thanks you for any advice -
How to make tinyMCE output text responsive
I am using a Django back-end, with a tinyMCE editor in the admin panel, where I can make edits that are displayed on the front page. My problem is that outputted text is not responsive, and even if it is readable on Desktop, it is to small on mobile, and I cannot make it readable on mobile unless I make it to large or Desktop. I was wondering if there is a way to eider make the output text responsive, either through settings, template language, or with javascript, or if it is possible to add a separate font size for smaller screens? my tinyMCE setting: TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | … -
502 Error while downloading a huge zip file containing multiple images in it
So,I want the user to be able to click a button and download a zip file containing a bunch of images. A view gets called upon clicking the button, which fetches the images from an SFTP server using pysftp module and creates a zip file and sends a response to the user for download. Now this thing works absolutely fine in most of the cases but in some cases the server throws a 502 proxy error which is because the images are either large in size (This is a hunch) or in number. I assume this is a timeout kinda thing where its taking a lot of time for view to process things. It would be really helpful if anyone could suggest a solution for this. I dont want "502 proxy error" to come in any case. def download_images(request): if request.GET.get('profile_id') and request.GET.get('mattersheet_id'): profile_id = request.GET.get('profile_id') mattersheet_id = request.GET.get('mattersheet_id') cnopts = pysftp.CnOpts() cnopts.hostkeys = None sftp = pysftp.Connection(host=Conf.IMG_SERV_IP, username='blabla',cnopts=cnopts) file_dir = f'''{Conf.DIR_CATALOG_PRODUCT_PATH}/{profile_id}/{mattersheet_id}/products/''' # import pdb; pdb.set_trace() response = HttpResponse(content_type="application/force-download") zip_file = ZipFile(response, 'w') products = products = MatterSheetProducts.objects.filter(matter_sheet_id=mattersheet_id).values('product_code','product_name','product_id','product_category_name').distinct('product_category_name','product_name') import time a = time.time() for product in products: try: if sftp.exists(f"{file_dir}{product.get('product_id')}.jpg"): fh = sftp.open(f"{file_dir}{product.get('product_id')}.jpg",'rb') category_name = product.get('product_category_name') if product.get('product_category_name') else '' … -
How to launch a script based on date/time field
I have set up MariaDB for the backend database for Ptyhon Django project. As it is in the initial POC stage, I will change the database also if you suggest anything. There is a table where the user data will be stored for all the entries the users create. And the table contains a data/time field. I want to trigger email when the date/time field value is equal to current time. Like, if the record1 is having value of tomorrow's 12:31 PM then immediately the email should be triggered to the email ID of the user. The email sending part we can take care but how to trigger the event when the datetime field value is equal to the current date/time. One option is to continuously run a background job to check the date/time value but that is not feasible as 1000s of records will be there. Please suggest, I am a newbie to the Python web projects. -
Django reading json and fetching data to bulk create with optimized approach and minimum resources
Basically i was wondering if i could somehow use a single for loop to achieve a task I am new to python and i am learning about the efficient ways to achieve stuff This is the current scenario json = { items: [ {'uuid': 'some uuid', 'quantity': 2}, {'uuid': 'some uuid', 'quantity': 3}, {'uuid': 'some uuid', 'quantity': 4}] } I am receiving this json and have to make a query to fetch each of these items based on the provided uuid. After fetching these items i have to create their entry in another model which is related to this model. My approach is to separate the uuids and quantity into two separate lists through a for loop for item in json: item_uuids.append(item['uuid']) item_quantities.append(item['quantity']) Fetch item objects q = Q() [q.add(Q(uuid=uuid), Q.OR) for uuid in item_uuids] items = model.objects.filter(q) Then do a list comprehension item_objs = [] [item_objs.append(model(uuid=uuid, quantity=quantity)) for uuid, quantity in zip(items, item_quantities)] Then after all of this I make the final query model.objects.bulk_create(items) Is there any efficient way to achieve this, as it constantly disturbs me i might be following the wrong approach here. Any help would be really appreciated. Thanks in advance