Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django views : unsupported operand type(s) for +: 'int' and 'NoneType'
I loop through multiple question stored in my DB each question has 5 answers(openness,conscientiousness,extraversion,agreeableness,neuroticism) and am trying to count how many times each answers is repeated and store the scores Models : class Reponses(models.Model): ScoreOp = models.IntegerField(blank=True,null=True) ScoreCon = models.IntegerField(blank=True,null=True) ScoreExt = models.IntegerField(blank=True,null=True) ScoreAgr = models.IntegerField(blank=True,null=True) ScoreNeu = models.IntegerField(blank=True,null=True) Product = models.OneToOneField("Product", on_delete=models.CASCADE,null=True) class Personalite(models.Model): Question = models.CharField(max_length=50,blank=True) openness = models.CharField(max_length=20,blank=True) conscientiousness = models.CharField(max_length=20,blank=True) extraversion = models.CharField(max_length=20,blank=True) agreeableness = models.CharField(max_length=20,blank=True) neuroticism = models.CharField(max_length=20,blank=True) models.ForeignKey("Reponses", on_delete=models.CASCADE,null=True) Views : def home_views(request): questions= Personalite.objects.all() product = Product.objects.get(id=5) if request.method == 'POST': try: reponse = Reponses.objects.create() reponse = Reponses(Product= product) allRep = [] allRep = request.POST.getlist('poll') for Rep in allRep: print(Rep) if Rep == 'openness': reponse.ScoreOp = reponse.ScoreOp + 1 elif Rep == 'conscientiousness': reponse.ScoreCon += 1 elif Rep == 'extraversion': reponse.ScoreExt += 1 elif Rep == 'agreeableness': reponse.ScoreAgr += 1 elif Rep == 'neuroticism': reponse.ScoreNeu += 1 else : print('HAHAHAHHAHAAH') reponse.save() except NameError: print("An exception occurred",NameError) context={ 'questions':questions } return render(request , "home.html",context) -
Discord.py call task immediately
I'm trying to add an API (Django/DRF) to my discord.py bot. Currently the best solution I have is to add a task from the endpoint then return a 202. The task then executes... eventually. Django Rest Framework viewset.py`: async def connect_client(self, request, client): print('Connecting client...') from discordbot import music_player await music_player.connect() @action(methods=['get'], detail=False) def connect(self, request, pk=None): from discordbot import client client.loop.create_task(self.connect_client(request, client)) return Response(status=202) This works, and it does do what the task is supposed to do. But when it executes seems to be entirely reliant on how fast the event loop polls. Can I either change how fast the event loop polls (to every 500ms or 1000ms), or have it create a task and call it immediately? -
Django: Annotating age from date_of_birth
I have a date of birth (dob) DateField in my Django Model (Author). I tried to annotate age parameter. I searched for many possible ways to do it and each procedure generated some kind of error. Here I tried in python console first to make sure that the expression would be a valid one: >>> from datetime import datetime >>> (datetime.now() - datetime(2000,1,1)).days #output: 7506 First Try: >>> from django.db.models import F >>> authors = Author.objects.annotate(age = (datetime.now()-F('dob')).days) #no-error here >>> print(authors) # Exception thrown here Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/puru/Documents/Python/django/prac1/django-master/lib/python3.7/site-packages/Django-3.2-py3.7.egg/django/db/models/query.py", line 324, in __getitem__ qs._fetch_all() File "/home/puru/Documents/Python/django/prac1/django-master/lib/python3.7/site-packages/Django-3.2-py3.7.egg/django/db/models/query.py", line 1305, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/puru/Documents/Python/django/prac1/django-master/lib/python3.7/site-packages/Django-3.2-py3.7.egg/django/db/models/query.py", line 70, in __iter__ for row in compiler.results_iter(results): File "/home/puru/Documents/Python/django/prac1/django-master/lib/python3.7/site-packages/Django-3.2-py3.7.egg/django/db/models/sql/compiler.py", line 1100, in apply_converters value = converter(value, expression, connection) File "/home/puru/Documents/Python/django/prac1/django-master/lib/python3.7/site-packages/Django-3.2-py3.7.egg/django/db/backends/sqlite3/operations.py", line 291, in convert_datefield_value value = parse_date(value) File "/home/puru/Documents/Python/django/prac1/django-master/lib/python3.7/site-packages/Django-3.2-py3.7.egg/django/utils/dateparse.py", line 75, in parse_date match = date_re.match(value) TypeError: expected string or bytes-like object Second time I used ExpressionWrapper to define that output type will be DateTimeField >>> from django.db.models import DateTimeField, ExpressionWrapper >>> authors = Author.objects.annotate(age = ExpressionWrapper(timezone.now() - F('dob'), output_field=DateTimeField()).days) AttributeError: 'ExpressionWrapper' object has no attribute 'days' I have also tried the RawSQL. I … -
Can i use some async function inside django without using async djnago?
I have simple function that cheks that file is exist to go next step, and on view of django requests launch that function to check and wait sleep some second, but in the same time, send response to front-end like "We are waiting". Or i need use async django better?or need use celery?but how to get feedback of celery? async def checkThatFileIsExist(filepath: "Path to file") -> dict: while True: if os.path.isfile(filepath): return {"status":True, "error-message":""} else: await asyncio.sleep(2) await asyncio.sleep(2) return {"status":False, "error-message":"I have no message use try"} -
Django: Static files not loading: MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled
I'm not sure what is wrong in my set up but an error seems to be being thrown when my application tries to load the stylesheets: My Settings.py file has the following configuration: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') MEDIA_ROOT = os.path.join(VENV_PATH, 'media') And my urls.py file has the following configuration: from django.contrib import admin from django.urls import path from django.conf.urls.static import static from django.conf import settings from .views import blog, index urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My file structure is as follows: I'm also calling load static in my head.html template so I'm not sure what could be going wrong: {% load static %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Bootstrap Blog - B4 Template by Bootstrap Temple</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="all,follow"> <link rel="stylesheet" href="{ % static 'vendor/bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{ % static 'vendor/font-awesome/css/font-awesome.min.css' %}"> <link rel="stylesheet" href="{ % static 'css/fontastic.css' %}"> <link rel="stylesheet" href="{ % static 'https://fonts.googleapis.com/css?family=Open+Sans:300,400,700' %}"> <link rel="stylesheet" href="{ % static 'vendor/@fancyapps/fancybox/jquery.fancybox.min.css' %}"> <link rel="stylesheet" href="{ % static 'css/style.default.css' %}" id="theme-stylesheet"> <link rel="stylesheet" … -
How to storage variable in django channels consumer?(channels==1.x)
I create a variable in connect consumer, i want to use this variable in receive consumer. But i find that this variable can not be saved. I read the source code of runserver & runworker, i found that every request will generate a new object, So what can i do? Does channels 1.x support variable storage? channels version: 1.x code like that: class SSHConsumer(WebsocketConsumer): def connect(self, message, **kwargs): self.a = xxx def receive(self, text=None, bytes=None, **kwargs): b = self.a -
How to SUM query number with comma in Django
In my database, I have numbers that is separated by comma i.e 10,000. So when I try to sum them I got this error : "Error converting data type nvarchar to float" Before this it's working just fine when I don't have the comma. Is it possible to SUM query data with comma ? Below is my code : total1 = Income.objects.filter(Q(income_id = income_id) & (Q(title='Salary') | Q(title='Overtime'))).annotate(as_float=Cast('conversion_amount', FloatField())).aggregate(Sum('as_float')) Really appreciate your help on this -
Bootstrap dropdown not working --- how to fix?
I have looked at other similar questions, but all of them does not work. I'm using Django, and here's my code. index.html {% extends 'base.html' %} {% block body %} <nav> <div class="logo"> Cleaveway Pizzas </div> <ul class="nav-links"> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> </ul> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown button </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </div> </nav> {% endblock %} base.html {% load static %} <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{% static 'bootstrap/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'bootstrap/bootstrap-grid.min.css' %}"> <link rel="stylesheet" href="{% static 'bootstrap/bootstrap-reboot.min.css' %}"> <link rel="stylesheet" href="{% static 'pizza/login.css' %}"> <link rel="stylesheet" href="{% static 'pizza/navbar.css' %}"> <link rel="stylesheet" href="{% static 'import/import.css' %}"> <link rel="script" href="{% static 'bootstrap/bootstrap.bundle.js' %}"> <link rel="script" href="{% static 'bootstrap/bootstrap.js' %}"> </head> <body> {% block body %} {% endblock %} </body> </html> can anyone help? It shows the button but nothing happens when the button is clicked. -
Django rounding decimal number to n decimal places based on another column
So I am using PostgreSQL and Django with the following model class Example(model.Model): num = models.DecimalField(max_digits=20, decimal_places=10) round_to= models.IntegerField() What I would like to achieve is that: Example.objects.annotate(rounded = Round(F('num'),F('round_to')) But it seems that Round function only allow me to round to integer. -
Django Form Not Submitting From Template
I am having troubles with submitting the this form. I could submit the form from the admin dashboard but not from the template. What could I be doing wrong? models.py file: from teamprofile.models import TeamProfile from django.utils import timezone from competition.models import CompetitionProfile from datetime import datetime from django.contrib.auth.models import User class MatchProfile(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) competition = models.ManyToManyField(CompetitionProfile) home_team = models.ForeignKey(TeamProfile, on_delete=models.CASCADE, related_name = 'home_team') away_team = models.ForeignKey(TeamProfile, on_delete=models.CASCADE, related_name = 'away_team') # start_time = models.DateField(blank=True, null=True) def __str__(self): return "{} vs {}".format(self.home_team, self.away_team) forms.py file: from .models import MatchProfile class CreateMatchForm(forms.ModelForm): class Meta(): model = MatchProfile fields = ('competition', 'home_team', 'away_team') widgets = { 'competition': forms.Select(attrs={'class': 'uk-select'}), 'home_team': forms.Select(attrs={'class': 'uk-select' }), 'away_team': forms.Select(attrs={'class': 'uk-select' }), # 'start_time': forms.SelectDateWidget(), } views.py file: from .forms import CreateMatchForm from .models import MatchProfile class MatchProfileCreateView(CreateView): model = MatchProfile success_url = reverse_lazy('timeline') form_class = CreateMatchForm def form_valid(self, form): form.instance.owner = self.request.user return super(MatchProfileCreateView, self).form_valid(form) .html file: <h5 class="mb-0"> Match Detail </h5> </div> <hr class="m-0"> <form class="uk-child-width-1-2@s uk-grid-small p-4" uk-grid method="POST"> <div> {% csrf_token %} <h5 class="uk-text-bold mb-2"> Competiton Name </h5> {{ form.competition }} <!-- <input type="text" class="uk-input" placeholder="Your name"> --> </div> <div> <h5 class="uk-text-bold mb-2"> Home Teams </h5> {{ form.home_team }} <!-- … -
New users credentials not showing up in Django database after registration
I am working on a Django application and making a user registration form using Django's built-in tools. The html in the form renders and accepts input, but when I check my Users model in my admin interface, the new user's credentials do not show up. The login page also does not work with the newly-created user. views.py - user (note I am using a different Django app to handle users) from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.urls import reverse from django.shortcuts import render, redirect from django import forms from .forms import RegisterForm #still need to build a way to handle error messages def register_view(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('index') else: form = RegisterForm() return render(request, 'users/register.html', {"form":form}) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2', 'email'] urls.py from django.urls import path, include from django.contrib import admin from django.contrib.auth.forms import UserCreationForm from . import views from users import views as users_views urlpatterns = [ path('', views.index, … -
Django Rest Framework DELETE request responds like a GET request
I'm trying to delete an entry in my data base that is returned by a modelviewset get_queryset. When sending a DELETE request through the DRF web interface and via postman, I receive this response "DELETE /api/remove_self/3 HTTP/1.1" 200 along with the data I am trying to delete. The code that gives this result looks like this: Models.py class EventAtendee(models.Model): """Lists users atending an event""" #below connects user profile to event id = models.AutoField(primary_key=True) event_id = models.IntegerField(null = True) user_profile = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return self.event_id views.py class RemoveSelfFromEvent(viewsets.ModelViewSet): """Remove Yourself From an Event you were attending""" authentication_classes = (TokenAuthentication,) serializer_class = serializers.EventAtendeeSerializer permission_classes = (permissions.UpdateOwnStatus, IsAuthenticated) def perform_create(self, serializer): """Sets the user profile to the logged in user""" # serializer.save(user_profile=self.request.user) def get_queryset(self): """ This view should return a list of all the purchases for the user as determined by the username portion of the URL. """ #user_profile = self.kwargs['user_profile'] event_id = self.kwargs['event_id'] return models.EventAtendee.objects.filter(event_id=event_id, user_profile=self.request.user) def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) def perform_destroy(self, instance): instance.delete() urls.py router = DefaultRouter(trailing_slash=False) router.register('events', views.EventAtendeeViewSet, basename='EventAtendee') urlpatterns = [ path('remove_self/<event_id>', views.RemoveSelfFromEvent.as_view({'get': 'list', 'delete': 'list'})), ] Any help is much appreciated! -
How to request uploaded files from a Model's FileField and that Model's Foreign Key's FileField?
Given these two models : class Question(models.Model): title = models.CharField(max_length=100) content = models.TextField() solution = models.FileField( validators=[FileExtensionValidator(allowed_extensions=['txt'])], upload_to= 'media') def __str__(self): return self.title def get_absolute_url(self): return reverse('coder:detail', kwargs={'pk': self.pk}) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) result = models.FileField( validators=[FileExtensionValidator(allowed_extensions=['txt'])], upload_to= 'media', blank = True, null = True) How would I request their uploaded files using request.FILES in a Class Based View to further compare those files? The view being this : from django.shortcuts import get_object_or_404, render from django.urls import reverse_lazy, reverse from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, DetailView, CreateView, UpdateView, RedirectView from django.db.models import Q from .models import Question, Answer class CoderListView(ListView): model = Question template_name = "coder/coder_list.html" context_object_name = 'question' class CoderDetailView(DetailView): model = Question template_name = "coder/coder_detail.html" context_object_name = 'question' class CoderCreateView(CreateView): model = Answer fields = ['result'] context_object_name = 'answer' template_name = "coder/coder_form.html" def get_success_url(self): question = self.object.question return reverse('coder:detail', kwargs={'pk': question.id}) def form_valid(self, form): form.instance.question = Question.objects.get(id=self.kwargs['qid']) return super().form_valid(form) def compare(solution, result): is_same = True for line1, line2 in zip(solution, result): if line1 != line2: is_same = False return is_same In the views.py, I want to assign solution the value of the Answer model's foreign key's ( Question ) uploaded file and result … -
how to remove extra squared brackets in a response on djago rest framework
I created a stored function in PostgreSQL returns a table, and called that function in a Django-rest-framework like this: def getSomeFunc(self): with connection.cursor() as cursor: cursor.execute(f'select json_agg(myfunctionpsql) from myfunctionpsql') table = cursor.fetchall() return table this function is called in a views file, like a code below: class myview(views.APIView): def get(self, request): fund = getSomeFunc(self) return Response({'data': fund}, status=status.HTTP_200_OK) well the response is like this: { "data": [ [ // I want to delete this [ // I want to delete this { "id": 21, "somedata": "FIX A", "somedata": "FIX A", "sometag": 0.95, "somdata": "005.119.745/0001-98", "somedatayear": 1.57, "somedata12": 4.11, "somedata36": 19.58, "somedata60": 51.9, "datarisk": 0 } ]// I want delete this ]// I want to delete this ] } and I need response below: { "data": [{ "id": 21, "somedata": "FIX A", "somedata": "FIX A", "sometag": 0.95, "somdata": "005.119.745/0001-98", "somedatayear": 1.57, "somedata12": 4.11, "somedata36": 19.58, "somedata60": 51.9, "datarisk": 0 }] } I try this: class myview(views.APIView): def get(self, request): fund = getSomeFunc(self) reps = str(fund)[1:-1] return Response({'data': resp}, status=status.HTTP_200_OK) but the response is all converted and return in a string, how to delete extra squared brackets, in a response. regards. -
Django import excel file returns blank even if there is data in my excel file?
I'm new to django and i really want to learn this framework. I tried to implement django-import-export in my project. I followed the django-import-export documentation and I encountered a problem when importing excel file. Here is my Status Model from django.db import models # Create your models here. class Status(models.Model): class Meta: verbose_name_plural = 'Status' StatusCode = models.CharField(max_length=60, null=False, blank=False, unique=True) def __str__(self): return self.StatusCode Here is the excel content Status.xlsx Here is the preview when i import the excel file Preview Why is it that the output is blank? -
What causes "no attribute 'object_list' when I purposely csuse HTML error
I am writing a django ListView with FormMixin, but it can't handle form errors. The model limits input to 140 characters, when I inspect and change limit to 200 and submit I get "'PostListView' object has no attribute 'object_list'". Here's the code class PostListView(FormMixin, generic.ListView): model = Post form_class = PostForm paginate_by = 10 template_name = 'index.html' def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): form = PostForm(request.POST) if form.is_valid(): form.save() return super().form_valid(form) else: return self.form_invalid(form) With everything working normally, it saves the data and displays the list. On error, no error, it fails. Kindly help -
Application labels aren't unique, duplicates: account. Django
I know there are Duplicates of this question, but they didn't solve the issue. my django app is conflicting between django-user-acccounts; account and allauth.account M Installed App INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'django.contrib.sites', # 'allauth', 'allauth.account', # django-allauth # conflict 'allauth.socialaccount', 'crispy_forms', 'account', # django-user-accounts #conflict 'pinax.referrals', 'kingEstateCore', 'widget_tweaks', ] I've tried renaming the account package inside my site_packages but no success. I've also tried adding AppConfig but there was no apps.py module insite my site_packages/account. Any Ideas pls -
How to dynamically update Django Form min_value in a view?
I am trying to create an auction site where a user can place a bid on an item. I'm storing a minimum bid within a model, and am retrieving that value when the view is loaded. I would like to use min_value to prevent a user from putting in a bid lower than min_bid. I am not getting any sort of errors, it's just that the min_value is not working. My form class: class place_bid(forms.Form): bid_amount = forms.IntegerField(label="Bid Amount") def __init__(self, min_value, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bid_amount'].min_value = 1 The view that loads the form (at this time I haven't written the part where I actually process the user submission, just trying to get the validation right first) def listings(request, listing_id): listing = Listing.objects.get(id=listing_id) if request.method == "POST": min_bid = listing.min_bid return render(request, "auctions/listings.html", { "listing": listing, "bids": listing.bids.all(), "form": place_bid(min_value={"bid_amount":5}) }) if request.method == "GET": return render(request, "auctions/listings.html", { "listing": listing, "bids": listing.bids.all(), "form": place_bid(min_value={"bid_amount":5}) }) The HTML: <form action="/listings/{{listing.id}}" method="post"> {% csrf_token %} {{ form }} <button class="btn btn-primary" type="submit">Place Bid</button> </form> I've tested removing all of the def __init__ stuff and changing bid_amount = forms.IntegerField(label="Bid Amount") to `bid_amount = forms.IntegerField(label="Bid Amount", min_value=5) and that works, but I … -
Previous and next object in a large Django queryset
I have a model like this: class Article(models.Model): title = models.CharField(max_length=2000) date_created = models.DateTimeField() public = models.BooleanField(default=True, blank=True) ... And a view (simplified): def article(request, id): article = get_object_or_404(Article, id=id) data = { 'article': article, } return render(request, 'articles/article.html', data) This works fine. Next, I tried to add the buttons for the previous and the next article, using Django's get_previous_by_FIELD and get_next_by_FIELD: def article(request, id): article = get_object_or_404(Article, id=id) try: previous_item = article.get_previous_by_date_created(public=True) except ObjectDoesNotExist: previous_item = None try: next_item = article.get_next_by_date_created(public=True) except ObjectDoesNotExist: next_item = None data = { 'article': article, 'previous_item': previous_item, 'next_item': next_item, } return render(request, 'articles/article.html', data) In principle, this works as well. But there is an issue with the performance. Without the previous/next buttons SQL queries are executed in under 50 ms. With the previous/next buttons, it takes over 2000 ms. The problem is that there are about 500.000 articles in the database (imported from RSS feeds so the number is increasing fast). Does someone have an idea how to implement the previous/next object functionality in a different, more efficient way? -
ImproperlyConfigured at /post/129/delete/ PostDeleteView is missing a QuerySet
i want to delete my project in my interface django with api but i received this problem ,please where is my error in this code ? views.py class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): def test_func(self, *args, **kwargs): success_url = '/project/' headers = {'Content-type': 'application/json', 'PRIVATE-TOKEN': ''} pk = self.kwargs.get('pk') url="http://172.16.0.111/api/v4/projects/:id/" data={"name":"", "description":""} data=JsonResponse(data) headers = {'Content-type': 'application/json', 'PRIVATE-TOKEN': ''} response = requests.delete("http://172.16.0.111/api/v4/projects/:id/", headers=headers,data=data) print(response) return HttpResponseRedirect(success_url) return Response(status = status.HTTP_204_NO_CONTENT) -
Querying Django Postgres for Fuzzy FTS + Typeahead
I'm using PostgreSQL 12.3 with Django 3.08. I'm trying to implement a typeahead functionality. I tried using Trigram similarity, but that didn't work too well since, if I were to have a text saying "chair," I would have to type "cha" before I get results. I'm using corejavascript/twitter's typeahead JS library. Their first example (The Basics) allows you to type in a single letter and get results instantly, some of which are not even the prefix of the word. How would I do that? You can view my current functionality here: https://github.com/Donate-Anything/Donate-Anything/blob/76348e9362d386d3d6375b9a75d47d5765960992/donate_anything/item/views.py#L21-L30 I thought that I should use to_tsvector with a SearchVectorField, but when I implemented that (with a query like this: queryset = ( Item.objects.defer("is_appropriate") .filter(name_search=str(query)) ) then I don't even see the results until I type in the full word. What would my implementation look like then? (Article for implementing the triggers for SearchVectorField) -
django-summernote attach images from another model/ForeignKey
I've added django-summernote to a project, but when the user inserts an image, instead of the upload popup, I want a popup with a ModelChoiceField for Photos.objects. It's a website for a photographer, and the Photos model has necessary additional functionality. I could have him go through the process of getting the image's url and adding it that way, but this would be much cleaner. I've tried a lot of things, but kind of a stab in the dark all around. django-summernote docs describe how to set a custom attachment model, but only just.... First, I created another model in django-summernote.models that inherits from AbstractAttachment: class PhotoAttachment(AbstractAttachment): img = models.ForeignKey(Photos, on_delete=models.PROTECT, default='None') I also tried changing django-summernote.forms.py: from: file = forms.ImageField(required=True) to: img = forms.ModelChoiceField(queryset=Photos.objects, required=True) ...and a few other things. I've been poking around for a few hours, but I honestly don't know where to begin. I do have working ModelChoiceFields on ForeignKey's elsewhere in my models coming up in the old djangoadmin, so that's all fine - I just want to customize summernote to pull one up when the user tries to add an image. Suggestions? -
Render & Clean Django model foreign key as text input with autocomplete
Hello everybody i'm developing my own functionality to give the option that a foreign key model field can be rendered as text input with autocomplete instead of a select. The front-end, js and ajax part works correctly but on form get and post time i'm a bit lost. I would like that when the form field is rendered it would construct a text type input with the name from the foreign key and when the post is made it would work the other way, that with the name it would obtain the id It could work with its own widget and do a couple of functions to go from id to name and vice versa. Anybody could help me ? Any idea ? Thank in advance. -
Django rest framework,filtering a date field raises None type error
I have an API with the following model: class Month(models.Model): date = models.DateField(primary_key=True, unique=True) days = models.PositiveSmallIntegerField(default=0, validators=IntegerValidators.MONTH_VALIDATOR, ) dealership = models.ForeignKey(to=Dealership, on_delete=models.CASCADE, related_name='months') def __str__(self): return str(self.date) and the serializer: class MonthSerializer(serializers.ModelSerializer): date = serializers.DateField(input_formats=['%m-%Y'], format='%m-%Y') class Meta: model = Month fields = '__all__' So my date format is MM-YYYY. In my view, when I try to get the object associated with this month using python's datetime module: class MonthsViewSet(ModelViewSet): authentication_classes = (TokenAuthentication,) def get_queryset(self): query_set = Month.objects.filter(farm__user=self.request.user) return query_set serializer_class = MonthSerializer @action(detail=False) def get_next_year(self, *args, **kwargs): year = datetime.datetime.today().year month = datetime.datetime.today().month first = datetime.date(year, month, 1).strftime('%m-%Y') query_set = self.queryset().filter(date=first) serializer = MonthSerializer(data=query_set) return Response(serializer.data, status.HTTP_200_OK) When I go to the endpoint I get the following error: "/home/yovel/PycharmProjects/scr/rivendell/api/views/months_view.py", line 38, in get_next_year query_set = self.queryset().filter(date__gte=year) Exception Type: TypeError at /api/months/get_next_year/ Exception Value: 'NoneType' object is not callable -
Django - I have a stats dashboard, recommendations on how to refresh the dashboard without client having to refresh page?
How can I have my stats dashboard refresh automatically with up to date revenue and transactions for the business, without user having to click on the refresh button in their browser. I want a similar implementation to this Bitcoin USD chart on Yahoo Finance, where data changes without refresh: https://finance.yahoo.com/quote/BTC-USD?p=BTC-USD views.py @login_required() def dashboard(request): business = get_object_or_404(Business, businessperson=request.user) return render(request, 'business/dashboard.html', { "business": business, }) dashboard.html {% extends my_base %} {% load static %} <title>Dashboard</title> {% endblock %} {% block content %} <h1>Dashboard</h1> <h2>{{business.name}}</h2> <p>{{business.transactions}}</p> <p>{{business.revenue}}</p> {% endblock %}