Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I do search for multiple things (full-text, geolocation etc) in DRF?
I have a model in Django-REST that has name, description etc, plus geolocation using GeoDjango. Now, I would like to have a complicated search, with full-text search in the name and description fields plus geolocation search(the user gives a location point and a maximum distance). I want these to work independently and together if need be. I've seen how to do full-text search (here:https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/search/) and how to search based on distance(here: https://docs.djangoproject.com/en/2.2/ref/contrib/gis/db-api/). My code so far (the models, doesn't matter, just think of the name, description and location point): class SearchAuctions(APIView): permission_classes = [AllowAny] def get(self, request, format=None): """ Return auctions after filtering. """ items = AuctionItem.objects if 'textToSearch' in request.data.keys(): textToSearch = request.data['textToSearch'] items = AuctionItem.objects.annotate( search=SearchVector('name', 'description'), ).filter(search=textToSearch) itemSerializer = AuctionItemSerializer(items, many=True) return Response(itemSerializer.data) Not sure how I can create a chain link between filters. I've though of making multiple requests and finding the common elements, but that is way too slow I guess. -
django templates add html attibute from variable
How do I add dynamic html attribute in django template? For example we have n=5 And have this html markup in index.html: <select tabindex={{n}}> But it doesn't work, generated html looks like this: <select tabindex="{{n}}"> And I need this: <select tabindex="5"> What do I do? -
I am running an app (Django framework). I get error
When I run app in Django - I get the following error (See below). The app's name is runtrack. The error is generated when I click an "ADD" button in the app. I thought it was to do with the Allowed Hosts not being defined. I added ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] in settings.py but no luck Actual Result in IDE: [18/Aug/2019 15:54:01] "GET /api/runtrack/?search= HTTP/1.1" 200 2 [18/Aug/2019 15:54:01] "GET /runtrack HTTP/1.1" 200 13174 [18/Aug/2019 15:54:01] "GET /api/runtrack/?search= HTTP/1.1" 200 2 [18/Aug/2019 15:54:02] "GET /runtrack HTTP/1.1" 200 13174 [18/Aug/2019 15:54:02] "GET /api/runtrack/?search= HTTP/1.1" 200 2 [18/Aug/2019 15:54:02] "GET /api/runtrack/?search= HTTP/1.1" 200 2 Bad Request: /api/runtrack/ [18/Aug/2019 15:54:06] "POST /api/runtrack/ HTTP/1.1" 400 92 -
Unknown issue when deploying a Django app to Heroku with anaconda
I use Django 1.11.20 and Python 2.7. My app is deployed with Heroku. As I need numpy/scipy and Heroku has a slug size limited to 500Mb, I am using anaconda through the three following Heroku packages : https://github.com/kennethreitz/conda-buildpack https://github.com/cyberdelia/heroku-geo-buildpack.git heroku/python The site was working perfectly since 1 year. I had not updated it since a few months. I brought minor changes to the site recently and I got the following error when deploying it to Heroku. I don't understand what is the issue exactly. Any clue ? -----> Deleting 0 files matching .slugignore patterns. -----> Python/Conda app detected added pinned file in /app/.heroku/miniconda/conda-meta/pinned Collecting package metadata: ...working... done Solving environment: ...working... done ## Package Plan ## environment location: /app/.heroku/miniconda added / updated specs: - nomkl The following packages will be downloaded: package | build ---------------------------|----------------- nomkl-3.0 | 0 48 KB ------------------------------------------------------------ Total: 48 KB The following packages will be UPDATED: nomkl 1.0-0 --> 3.0-0 Proceed ([y]/n)? Downloading and Extracting Packages Preparing transaction: ...working... done Verifying transaction: ...working... done Executing transaction: ...working... done -----> Installing dependencies using Conda Collecting package metadata: ...working... done Solving environment: ...working... The environment is inconsistent, please check the package plan carefully The following packages are causing … -
Django urls can't find templates with HTML file
I'm trying to create views in my Django ToDo App. But there is a TemplateDoesNotExist error. I was looking for solve but it still not working. This is my urls.py in main folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('todoapp_api.urls')), ] Then my app folder is "todoapp_api" And there i have urls.py from django.urls import path from . import views urlpatterns = [ path('', views.app, name='app'), ] My views.py looks like this from django.shortcuts import render from django.http import HttpResponse def app(request): return render(request, 'todoapp_api/app.html') -
Manually pass additional data during partial model update
I have to pass user to different fields depending on the requested data. In case the instance was "rejected" I need to pass rejected = True and the user as rejected_by = request.user how to change those values manually since I use partial_update. I have tried to do this by passing additional data to serializer_class but this seems to not work. class AcceptRejectCoreWord(generics.UpdateAPIView): queryset = WordCoreModel.objects.all() serializer_class = AcceptRejectCoreWordSerializer lookup_field = 'id' def patch(self, request, *args, **kwargs): user = get_user_model().objects.get(email=request.user) if not user.groups.filter(name="Moderator").exists(): return Response({ 'error': 'Only moderators have permissions to view this endpoint'}, status=status.HTTP_403_BAD_REQUEST) if request.data['rejected']: reject_reason = request.data['rejection_reason'] if not reject_reason: return Response({ 'error': 'Rejection reason is required'}, status=status.HTTP_400_BAD_REQUEST) self.serializer_class(accepted=False, accepted_dy=None, rejected=True, rejected_by=user, modified_by=user, publishing_status='rejected') if request.data['accepted']: self.serializer_class(rejected=False, rejected_by=None, accepted=True, accepted_dy=user, modified_by=user, publishing_status='published') return self.partial_update(request, *args, **kwargs) My serializer class contains this fields but I don't know how to update them in case of using partial_update method. class AcceptRejectCoreWordSerializer(serializers.ModelSerializer): part_of_speech_type = CoreWordSpeechPartDescriptionSerializer( many=True, required=False) class Meta: model = WordCoreModel fields = ['id', 'word_core', 'word_russian_typed', 'word_english_typed', 'part_of_speech_type', 'uncensored_word', 'modified_by', 'publishing_status', 'accepted', 'accepted_by', 'rejected', 'rejected_by', 'rejection_reason'] extra_kwargs = {'id': {'read_only': False}} def update(self, instance, validated_data): word_descriptions = validated_data.pop('part_of_speech_type') core_word = WordCoreModel.objects.get(id=validated_data['id']) for word_description in word_descriptions: CoreWordSpeechPartDescription.objects.update( word=core_word, **word_description) return core_word … -
ValueError not enough values to unpack (expected 4, got 2) - Django
I have this view: def getData(): response = requests.get("https://path.to/api/") data = response.json() random_data = [MyModel(name=name, street=street, email=email, phone=phone) \ for name, street, email, phone, in data.items()] MyModel.objects.bulk_create(random_data) @require_http_methods(['GET', 'POST']) def index(request): datas = getData() return render(request, 'index.html') When I access the specified url for index method, it throws me this: Traceback (most recent call last): File "/home/user/.virtualenvs/myproj/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/.virtualenvs/myproj/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/.virtualenvs/myproj/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.virtualenvs/myproj/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/home/user/django_projects/myproj/myproj/user/views.py", line 29, in index datas = getData() File "/home/user/django_projects/myproj/myproj/user/views.py", line 18, in getData for name, street, email, phone, in data.items()] File "/home/user/django_projects/myproj/myproj/user/views.py", line 18, in <listcomp> for name, street, email, phone, in data.items()] ValueError: not enough values to unpack (expected 4, got 2) [18/Aug/2019 15:18:05] "GET /api/index/ HTTP/1.1" 500 85435 Method Not Allowed (HEAD): /api/index/ From this error, I think that the resulting json response from the api might be the problem, since some of these items are kind of nested into the resulting json Here's an example response: random Any ideas? -
You may need to add u'127.0.0.1' to ALLOWED_HOSTS
I am getting the following error when I am trying to start my Django server python manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). August 18, 2019 - 20:47:09 Django version 1.11, using settings 'config.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. [18/Aug/2019 20:47:09] "GET /view/stockprice/ HTTP/1.1" 400 16918 [18/Aug/2019 20:47:09] "GET /view/stockprice/ HTTP/1.1" 400 16918 [18/Aug/2019 20:47:09] "GET /view/stockprice/ HTTP/1.1" 400 16918 Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add u'127.0.0.1' to ALLOWED_HOSTS. I have already given 127.0.0.1 in the list of ALLOWED_HOST. SECRET_KEY=BeatTheStreet DEBUG=True ALLOWED_HOSTS=['127.0.0.1', '0.0.0.0'] EVENT_STARTED=True EVENT_ENDED= # Production database details DB_NAME= DB_USER= DB_PASSWORD= DB_HOST= DB_PORT= Pointers to fix this will really help. I am running server with 0.0.0.0:8000 because of issue I had in Django … -
How to change the default Django page to my own one?
I'm learning Django,and I followed a guidebook.I want to change the default Django page into my own one.It has took me 2 hours to solve this,and nothing worked. The project is called learning_log,and the app is called learning_logs. Here's what I'm trying to do: 1.add module learning_logs.urls: """ Definition of urls for learning_log. """ from datetime import datetime from django.urls import path from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView from app import forms, views #added from django.conf.urls import include, url import learning_logs.views from django.urls import path,re_path app_name='learning_logs' urlpatterns =[ path('', views.home, name='home'), path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('login/', LoginView.as_view ( template_name='app/login.html', authentication_form=forms.BootstrapAuthenticationForm, extra_context= { 'title': 'Log in', 'year' : datetime.now().year, } ), name='login'), path('logout/', LogoutView.as_view(next_page='/'), name='logout'), path('admin/', admin.site.urls), #added re_path(r'',include('learning_logs.urls',namespace='learning_logs')) ] To include the module,I've tried: url(r'',include('learning_logs.urls',namespacec='learning_logs')) path('',include('learning_logs.urls',namespacec='learning_logs')) path('',include('learning_logs.urls')) path('',learning_logs.urls) path('',learning_logs.views) But none of them worked. 2.Create urls.py in learning_logs.here's the code: """define learning_logs's url mode""" from django.urls import path,re_path from . import views from django.conf.urls import include,url urlpatterns=[ #homepage: re_path(r'(?P^$)',views.index,name='index')] #path('',include('learning_logs.views.index'))] As you can see,I also tried many times. 3.Write views.py in learning_logs from django.shortcuts import render # Create your views here. def index(request): """homepage of learning logs""" return render(request,'learning_logs/index.html') 4.write HTML document in learning_logs/templates/learning_logs/index.html code … -
Django Tutorial and Sqlite command line
I am going through the Django tutorial at https://docs.djangoproject.com/en/2.2/intro/tutorial02/ It had said previously that if I use sqlite that I don't need to install anything. Now, it says, after I migrate, ," If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created. " Am I supposed to have a command line editor for sqlite already or do I need to go fetch something from the web? If the latter, what do I get? If the former, what is the command to start it up? -
Angular8: Call localhost Rest Api services
I developed my web application with Angular 8. The backend is a rest api that I developed with django rest framework and it's viewed just in the localhost. I tested it and it works fine. For example the service http://127.0.0.1:8000/api/devices gives a list of devices. It gives a good results if I test it with browser or curl command. I'm calling this service from my angular app. I executed the angular app with the command: ng serve --host 0.0.0.0 --port 4201 If I open the web application in the browser with http://127.0.0.1:4201/api/devices the service /api/devices is well called and I get the list of devices in my web page. but if I open the web application with my LAN IP address like that http://192.168.1.59:4201/api/devices, so I get HTTP 400 bad request error in my console. And the same error is shown in django server traces: "GET /api/devices/ HTTP/1.1" 400 26 After some searches in the internet I concluded that this error is frequently coming from angular app especially the proxy: my proxy config file proxy.config.json is: { "/api" : { "target": "http://localhost:8000", "secure": false } } I mad other searches and I found an answer to similar question Angular 6 … -
scroll down button changes url django
I am working on a django website which contains a button at the top of the page, which when clicked should scroll down. The button is enclosed in an anchor tag, with a specified href attribute. When I click the button the program alters the url, resulting in a 404 error. How do I code this to ensure that the url is not affected when the button is clicked? This is my code so far <a class="scroll_down_button" href='.second_part'>click</a> <div class="second_part"> This is a test </div> This is the error I am getting Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/.second_part -
Hotel Reservation system in Django: How to make a room unavailable to other users for a period of time
I am building a hotel reservation system for my a-level coursework and my problem is when a user books a room I want to make sure no other user can reserve that room for the duration of the time period that the room is occupied. I tried using iteration to loop over the dates and have a boolean value that is set to true when the room is reserved and false when it is not. Here is my models class Room(models.Model): name = models.CharField(max_length = 200) img = models.ImageField(upload_to='Pictures') desc = models.TextField() price = models.IntegerField() is_reserved = models.BooleanField(default=False) number_of_people = models.PositiveIntegerField() def __str__(self): return self.name class Meta: verbose_name = 'Room' verbose_name_plural = 'Rooms' class Reservation(models.Model): check_in = models.DateField(default=timezone.now) check_out = models.DateField() room = models.ForeignKey(Room, on_delete = models.CASCADE) guest = models.ForeignKey(User, on_delete= models.CASCADE) class Meta: verbose_name = 'Reservation' verbose_name_plural = 'Reservations' This is my function in views where it will loop over the checkin and check out dates inputted by the user and make sure that no other user can reserve that room for those dates def confirm(request, pk = None): if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) guest_id = request.user check_in = request.session['check_in'] check_out = request.session['check_out'] … -
What does 'group_list' object has no attribute 'object' mean?
I want to create listview and createview on the same screen, but I do not understand the meaning of the current error "'group_list' object has no attribute 'object'". I tried to create it on the basis of createview, but the list was confused. I also tried to create and inherit the createview and listview classes, but the same error occurred. #error 'group_list' object has no attribute 'object' #forms class GroupRequestForm(mixins.BaseModelForm): class Meta: model = belong fields = ('group',) #view class group_list(ListView,ModelFormMixin): model = group form_class = GroupRequestForm template_name = 'group/group_list.html' context_object_name = 'group_list' queryset = group.objects.all() def form_valid(self, form): group_pk = self.kwargs['pk'] comment = form.save(commit=False) comment.post = get_object_or_404(group, pk=group_pk) comment.save() return redirect('app:detail_and_create', pk=group_pk) def post(self, request, *args, **kwargs): self.object = self.get_object() # assign the object to the view form = self.get_form() if form.is_valid(): return self.form_valid(form) else: self.object = self.get_object() return self.form_invalid(form) # class group_list(CreateView,): # form_class = GroupRequestForm # template_name = 'group/group_list.html' # success_url = reverse_lazy('group:group_list') # # def get_context_data(self, *, object_list=None, **kwargs): # context_data = super(group_list, self).get_context_data(**kwargs) # context_data['group_list'] = group.objects.all() # return context_data # # def form_valid(self,form): # user = self.request.user # # POST.get('user_id') # form.instance.user = user # return super().form_valid(form) # class group_list(ListView): # model = group … -
ValueError: invalid literal for int with base 10: ' '
I am getting following error when I am trying to start the Django server. python manage.py runserver 0.0.0.0:8000 Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/core/management/init.py", line 307, in execute settings.INSTALLED_APPS File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/conf/init.py", line 110, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/python/python-2.7/lib64/python2.7/importlib/init.py", line 37, in import_module import(name) File "/u/agrawalo/beatthestreet/beatthestreet/config/settings.py", line 96, in 'PORT': config('DB_PORT', cast=int), File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/decouple.py", line 197, in call return self.config(*args, **kwargs) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/decouple.py", line 85, in call return self.get(*args, **kwargs) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/decouple.py", line 79, in get return cast(value) ValueError: invalid literal for int() with base 10: '' Content in .env SECRET_KEY=BeatTheStreet DEBUG=False ALLOWED_HOSTS=['*'] EVENT_STARTED=True EVENT_ENDED= # Production database details DB_NAME= DB_USER= DB_PASSWORD= DB_HOST= DB_PORT= -
How to fix form fields not appearing in html/django?
I'm very new to Django and was following a tutorial on creating a user registration page. However, when I run the server the form fields don't appear and only the submit button is there. I looked through many tutorials and tried to change the UserForm class thinking that that was the problem but I get the same issue. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ["username", "email", "password"] views.py ... class UserFormView(View): form_class = UserForm template_name = 'static/register.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {"form":form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): #creates an object frm the form but doesnt save it into the database user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns object if credenials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('main:homepage') return render(request, self.template_name, {"form":form}) urls.py from django.urls import path from . import views from django.conf.urls import url, include app_name = "main" urlpatterns = [ path("", views.homepage, name="homepage"), path("register/", views.UserFormView.as_view(), name='register'), ] register.html {% extends 'static/header.html' %} {% block content %} <br> … -
Google Search using python
I get data from input. When I click to search button I need to open webbrowser page and see my input data in google. How can I do that? Many thanks. This is my code: views.py: from django.http import HttpResponse from django.shortcuts import render def index(request): if request.method == 'GET': return render(request, 'index.html', context={}) # Handles the search once the submit button in the form is pressed # which sends a "POST" request if request.method == 'POST': # Get the input data from the POST request search_query = request.POST.get('search', None) # Validate input data if search_query and search_query != "": return HttpResponse(search_query) try: from googlesearch import search except ImportError: print("No module named 'google' found") for j in search(search_query, tld="co.in", num=10, stop=1, pause=2): print(j) else: return HttpResponse('Invalid input.') index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <body> <form method="POST"> {% csrf_token %} <input type="text" name="search" placeholder="some text"><br> <button class="button" name="submit" type="submit">Search</button> </form> </body> </html> urls.py from django.urls import path from firstapp import views urlpatterns = [ path('', views.index, name='home') ] All files are in hello folder. My app namely firstapp path: C:\Users\user\Desktop\hello\firstapp index.html path is: C:\Users\user\Desktop\hello\firstapp\templates -
Django not saving form data
I've made a simple test django project that's a simple list of posts. And I'm trying to add functionality to update a post. Everything seems to be working, except the edits aren't saved to the database. I've checked the cleaned data to see if the updated data is coming through, and it is, but the save() function doesn't seem to actually do anything. models.py class Block(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=140, null=True, blank=True) content = models.TextField() def save(self, *args, **kwargs): if self.slug is None: self.slug = get_unique_slug(self, 'title', 'slug') super().save(*args, **kwargs) def get_absolute_url(self): return reverse("bulkapp:one_view", kwargs={"slug_id": self.slug}) def __str__(self): return self.title views.py def edit_block_view(request, slug_id): single_block_query = get_object_or_404(Block, slug=slug_id) update_form_query = BlockForm(request.POST or None, instance=single_block_query) if update_form_query.is_valid(): update_form_query.save() return redirect('bulkapp:one_view', slug_id=slug_id) return render(request, 'bulkapp/update.html', {'update_form': update_form_query}) <form class="form-container" method="POST"> {% csrf_token %} {{update_form.as_p}} <input type="submit" value="Edit"> </form> The redirect fires as expected, but no changes are saved, and no error messages are written to the console. Any help would be much appreciated. -
How to save Django QuerySet directly into redis?
I'd like to save results of Django QuerySets directly into redis instead of using built in cache.set and cache.get. The reason is that I'd like to use a separate redis db for certain queries to accelerate data retrieval. Here is my sample code: def cached_post(id): r = redis.StrictRedis(unix_socket_path='/var/run/redis/redis.sock', db=6) key = "tpcpots:" + id if not r.get(key): post = Post.objects.get(pk = id) r.set(key, post, AN_HOUR) return r.get(key) But I get this error: cannot concatenate 'str' and 'long' objects How can I fix this? -
How to set custom rates, for throttling in django rest framework?
I'm using DRF for throtlling, according to the document I can choose one of these options for my rate : second, minute, hour, or day. But the problem is, that I want a custom rate, for example, 3 requests per 10 minutes. Is it possible in DRF ? -
What is the standard or the best way to filters using boolean field and retrieve the resources accordingly?
I have a use case where I want to list the resources(posts) based on the filters applied which are all, active and inactive. There is a flag in the Django post model which has is_active status. I want to know what is the best way to design the API contract for this filter. The list post API is a POST API call. Context below: Filters in UI (Multiple Checkbox): All Active Inactive If all is selected, then select both Active and Inactive. Ideal Output: If all is select, then show the list the posts irrespective of the statuses. If None are selected, then show the list the posts irrespective of the statuses. If either Active or Inactive is selected, then list the posts with respect to that. class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) is_active = models.BooleanField(default=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title The approach is to have a flag as status in post API and values can be true, false, null. { ... "status": true, ... } Approaches are: if the status is true, then list only post with true status. if the … -
I Have a problem with django2.2 and django-tastypie
I have this problem: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Hide empty values with prefetch-object
I want to hide all "delivery"-objects when there is no package in it. prefetch = Prefetch('packages',queryset=Package.objects.filter(status = "open",order__producttyp = request.POST['products'])) queryset = Delivery.objects.annotate(num_packages = Count('packages')).filter(num_packages__gt=0).prefetch_related(prefetch) I would like to get a queryset object which I can iterate over in my template without having a lot of "empty Deliveries". At the Moment the result looks like: DeliveryInstance 1.1. Package 1.2. Package DeliveryInstance DeliveryInstance DeliveryInstance 4.1. Package 4.2. Package -
How to update data in database table using conditional expression
I want to update my data in my database table only if conditional expression work. I have a dictionary called result_total which is continuously updated. Using for loop condition I want to update my data. For example: if result_total[news_item][2] is equal to any of my database table entries then result_total[news_item][2] will not be updated for news_item in result_total: if Haberler.objects.get(haber_link=result_total[news_item][2]): Haberler.objects.filter(sira_no=news_item).update( haber_id=result_total[news_item][0], haber_baslik=result_total[news_item][1], haber_link=result_total[news_item][2], haber_imagelink=result_total[news_item][3], haber_text=result_total[news_item][4] ) error messages shows following "Haberler matching query does not exist." -
Is it possible to query a database based on it's __str__?
Let's say theoretically I have these 3 models: class Cable(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.IntegerField(choices=choices.cableTypes, default=1) notes = models.TextField(blank=True) length = models.DecimalField(decimal_places=2, max_digits=6) def __str__(self): return str(self.get_type_display()) + " Cable, " + str(self.length) + "m" class Adapter(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) adaptFrom = models.IntegerField(choices=choices.connectors, default=1) adaptTo = models.IntegerField(choices=choices.connectors, default=1) notes = models.TextField(blank=True) length = models.DecimalField(decimal_places=2, max_digits=6) def __str__(self): return str(self.get_adaptFrom_display()) + " to " + str(self.get_adaptTo_display()) class Fixture(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.IntegerField(choices=choices.fixtureTypes, default=1) model = models.CharField(blank=False, max_length=128) manufacturer = models.CharField(blank=False, max_length=128) notes = models.TextField(blank=True) def __str__(self): return str(self.manufacturer) + " " + str(self.model) Is it possible to query these models based on the string they return? If not, how would I go about doing something similair to it? The reason I need to do this is because I have a parent model called item (which is where all of these models get their primary keys from) but I still need to implement a search function to my website. Here is my current way of doing it, which is a bit messy: results = [] form = SearchForm(request.POST) if form.is_valid(): for category in Type.objects.all(): for item in Item.objects.all(): if item.type == category: model …