Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to restrict int field in fucntion queryset
How can I restrict rating field to exactly to +1. Now it goes up to +2, +3, +4. My model field: rating = models.SmallIntegerField(default=0, validators=[MinValueValidator(-1), MaxValueValidator(1)]) My function: def add_like(obj, user): obj_type = ContentType.objects.get_for_model(obj) like = Like.objects.update_or_create(content_type=obj_type, object_id=obj.id, user=user) Like.objects.filter(content_type=obj_type, object_id=obj.id, user=user).update(rating=F('rating') + 1) return like -
making link short in django pagination
I have multiple params in GET request which i'm passing through-out pagination.(i mean pass params in pagination's link). Following code in my pagination link. <a class="waves-effect page-link" href="?page={{ page_obj.previous_page_number }}{% if search == none %}{%else%}&search={{search}}{%endif%}{% if filter_property == none%}{% else %}&filter_property={{filter_property}}{% endif %}{% if overseas %}&overseas={{overseas}}{% endif %}{% if rtc %}&rtc={{rtc}}{% endif %}{% if rbc %}&rbc={{rbc}}{% endif %}" aria-label="Next"> Next</a> is there any solution where i can make it short and batter through pythonic way? Thanks in advance. -
How to create a XML-RPC api with Django
I need to create a XML-RPC API with Django, I check xmlrpc docs but I didin't found a way to integrate the server with Django and also I can't find any resource that may can help me with this. Any suggestion or resource to acomplish this would be great. -
Summing up multiple class Def function to get total amount in Django models
I've gone through questions relating to my question, but none is pointing to what I've in mind. I've different class model, with def functions. I can achieve the total amount for each model, but what I want to achieve is, after getting the total amount for each model, how can I sum to models together, to get my total amount for all the models. Below are my code class HomeOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) home_ordered = models.BooleanField(default=False) item = models.ForeignKey(HomeItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def get_total_item_price(self): return self.quantity * self.item.home_price def get_total_discount_price(self): return self.quantity * self.item.home_discount_price def get_final_price(self): if self.item.home_discount_price: return self.get_total_discount_price() return self.get_total_item_price() class HomeOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) home_items = models.ManyToManyField(HomeOrderItem) date_created = models.DateTimeField(auto_now_add=True) ordered_created = models.DateTimeField() home_ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total_everything(self): total = 0 for order_item in self.home_items.all(): total += order_item.get_final_price() return total class MenOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) men_ordered = models.BooleanField(default=False) item = models.ForeignKey(MenItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def get_total_item_price(self): return self.quantity * self.item.men_price def get_total_discount_price(self): return self.quantity * self.item.men_discount_price def get_final_price(self): if self.item.men_discount_price: return self.get_total_discount_price() return self.get_total_item_price() class MenOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) men_items = models.ManyToManyField(MenOrderItem) date_created = models.DateTimeField(auto_now_add=True) ordered_created = models.DateTimeField() men_ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total_men_everything(self): … -
Using fetch() to dynamically update objects rendered on HTML page?
I am developing a dictionary app using Django. I have a bookmarks page that lists bookmarked definitions. Every bookmarked definition has a button to remove the bookmark. My problem is that when I remove the bookmark from a bookmarked definition it does not go away from the bookmarks page until I refresh the page. In bookmark.js, am trying to call fetch() after I remove the bookmark from the definition to "reload" or "update" the content of the page dynamically: function bookmark(event) { // Get definition id. let id = event.target.id.split("-")[1]; // Add/remove bookmark to definition. $.get("/bookmarks/bookmark/" + id, function (data) { if (data.added) { alert('Definition added to your bookmarks.') event.target.innerHTML = 'Remove definition from your Bookmark'; } else if (data.removed) { alert('Definition removed from your bookmarks.') event.target.innerHTML = 'Add definition to your Bookmarks'; } }); // Get updated list of bookmarks. fetch('/bookmarks/') // <---------------- PROBLEM } $(window).on("load", () => { $(".bookmark-btn").each(function (index) { $(this).on("click", bookmark); }); }); This is my views.py: # URL: /bookmarks/ class BookmarksView(generic.ListView): """Lists bookmarked definitions.""" model = Definition template_name = "bookmarks/bookmarks.html" def get_context_data(self, **kwargs): language = get_language() bookmarks = self.model.objects.filter(language=language, is_bookmarked=True) context = super().get_context_data(**kwargs) context["bookmarks"] = bookmarks.order_by("-publication_date") return context # URL: /bookmarks/bookmark/definition_id def bookmark(request, definition_id): """Toggles … -
Running custom Django command from Apache
Objective I'm trying to deploy my application in Django to Apache on a raspberryPi to be able to access my website from another PC connected to the same wifi. Setup Apache As for now I have the following Apache default config file /etc/apache2/sites-available/000-default.conf <VirtualHost *:443> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName www.example.com ServerAdmin webmaster@localhost #DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. LogLevel info debug ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line … -
Where I have to write bulk_create function If I want to insert the data into database in Django app? In which file
I have to check the infinite scroll of post news. And I need to bulk_create a lot of empty news. But I don't know where I have to write the code in order to insert the data into database I think with for loop. Thank you! -
Django display a png created with a view
I am currently working on a project on which I want to build a website where you can enter any URL. With clicking on a button you should get a screenshot of this requested website. Furthermore, there is another button that modulates this png into an RGB-image. For a few days, I have a problem, that the screenshot is generated but not displayed anymore on my website, while there is still an old image displayed. This is my HTML-template. <h1> CovertCast </h1> <form action="" method="post"> {% csrf_token %} <label>url: <input type="url" name="deine-url" value="https://"> </label> <button type="submit">Get Screenshot</button> </form> {% load static %} <img src="/media/screenshot_image.png" class="bild"/> <form action="/modulated.html" method="post"> {% csrf_token %} <button type="submit">Modulate</button> </form> <img src="/media/modulated_image.png" alt="abc"/> My function view looks like this: def screenshot(request): DRIVER = 'chromedriver.exe' if request.method == 'POST' and 'deine-url' in request.POST: url = request.POST.get('deine-url', '') if url is not None and url != '': options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-ssl-errors') driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get(url) img_dir = settings.MEDIA_ROOT img_name = ''.join(['screenshot', '_image.png']) path = os.path.join(img_dir, img_name) if not os.path.exists(img_dir): os.makedirs(img_dir) driver.save_screenshot(path) screenshott = img_name driver.quit() return render(request, 'main.html') else: return render(request, 'main.html') def modulate(request): with open('screenshot_image.png', 'rb') as image: f = image.read() a = bytearray(f) w = … -
why tests are not using test-database in testing django-rest-framework API? in this API there is another api call
tests.py from rest_framework import status from django.urls import reverse from rest_framework.test import APITestCase lass LoginTestCase(APITestCase): def test_sent_forgot_pass_code_and_checkmail(self): response = self.client.put( reverse('create_token'), # /login/ data={ 'username': self.gmail_user } ) self.assertEqual(response.status_code, status.HTTP_200_OK) you see I am using APITestCase in tests. views.py from rest_framework.reverse import reverse from rest_framework import status, generics from rest_framework.response import Response import requests from common.utils import get_abs_url class CognitoViews(generics.GenericAPIView): def put(self, request, *args, **kwargs): print(request.data) username = request.data.get('username') username = username.replace(" ", "") reset_pwd_payload = { "email": username } reset_pwd_request = requests.post( get_abs_url(request, reverse('reset-password-request')), #/password/ data=reset_pwd_payload, allow_redirects=False) if reset_pwd_request.status_code == 200: response_data = {'message': 'Code Sent.'} status_code = status.HTTP_200_OK else: response_data = {'message': 'Error sending the code.'} status_code = status.HTTP_401_UNAUTHORIZED return Response(response_data, status=status_code) here in this view there is another api call which is using python requests package which I think causing the problem. common/utils def get_abs_url(request, url): host = request.get_host() if not settings.DEBUG: return '{0}{1}{2}'.format('https://', host, url) else: return '{0}{1}{2}'.format('http://', host, url) when I run this test I get this error: File "/home/bilal/codebase/django-backend/.venv/lib/python3.7/site-packages/requests/adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='testserver', port=443): Max retries exceeded with url: /password/ (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fa3c9aa5990>: Failed to establish a new connection: [Errno -2] Name or service not known')) … -
Django Localhost Redirecting too many times
Hi there I created a decorator to protect a certain view from unauthorized persons though I am using django allauth to handle my authentications so I've used its login url. On testing whether the authorization works instead of redirecting me to the login page Localhost gets stuck in a redirect loop here is a look at my code decorators.py from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import user_passes_test def seller_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='account_login'): ''' Decorator for views that checks that the logged in user is a seller, redirects to the log-in page if necessary. ''' actual_decorator = user_passes_test( lambda u: u.is_active and u.is_seller, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator views.py from django.views.generic import CreateView,DetailView, ListView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from .decorators import seller_required @method_decorator( seller_required , name='dispatch') class SellerDashBoardView(ListView): model = Seller template_name = 'seller_dashboard.html' App level urls from django.urls import path from .views import SellerSignUpView, SellerDashBoardView urlpatterns = [ path('seller_reg/', SellerSignUpView.as_view(), name='seller_reg'), path('seller/', SellerDashBoardView.as_view(), name='seller_dash') ] project level urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('user.urls')), #path('users/', include('django.contrib.auth.urls')), path('accounts/', include('allauth.urls')), path('', include('pages.urls')), path('store/', include('store.urls')), #path("djangorave/", include("djangorave.urls", namespace="djangorave")), … -
Django-filters how to create dynamically filterset_fields
I wrote a viewset, which depends on the endpoint: ALLOWED_ENTITIES = { 'persons': [Person, PersonSerializer, '__all__'], 'locations': [Location, LocationSerializer, ('country', 'city', 'street')], 'institutes': [Institute, InstituteSerializer, ('number', 'name_short', 'mail_domain')], } class EntityViewSet(viewsets.ModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = '__all__' #should be ALLOWED_ENTITIES[self.kwargs['entity_name']][2] def get_queryset(self): model = ALLOWED_ENTITIES[self.kwargs['entity_name']][0] return model.objects.all() def get_serializer_class(self): serializer = ALLOWED_ENTITIES[self.kwargs['entity_name']][1] return serializer urls.py: urlpatterns = [ path('', RedirectView.as_view(url=reverse_lazy('aim:api-root'))), url(r'^api/(?P<entity_name>\w+)', EntityListView.as_view({'get': 'list'})), url(r'^/admin/', admin.site.urls), ] and it works as expected, when i go to /api/persons it shows me viewset with Person Model and PersonSerializer. But the problem, that i dont know how to define filterset_fields = ALLOWED_ENTITIES[self.kwargs['entity_name']][2] and i can not use filterset_fields = '__all__' because i get the following error: Unsupported lookup 'icontains' for field 'aim.Department.parent'. where 'aim.Department.parent' is ForeignKey. Perhaps someone knows how to dynamically define filterset_fields. Thank you in advance. -
DJANGO POST GET not working after i18n translation
I have multiple POST requests from my template for example: $.ajax({ url: '/apply_payment', type: 'POST', data: { basket: JSON.stringify(basket), key: $('#key_input').val(), csrfmiddlewaretoken: CSRF_TOKEN }, dataType: 'json', success: function (data) { $("#key_input").val(""); }, ... I read in the basket data in a view.py like this: basket = request.POST.get('basket', '') In the urls.py I have these urls in the form of: path('apply_payment', entrance_api.apply_payment, name='apply_payment'), Now lately I added i18n_patterns into the URLs, and translated all of my pages, however the AJAX calls stopped working. I guess it is becase the URLs are dynamically changing between selected languages, but I might be wrong. For example the shows basket variable is always None in the view now. How can I fix this? -
Django - create new Objects when new user is registered
I am working on a bet app / guessing app. The user can bet on all NFL games and guess the correct result. So I made 4 Models (2 relevant for my current problem): class Customer(models.Model): name = models.ForeignKey(User,on_delete=models.CASCADE) points = models.IntegerField(null=True, default=0) class Tipp(models.Model): # model for one gameday (17 gamedays at all) user = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) week = models.ForeignKey(Game, on_delete=models.CASCADE, null=True, blank=True) result_hometeam1 = models.IntegerField(null=True, blank=True) result_guestteam1 = models.IntegerField(null=True, blank=True) ... So there are 16 games every week the user can bet. For this I created a form and implement in the template: class Tipp_form(ModelForm): class Meta: model = Tipp fields = '__all__' # views.py def week(request, pk): game = Tipp.objects.get(id=pk) form = Tipp_form(initial={'user':request.user, 'week':game}, instance=game) if request.method == 'POST': form = Tipp_form(request.POST, instance=game) if form.is_valid(): form.save() return render(request, 'main/week.html', { 'game': game, 'form': form, }) everything is working perfectly but now if a new user register I dont want to create 17 new weeks with 16 games every gameday! Is there a way to say: if a new user is logged in, create 17 new objects in Tipp and set user = new User? -
django filters.py @property def qs user
I am trying to filter the associated_portfolios fields object to only those created by the user. Which worked before I tried to add pagination (which is working if I remove the current filter I have for associated_portfolios) I believe what I need to do is remove: def associated_portfolios this is because it seems request is not past with the new setup. Instead, I should use this method https://django-filter.readthedocs.io/en/stable/guide/usage.html#filtering-the-primary-qs filters.py current; not working after adding pagination def associated_portfolios(request): associated_portfolios = Portfolio.objects.filter(user=request.user) return associated_portfolios.all() class TradeFilter(django_filters.FilterSet): associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios) date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['status', 'type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] filters.py possible solution based on documentation class TradeFilter(django_filters.FilterSet): date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['status', 'type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] @property def qs(self): parent = super().qs user = getattr(self.request, 'user', None) return parent.filter(user=user) The problem is the is no error message but the objects not created by the user are still showing. Tried probably a dozen + variations of this @property from what I've seen on SOF and the docs but no success yet.. views.py class FilteredListView(ListView): filterset_class = None def get_queryset(self): # … -
MultiValueDictKeyError at /search/
views.py def search(request): query=request.GET['origin'] if request.method=='GET': if query is not None: flightsearch=flight.objects.filter(origin_icontains=query) return redirect('searchresult/') return render(request,'search.html') // search.html {% csrf_token %} <div class="row"> Origin: <div class="col"> <div class="input-field col s10 m6"> <select style="display: inline; width: 250px; height: 30px;" name="origin" > <option value="" disabled selected>Choose Source</option> {% for ori in flight %} <option value="{{ori.id}}">{{ori.origin}}</option> </select> </div> </div> </div> -
Django query is very slow - filter and order by DATE, multiple additional filters
In my Django app, a UserProfile subscribes to many Artists (M2M) through a Subscription table (OneToOne with each). An Artist has an M2M relationship with Releases. I'm trying to display the relevant releases to to users, these should be: released within the last month (release date range: [month_ago, now]) from an artist the user follows have a type field that is in the user's wanted_type They should be distinct, and ordered by their release date. I have an index on Release.release_date (notice: DateField, not DateTimeField). This query is taking quite a long time. Often more than 10 seconds. Here's how I'm doing it: # notice: some model names are actually different in the database, they do match in actual code # selectors.py def get_releases_for_profile(profile: UserProfile): profile_wanted_types = profile.get_release_types() profile_art_ids = profile.subscription_set.all().values_list("artist__id") releases = Release.objects.filter( artist__id__in=profile_art_ids, type__in=profile_wanted_types ) return releases # views.py day_offset = 30 delta = timedelta(days=day_offset) past_delta = now - delta profile_rgs = selectors.get_releases_for_profile(profile=current_profile) past_month_releases = ( profile_rgs.filter(release_date__range=[past_delta, now]) .order_by("-release_date") .distinct() .prefetch_related("artist_set") ) context["past_month_releases_count"] = past_month_releases.count() context["past_month_releases"] = past_month_releases[:20] If I dump PostgreSQL's cache with sync && sudo purge to avoid calling it from the cache, this takes anywhere from 10-14 seconds. Debug toolbar is showing me these related … -
Date field dont autofill value Django
My browser (chrome and firefox) doesn`t autofill my Datefield, but in safari working example I inspected my html HTML field have value my view.py def get(self, request, slug): order = get_object_or_404(Order, order_number=slug) form = DirectorForm(instance=order) return render(request, 'edit_order.html', context={'form': form}) my forms.py widgets = {'order_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})} -
Setting Up Category and Forum and Loop it
I'm creating a forum software in Django and I'm having a hard time figuring out how to relate the forums table to the categories. I want to display this to the index page: Category 1 --forum 1 --forum 2 --forum 2 Category 2 --forum 1 --forum 2 --forum 3 These are my models: class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Forum(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='forums') def __str__(self): return self.name Here are my views: class HomeView(ListView): context_object_name = 'name' template_name = 'index.html' def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) context['forums'] = Forum.objects.all() context['categorys'] = Category.objects.all() return context This is what I currently have on the home page, the only problem is, it's simply looping through all the categories and forums. I want the category to be looped in the first for loop, and in the second one to pull all the forums that belong to that category. {% for category in categorys %} --code {% for forum in forums %} --code {% endfor %} {% endfor %} How do I fix this so that it displays properly and the relation is correct? A category can have many forums but … -
How to set initial data in a FormMixin and DetailView
I want to create a comment form using generic foreignkey, but a having troubles with getting the initial data for object_id and content_type in the form ? class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type= models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object= GenericForeignKey() parent= models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE) content = RichTextField() time_stamp = models.DateTimeField(auto_now_add=True) Forms.py class CommentsForm(forms.ModelForm): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) content = forms.CharField(widget=forms.Textarea(attrs={ 'class':'form-control', 'cols':'4', 'rows':'3' })) class Meta: model = Comment fields = ['content','user','object_id', 'content_type'] Views.py class SongDetail(FormMixin, DetailView): model = Song form_class = CommentsForm def post(self, request, *args, **kwargs): obj = self.get_object() if not request.user.is_authenticated: return redirect('music:obj.get_absolute_url()') if form.is_valid(): form.save() return self.form_valid(form) -
No module named Crypto.Cipher Open EdX
Tried to import this code to our edx site encrypt data in python but it requires a package which is pycryptodome. Tried installing it using: pip install pycryptodome but it still shows an error everytime I call from Crypto.Cipher import AES . WARNING:enterprise.utils:Could not import Registry from third_party_auth.provider WARNING:enterprise.utils:cannot import name EnterpriseCustomerUser Traceback (most recent call last): File "./manage.py", line 120, in <module> startup.run() File "/openedx/edx-platform/cms/startup.py", line 19, in run django.setup() File "/openedx/venv/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/openedx/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 116, in populate app_config.ready() File "/openedx/edx-platform/cms/djangoapps/contentstore/apps.py", line 22, in ready from .signals import handlers # pylint: disable=unused-variable File "/openedx/edx-platform/cms/djangoapps/contentstore/signals/handlers.py", line 12, in <module> from contentstore.proctoring import register_special_exams File "/openedx/edx-platform/cms/djangoapps/contentstore/proctoring.py", line 19, in <module> from contentstore.views.helpers import is_item_in_course_tree File "/openedx/edx-platform/cms/djangoapps/contentstore/views/__init__.py", line 9, in <module> from .course import * File "/openedx/edx-platform/cms/djangoapps/contentstore/views/course.py", line 101, in <module> from Crypto.Cipher import AES ImportError: No module named Crypto.Cipher Sorry for a very vague question since I'm not really a python/django/open edx developer and was just tasked to support the project and did some heavy research but still no light. -
Django - Create and add multiple xml to zip, and download as attachment
I am learner, and trying to build code to in which user has option to download the zip file that contains multiple .xlm files, which are created on the bases of database. I have been able to create below code to download single xml file. But struggling to get multiple files packed in zipped format(for each row of database). import xml.etree.ElementTree as ET def export_to_xml(request): listings = mydatabase.objects.all() root = ET.Element('listings') for item in listings: price = ET.Element('price') price.text = str(item.Name) offer = ET.Element('offer', attrib={'id': str(item.pk)}) offer.append(price) root.append(offer) tree = ET.ElementTree(root) response = HttpResponse(ET.tostring(tree.getroot()), content_type='application/xhtml+xml') response['Content-Disposition'] = 'attachment; filename="data.xml"' return response -
Django: Retrieve all details of all Test model instances assigned to a User model
Following is my models.py models: from django.db import models from django.contrib.auth.models import User class Question(models.Model): question= models.TextField() optionA= models.CharField(max_length= 32) optionB= models.CharField(max_length= 32) optionC= models.CharField(max_length= 32) optionD= models.CharField(max_length= 32) answer= models.CharField(max_length= 6, choices= options, default= 'A') class Test(models.Model): name= models.CharField(max_length= 16) questions= models.ManyToManyField(Question) class TestTaker(models.Model): user= models.OneToOneField(User, on_delete= models.CASCADE) tests= models.ManyToManyField(Test) Following is my definition of home function that renders the website home inside views.py def home(request): try: tests= TestTaker.objects.filter(user= request.user).values('tests') print(tests.values) # tests= Test.objects.filter(user= request.user) return render(request, 'tests/home.html', {'tests': tests}) except: print('excepted') return render(request, 'tests/home.html') I want to extract the whole tests that are assigned to a logged in user. I can get only the test objects assigned to an authenticated user, but I want to be able to retrieve the whole of each test, along with it's questions. How can I do that? -
My first django app - how to import templates?
I am creating my first django app in django 3.1.1. There are video tutorials for old django versions and they don't always work... I want to create HTML pages for both home and about sections. I have already written some HTML files, but the def home(request): return render(request, 'home.html') doesn't want to work. I add my file tree for you to see the structure of files. RemoveBigFile ├── RBF1module │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── RemoveBigFile │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ ├── views.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── RemoveBigFile.sublime-project ├── RemoveBigFile.sublime-workspace ├── db.sqlite3 ├── manage.py └── templates ├── about.html └── home.html And that is the error message I get: TemplateDoesNotExist at / home.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.1 Exception Type: TemplateDoesNotExist Exception Value: home.html Django also asks me to put my templates in one of main django installation directories called templates and as far as I … -
how to connect to mongodb atlas through ssh in django
I'm trying to connect to remote mongodb database through ssh. I'm able to do it in Mongodb compass but not in my django project. Can someone please give me the correct configuration -
restrict access to the APIs just with my Android app and my vue.js web app
I'm new to Django Rest Framework. I want to restrict access to the APIs just with my Android app and my vue.js web app, without any user login. What is the standard way for doing this?