Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure Django Email Back-end Settings to send email via RoundCube Webmail in production
During development, I have been using Gmail SMTP to send emails from my Django app. The Gmail settings are (settings.py): EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxxxxx' However, during production, I need to change to RoundCube webmail client to allow my project to use a custom email address that matches the domain name. I have tried the following settings and many others but none of them is working. I know this is simple, but this is my first project and I don't know whether there is something I am missing. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mydomain.com' EMAIL_USE_TLS = True EMAIL_PORT = 465 EMAIL_HOST_USER = 'accounts@mydomain.com' EMAIL_HOST_PASSWORD = 'xxxxxxxxx' -
Wagtail search backend with Postgres - using unaccent with English search config
I'm not sure if this is a fault with Wagtail's search engine, or if I'm missing a setting/configuration step along the line. I'm working with a couple of European sites where they work in English as a common language but there are plenty of people and place names in the content with extended latin characters. On the db server, I added the unaccent extension and created a new search config based on the built-in english with unaccent added (using the example from postgres): CREATE TEXT SEARCH CONFIGURATION english_extended ( COPY = english ); ALTER TEXT SEARCH CONFIGURATION english_extended ALTER MAPPING FOR hword, hword_part, word WITH unaccent, english_stem; And backends: WAGTAILSEARCH_BACKENDS = { 'default': { 'BACKEND': 'wagtail.search.backends.database', 'SEARCH_CONFIG': 'english_extended', }, 'es': { 'BACKEND': 'wagtail.search.backends.database', 'SEARCH_CONFIG': 'spanish', }, } I have a page title with the word Bodø. To test, I tried a default search from the psql command line: # select title from wagtailcore_page where to_tsvector(title) @@ to_tsquery('Bodo'); title ------- (0 rows) No results, as expected. Then again using the new search config: # select title from wagtailcore_page where to_tsvector('english_extended', title) @@ to_tsquery('Bodo'); title ---------------------------------------------------- The old dock at Kjerringøy, Bodø, Nordland, Norway (1 row) Page now found, so the unaccent … -
How can I filter by a polymorphic attribute for an attribute only existing in one class?
I'm uncertain how to phrase this question better, so please let me show an example: I use Django-polymorphic and have this structure: from polymorphic.models import PolymorphicModel from django.db import models class Book(PolymorphicModel): author = models.OneToOneField( "Author", on_delete=models.PROTECT, null=True, blank=True, ) class Author(models.Model): name = models.CharField(max_length=20, blank=True) class AnonymousAuthor(Author): known_as = models.CharField(max_length=20, blank=True) I want to filter for all books by the anonymous author known as "foobar". I tried: Book.objects.filter(author__known_as="foobar").all() but I get: Cannot resolve keyword 'known_as' into field. Choices are: name. I can filter for books by anonymous authors like this: aa_ctype = ContentType.objects.get_for_model(AnonymousAuthor) Book.objects.filter(author__polymorphic_ctype=aa_ctype) But even with that I cannot filter for books with that name. How can I filter for all Books by the anonymous author `"foobar"? It is necessary to do the filtering with Django ORM. In my actual example I need to do this for django-filters. -
Django-Admin : Override add-URL of the Foreign Key Auto-Complete "add" button / + green cross
Is there a simple way of overriding/pass a parameter to the popup url automatically created by django-admin built-in autocomplete/select2 widget to create a new foreign key object? This url is embedded in the green cross (see picture). I didn't come across any well described solutions. So the default url is pointing towards admin/app/model/add/?_to_field=id&_popup=1 but I would like to add a parameter admin/app/model/add/?_to_field=id&_popup=1&field_1=100 in order to pre-populate some fieds on the popup add_view. Any leads? -
Docker-compose + Django + Postgresql
I'm not able to get the data I fill in my models to go to my database. When I do the migrations, the project works on the web, but when I view it inside the postgres database, nothing appears. I made my docker-compose in a way that it does the migrations itself, however, still nothing happens. docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_ENGINE=${POSTGRES_ENGINE} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_HOST=${POSTGRES_HOST} - POSTGRES_PORT=${POSTGRES_PORT} web: build: . command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_ENGINE=${POSTGRES_ENGINE} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_HOST=${POSTGRES_HOST} - POSTGRES_PORT=${POSTGRES_PORT} depends_on: - db I've tried everything, I've looked in several places, but nothing makes my migrations go to my database. Can someone help me? Dockerfile FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . settings.py DATABASES = { 'default': { 'ENGINE': os.environ.get('POSTGRES_ENGINE'), 'NAME': os.environ.get('POSTGRES_DB'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': os.environ.get('POSTGRES_HOST'), 'PORT': os.environ.get('POSTGRES_PORT'), } } -
How to save the user form with ManyToMany relationship
I am a beginner in django and trying to create a web application. I am trying to save the user form, but I have the problem that it does not save in the database the ManyToMany relationship of groups in the user_user_groups table My model class User(AbstractUser): state = models.BooleanField(default=True) def __str__ (self): return '{}'.format(self.username,self.state,self.groups) My form from django.contrib.auth.models import Group class UserForm(UserCreationForm): username = forms.CharField(label="User",widget=forms.TextInput(attrs= {"class":"form-control"})) state = forms.CheckboxInput() groups = forms.ModelMultipleChoiceField(queryset=Group.objects.all(), widget=forms.CheckboxSelectMultiple,required=True) password1 = forms.PasswordInput() password2 = forms.PasswordInput() class Meta: model = User fields = [ "username", "password1", "password2", "state", "groups" ] My view def create_user(request): if request.method == 'POST': form = UserForm(request.POST) form.fields['username'].help_text = None form.fields['password1'].help_text = None form.fields['password2'].help_text = None if form.is_valid(): form.save() return redirect('/') return render(request, 'user/user_form.html',{'form': form}) else: form = UserForm() return render(request, 'user/user_form.html',{'form': form}) -
Display scraping data on html table page
I'm working on a scraping project using selenium, after the scraping is finished, the data is inserted into a database and then an html page display which contain a table with all the product from the database. The problem is that process take so much time because of the scraping. Is there a way the html page will be displayed before the scraping code is finished and show just the data that inserted in the database so far, and while refreshing the page the other data will be displayed too. I hope my issue is clear, any help is highly appreciated. this is my code which helps me to execute the different codes : def datatable_view(request): if request.method =='POST': form = Scraping(request.POST) if form.is_valid(): subject=form.cleaned_data['subject'] #run python code of scraping scrap(subject) #add the products scraped to the database client = pymongo.MongoClient("mongodb://localhost:27017/") # use variable names for db and collection reference db= client["db2"] col = db[subject] products = col.find() context = {'products' : products} #open datatable html and display all the data from database return render(request,'datatable.html', context) return -
Field 'customer_id' expected a number but got <Customer: Lary>
I have these two models with their serializers: class ChronicPrescription chronic_prescription_id = models.AutoField(primary_key=True) date = models.DateField(default=datetime.date.today, validators=[no_future_date, no_old_date]) # This field is for the prescription duration in days duration = models.PositiveIntegerField(default=90, validators=[MaxValueValidator(90), MinValueValidator(30)]) customer = models.ForeignKey('customers.Customer', on_delete=models.CASCADE, related_name="chronic_prescription", validators=[prescriptions_for_patient_only]) class Customer(models.Model): id = models.BigAutoField(primary_key=True) customer_name = models.CharField(max_length=100, null=False, blank=False, unique=True) phones = ArrayField(models.CharField(max_length=10, validators=[validate_phone_number, prevent_replicated_phone]), default=list, null=True, blank=True) customer_type = models.CharField(max_length=10,default='patient', choices=CUSTOMER_TYPE) The problem is when i try to create a prescription serializer during a unit test (the test suppose to fail due to duration, it should not exceed 90) during a unit test: def test_upper_bound_duration(self): customer = Customer.objects.create(customer_name="Lary") prescr_serializer = ChronicPrescriptionSerializer(data={'duration': 1000, 'customer': customer.id}) if prescr_serializer.is_valid(): prescr_serializer.save() self.assertFalse(prescr_serializer.is_valid()) self.assertEqual(set(prescr_serializer.errors), set(['duration'])) I got an unexpected error: Field 'id' expected a number but got <Customer: Lary>. Even i'm providing the customer id not the customer itself, What is weird though, it were all god, but suddenly it doesn't work anymore. -
Listview must return only the courses that student have puchased in django
My models User class User(AbstractUser): is_student = models.BooleanField(default=False) .... purchased = models.ManyToManyField(Course, blank=True) Course class Course(models.Model): title = models.CharField(max_length=1000) ..... price = models.FloatField() My Views class StudentPurchasedcourse(ListView): model = Course template_name = 'tutspack/purchasedcourse.html' context_object_name = 'course' def get_queryset(self): queruset = Course.objects.filter(pk=self.request.user.purchased.all()).order_by('title') return queruset My Urls.py path('purchased_course/', views.StudentPurchasedcourse.as_view(), name='purchased-course'), I want to return all the courses That student have purchased on the studentViewpage. It would be helpful If anyone knows the answer. -
How to fill dropdown on Django from database?
I am trying to fill up a dropdown on a form and the data is from database forms.py // ERROR: unsupported operand type(s) for +=: 'ModelChoiceIterator' and 'tuple' for x in MyModel.objects.values_list( 'id', 'name', named=True): self.fields['mymodel'].widget.choices += ((x.id, '%s - %s' % (x.id, x.name)),) // I've tried, but it doesnt work for x in MyModel.objects.all(): self.fields['mymodel'].widget.choices += ((x.id, '%s - %s' % (x.id, x.name)),) What am I doing wrong? Thank you -
Dynamic URL Routing Django
I Created a dynamic url routing/views for each one of the product on my website, Everything is working fine until I go to Cart/checkout and it loads on of the product page currently in Cart instead of Cart.html and Checkout.html urlpatterns = { path('<str:pk>/', views.dynamic_product_view, name='productdetail'), } views.py: def dynamic_product_view(request, pk=None): products = Product.objects.all() slug=None data = cartData(request) items = data['items'] if pk is not None: try: slug = Product.objects.get(slug=pk) except: Http404() context = { 'slug':slug, 'products': products, 'items': items } return render(request, 'product-details.html', context) It's currently working fine on any other Page like index, store and Products page but the problem appear in Cart and Checkout -
Javascript Django like button doesn't update counter
I have created Put request to update like count, but when I press like button count doesn't change unless I refresh page. and like/unlike function works fine. Can somebody help me resolve this issue? view.py Here is how i have done put request. class PostLikeView(APIView): authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated] def get(self, request, post_id, slug=None, format=None): post = Post.objects.get(pk=post_id) serializer = PostSerializer(post, many=False, ) return JsonResponse(serializer.data, safe=False) def put(self, request, post_id, slug=None, format=None): post = Post.objects.get(pk=post_id) user = self.request.user # if user.is_authenticated(): if user in post.likes.all(): post.likes.remove(user.id) else: post.likes.add(user.id) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False) In javascript at like_button.addEventListener i calling function like post where i pass post_id this function works except counter doesnt change unless i refresh page, can I edit so counter update without refreshing if not how to setup automatically to refresh after put request complete? index.js function post_list(post) { const postdiv = document.createElement('div') postdiv.setAttribute('id','post-div') const userdiv = document.createElement('div') userdiv.setAttribute('id', 'username-div') const bodydiv = document.createElement('div') bodydiv.setAttribute('id', 'body-div') const datediv = document.createElement('div') datediv.setAttribute('id', 'date-div') const datep = document.createElement('p') datep.setAttribute('id', 'date-paragraph') const userp = document.createElement('p') userp.setAttribute('id', 'username-paragraph') const bodyp = document.createElement('p') bodyp.setAttribute('id', 'body-paragraph') // LIKE const likesdiv = document.createElement('div') likesdiv.setAttribute('id', 'likes-div') let likesp = … -
Multipart form parse error - Invalid boundary in multipart: None'. Django Rest Framework [closed]
Всем привет. Не получается отправить данные вместе с файлом изображения через клиент запрос fetch на сервер DRF. Вот метод VUE при отправке формы: async createTodo(){ const formData = new FormData formData.append('title', this.titleValue) formData.append('description', this.descriptionValue) formData.append('image', this.imageValue[0]) formData.append('urgent', this.urgentValue) const response = await fetch('http://localhost:4000/api/v1/todo-list/', { method: 'POST', headers: { "Content-Type": "multipart/form-data", }, body: formData, }) const newTodo = await response.json() } В переменной newTodo я получаю следующий результат: {detail: 'Multipart form parse error - Invalid boundary in multipart: None'} Код view django: from rest_framework import generics from .serializers import TodoSerializer from .models import Todo from rest_framework.parsers import MultiPartParser, FormParser class TodoAPIList(generics.ListCreateAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer parser_classes = (FormParser, MultiPartParser, ) Я так понимаю нужно дописывать функционал в django, или я просто не правильно отправляю запрос на стороне сервера? -
How can I create fixtures that references a few foreign instances with pytest and factory-boy?
I have the function that calculate the sales of each companies in month, then I want to test this function. so I want to create some Sales fixtures of a few companies for the test. like: create 2 or 3 companies fixtures create many sales fixtures for these companies use created sales fixtures for my aggregation function test How can I do this? Do some methods exist for this like FuzzyXXX? I defined factories like below, but it generates sequential company ids. def aggregate_companies_sales_in_month(): result = ( Sales.objects.all() .annotate(year=TrunkYear('sold_at'), month=TrunkMonth('sold_at')) .values("year", "month", "company") .annotate(sales=Sum("amount")) .values("year", "month", "company", "sales") ) return result and models like: class Company(Model): name = CharField(max_length=64) class Sales(Model): sold_at = DatetimeField() company = ForeignKey(Company, on_delete=CASCADE) amount = PositiveIntegerField() then define factories using factory-boy class CompanyFactory(DjangoModelFactory): class Meta: model = Company name = faker.company() class SalesFactory(DjangoModelFactory): class Meta: model = Sale sold_at = FuzzyDate(start_date=date(2022,4,1), end_date=date(2022,12,31)) company = Subfactory(CompanyFactory) # maybe should change here? amount = 100 my test code is like: @pytest.fixture def setup(sales_factory): # This creates sales for 20 companies with sequential ids. sales_factory.create_batch(size=20) @pytest.mark.django_db def test_my_aggregation_function(setup): # create sales fixtures here or take it as argument? actual = aggregate_companies_sales_in_month() ... -
How to configure Celery when a database is shared between 2 Django projects?
I build an application with 2 Django projects, A and B. Both projects: have Celery configured and their own tasks share the same PostgreSQL database have a common Django application trading because they need access to the same models live in separate Docker containers on the same Docker host have dedicated Redis container and port number The problem is that Celery from project A says the task my_task from project_b/trading/tasks.py isn't registered. What is the reason for this and how can I isolate further more the two projects ? Project A settings.py CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://127.0.0.1:6377/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "redis://127.0.0.1:6377/0") CELERY_IMPORTS = ('trading.tasks',) celery.py app = Celery("project_a", broker='redis://localhost:6377/0') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) tasks.py empty Project B settings.py CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://127.0.0.1:6376/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "redis://127.0.0.1:6376/0") CELERY_IMPORTS = ('trading.tasks',) celery.py app = Celery("project_b", broker='redis://localhost:6376/0') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) tasks.py from project_b.celery import app @app.task def my_task(): pass -
How can I retrieve values of previously set session variables in a class based view?
I would really appreciate some insight on this because I think I've tried everything I could think of but I can't seem to make this work. I've tried using cache.set and cache.get instead of session variables but the class can't seem to read the cache that has been set even though my other function-based views can read them. I'm currently attempting to use server-side processing to display over 100k rows of data in a data table. The examples I've seen so far are mostly like this: class ItemListView(ServerSideDatatableView): queryset = TableName.objects.all() columns = ['column1', 'column2', 'column3'] But for my case, I have a function that stores filters selected by the user from the page. What I would like to do is: class ItemListView(ServerSideDatatableView): (code that retrieves session variables that store the filters selected by the user) queryset = TableName.objects.filter(country__in=selectedcountries, plant__in =selectedplants) columns = ['column1', 'column2', 'column3'] something like that. Can someone please help me, I don't have much experience on class-based views. thank you! -
Django - query extracts most frequent values field by field
i would like to return a single tuple with, field by field, the most frequent values. My models is as follows: class myTable(models.Model): a = models.IntegerField(blank = True, default = 0) b = models.IntegerField(blank = True, default = 0) c = models.IntegerField(blank = True, default = 0) d = models.IntegerField(blank = True, default = 0) My DB is as follows: ID a b c d 0 2 4 1 0 1 3 4 2 3 2 2 3 1 3 3 1 2 6 2 The single tuple that I want to return is constitued like that: a=2, b=4, c=1, d=3 (a is 2,3,2 and 1 so the most frequent value is 2). How can I do that? -
Problems with jquery/select2 framework - it doesn't work in my django project
i'm newbie in python, still learning this language and django framework. So i making simple project now, and now i meet this problem: i can't modify my design cause select2 and jquery not working in html document. Here is my files: base.html {% url 'cities:home' as cities_home_url%} {% url 'cities:create' as cities_create_url%} {% url 'trains:home' as trains_home_url%} {% url 'trains:create' as trains_create_url%} <!doctype html> <html lang="ar" dir="rtl"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.rtl.min.css" integrity="sha384-+4j30LffJ4tgIMrq9CwHvn0NjEvmuDCOfk6Rpg2xg7zgOxWWtLtozDEEVvBPgHqE" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/> <title>{% block title %}{% endblock %}</title> {{ form.media.css }} </head> <body> <nav class="navbar navbar-expand-lg container" style="background-color: #e3f2fd;"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home'%}">FindRoute</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item {% if request.path == cities_home_url%}active {% endif %}"> <a class="nav-link" aria-current="page" href="{% url 'cities:home'%}">Города</a> </li> <li class="nav-item" {% if request.path== trains_home_url%}active {% endif %}> <a class="nav-link" href="{% url 'trains:home'%}">Поезда</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item dropdown" {% if request.path== cities_create_url or request.path== trains_create_url %} active {% endif %} > <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Добавить </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" … -
problem with rendering <form> asynchronously using fetch in javascript in django application
I have written an ajax request in jQuery that I want to rewrite to pure javascript using fetch. What I am currently using is this: views.py @login_required def like_article(request, id): article = get_object_or_404(Article, id=id) is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' liked = False if article.likes.filter(id=request.user.id).exists(): article.likes.remove(request.user) liked = False else: article.likes.add(request.user) liked = True context = { 'article': article, 'is_liked': liked, 'total_likes': article.total_likes(), } if is_ajax: like_form = render_to_string('components/ajax_like.html', context, request=request) return JsonResponse({'like_form': like_form}) url.py path('like_article/<int:id>/', views.like_article, name='like_article'), ajax_like.html <form action="{% url 'like_article' article.id %}" method="POST"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" value="{{article.id}}" class="btn btn-clicked"><i class='bx bxs-like'></i></button> {% else %} <button type="submit" id="like" value="{{article.id}}" class="btn btn-to-be-clicked"><i class='bx bx-like'></i></button> {% endif %} {{ total_likes }} like{{ total_likes|pluralize }} </form> jQuery ajax request (working fine) $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var id = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like_optimazon" article.id %}', data: { 'id':id, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function(response){ $('#like-section').html(response['like_form']) }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); }); What I tried to do is below. Basically, after clicking the like button the class should change from .btn-not-liked to .btn-liked and the number of likes should increase by 1. I;d like to … -
Nested dynamic URLs from different Viewsets
backend noob here. I have a question about nested URLs in Django/DRF. I want to nested url structure, for example: site.com/blog/: shows list of blog. site.com/blog/blog-name/: which shows single blog with name. site.com/blog/blog-name/posts: shows the post list of the blog. site.com/blog/blog-name/posts/some-blog-post: single blog post. site.com/blog/blog-name/posts/some-blog-post/tags: list of tags. site.com/blog/blog-name/posts/some-blog-post/tags/1: a tag with id = 1. I have read this answer but it suggest an additional method in BlogViewset. However I need to nest URLs using two different viewsets. Because as you can see this is just initial fields of an userblog system and I want to be able to manage it without having big files. I have three models, like this: class TagModel(models.Model): tag = models.CharField(max_length=32) def __str__(self): return self.tag class BlogModel(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) profession = models.CharField(max_length=100) class Meta: pass def __str__(self): return self.name class PostModel(models.Model): title = models.CharField(max_length=120) content = models.TextField() tags = models.ManyToManyField(TagModel) blog = models.ForeignKey(BlogModel, on_delete=models.CASCADE, related_name="posts") def __str__(self): return self.title This is my viewset for Blogs: from ..models.blog import BlogModel, PostModel from ..serializers.blog import BlogSerializer from rest_framework import viewsets from rest_framework import mixins from django.shortcuts import render class BlogViewset( mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = BlogModel.objects.all() serializer_class = BlogSerializer # Return … -
How to run VBScript file using django in IIS
I want to execute vbscript file in project folder using django in IIS. It is working fine in django production server but it is not working in IIS server. I have used the following code to execute vbscript file completed = subprocess.run(["cscript", "C:\\Automation\\Python\\Invoicepdfdemo\\pdfdemo\\media\\pdfs\\start.vbs"]) please advice how to call and execute vbs file in django in IIS -
Multiple models seaarch with Django Rest Framework
I need to make a search through some different models and than make an endpoint for it with DRF. So my attempt to make it looks like this class DataSearch(FlatMultipleModelAPIView): def get_querylist(self): q = self.request.query_params.get('query') if q: vector_data = SearchVector('research', 'data', 'research__name') vector_var = SearchVector('label', ) query = SearchQuery(q, search_type='websearch') querylist = [ { 'queryset': Data.objects.annotate(search=vector_data).filter(search=query), 'serializer_class': DataSerializer }, { 'queryset': Variable.objects.annotate(search=vector_var).filter(search=query), 'serializer_class': VariableSerializer } ] else: querylist = [Data.objects.none()] return querylist Here I'm using DjangoRestMultipleModels for making query goes by two models. When I'm trying to run thin stuff I have an error DataSearch cannot use the regular Rest Framework or Django paginators as is. Use one of the included paginators from drf_multiple_models.pagination or subclass a paginator to add the format_response` method. Any ideas of what paginators doing here? Or how to make all this stuff work correctly? -
JSON parse error - Expecting value: line 1 column 1 (char 0)
I want to serialize with Django and Django Rest, but I am getting the error I mentioned above while adding a record. Can you help me? def recordCreate(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = RecordSerializer(data = data) if serializer.is_valid(): serializer.save() return render(request,"registration_form.html") return render(request,"registration_form.html") serializers.py class Meta: model = Records fields = ['id','username','tel','tcNo','adress','kurum','diagnosis','intervention','conclusion','doctor'] -
Creating a nested Comment section
What is the best way to create a nested comment section? I haven't been able to set it up add to my current setup. My current Views is setup is class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'add_comment.html' # fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('home') This is my current models is.. class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=250) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) Any help on this would be greatly appreciated! -
Django query by separate date and time fields (how to perform conditional order_by)
I have a Meeting model. It has a separate data and time field, the reason why it is not a single datetime field, is that the time is allowed to be null. If I used a single datetime field and set the hours/minutes to 00:00 if no time given, then I can't distinguish that from a meeting set at 00:00. And some unusual sentinel value like 13:37:42 as no meeting is a werid hack. Heres the model: class Meeting(models.Model): meeting_date = models.DateField(db_index=True) meeting_time = models.TimeField(db_index=True, null=True, blank=True) Now the problem comes in to filter by a given date/time. So I think the solution is to filter by date, then order by the time. E.g. to get the latest meeting that is before now: from datetime import datetime now = datetime.now() prev_meeting = ( Meeting.objects.filter(meeting_date__lte=now.date()) .order_by('-meeting_date', f'meeting_time <= {now.time()}', '-meeting_time') .first() ) The f'meeting_time <= {now.time()}' is the part I don't know how to do with the django ORM, but I know how to do with SQL. the Django Docs do not mention conditional ordering.