Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mocking Django inclusion tag in pytest
I have an inclusion tag: from django import template from accounts.models import UserTracking register = template.Library() @register.simple_tag(takes_context=True) def has_shipped(context): return UserTracking.objects.filter(shipping=True, user=context['request'].user).exists() and I am testing a function, awarded, that is calling a template that contains that tag. from unittest.mock import patch from myproject.views import awarded @patch('myproject.templatetags.something.has_shipped') def test_awarded(mymock, rf): mymock.return_value = '' # this is not having any effect result = awarded(rf) assert result and the code under test: def awarded(request): return render(request, 'awarded_form.html', {'revisions' : revisions}) Pytest is yelling at me because it says I'm using the database, which I am (but don't want to), so I want to mock the function containing the database call, has_shipped. How do I do that? When I try to mock the function directly from where it is declared, it doesn't work, because it's apparently not the right scope, so how do I do this? And is this one of those situations where it's just easier to throw @mark_db on it? -
Error displaying list of registered user profiles in Django app using class based views
I created these two class based views to display the profiles of registered users according to their gender, to an authenticated user. here is the code #views.py class FemaleUserList(LoginRequiredMixin, generic.ListView): queryset = Profile.objects.filter(gender='Female').order_by('-age') template_name = 'users/female_user_profiles.html' context_object_name = 'female_users' paginate_by = 6 class MaleUserList(LoginRequiredMixin, generic.ListView): queryset = Profile.objects.filter(gender='Male').order_by('-age') template_name = 'users/male_user_profiles.html' context_object_name = 'male_users' paginate_by = 6 I know there is a better way to this since am basically repeating myself but then it was working fine with a template tag like this #male_user_profiles.html <div class="py-5 text-center"> {% for profile in male_users %} <div class="card" style="width:600px"> <div class="card-img-top"><img class="rounded-circle" src="{{ user.profile.avatar.url }}" alt="{{ user.username }}" width="300px"></div> <hr> <h3>{{ user.username }}</h3> <div class="card-body"> <p class="lead"> <div class="media-body"> <div class="card-text">BIO: {{ user.profile.bio }}</div> <p>Age : {{ user.profile.age }}</p> <hr> <p>Gender : {{ user.profile.gender }}</p> <hr> <p>Interested In : {{ user.profile.interested_in }}</p> <hr> <p>Studying : {{ user.profile.discipline }}</p> <hr> <p>At : {{ user.profile.campus }}</p> <hr> <p>Relationship Status : {{ user.profile.status }}</p> <hr> <p>Enjoys : {{ user.profile.hobbies }}</p> </div> <a class="btn btn-default" href="{% url 'postman:write' %}"><i class="fa fa-envelope"></i>Start Chat with {{ user.username }}</a> </p> </div> </div> {% endfor %} but now all it does is to list the profile of only the logged in … -
DRF APIView "get() returned more than one Article -- it returned 2"
I use DRF to create an API. I have created a view to articles belonging category. But instead I get an error: get() returned more than one Article -- it returned 2! Here is my view how I try to get articles: class CategoryArticlesListView(APIView): queryset = Article.objects.all() def get(self, request,slug=None, format=None): category = get_object_or_404(Category,slug=slug) articles = category.article_categories.get() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data) and my traceback: Environment: Request Method: GET Request URL: http://localhost:8000/api/article_categories/yoga/list/ Django Version: 3.0.5 Python Version: 3.8.5 Installed Applications: ['baton', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fluent_comments', 'threadedcomments', 'django_comments', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'rest_auth', 'rest_auth.registration', 'django_rest_passwordreset', 'django_filters', 'crispy_forms', 'sorl.thumbnail', 'photologue', 'sortedm2m', 'ckeditor', 'webpack_loader', 'yogavidya.apps.core', 'yogavidya.apps.actions', 'yogavidya.apps.categories', 'yogavidya.apps.filemanager', 'yogavidya.apps.galleries', 'yogavidya.apps.tags', 'yogavidya.apps.articles', 'yogavidya.apps.books', 'yogavidya.apps.locations', 'yogavidya.apps.pages', 'yogavidya.apps.profiles', 'yogavidya.apps.statusses', 'yogavidya.apps.user_messages', 'yogavidya.apps.videolessons', 'baton.autodiscover'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'yogavidya.lang_middleware.ForceDefaultLanguageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/ytsejam/.virtualenvs/tertemiz/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) … -
Is DRF (Django REST Framework) the equivalent to Express in JavaScript?
I'm a beginner-intermediate web developer, but I have a little more experience with JavaScript libraries, frameworks and Backend/Frontend development than Python/Django stuff. As I understand Django is a very Robust framework but I don't understand very well why to use DRF. Is it as express js? I mean, is it for making CRUD operations? Or is for much more than that? -
Static file is not showing in django
I am just learning django with static files.......Here the issue is my image is not loaded in browser its shows just like a icon here is snapshot of output and codes that I am using enter image description hereplz see my images MY codes.. Setitngs.py TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') STATIC_DIR=os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS=[STATIC_DIR,] Blockquote c2.html <!DOCTYPE html> {% load static %} <html <head> </head> <body> <H1> {{ title|upper }} <br> HEllo {{ cname }}</H1> <img src="{% static 'image/i1.png' %}" /> </body> </html> image description : this is what i get instead of full image image when hit url -
403 Forbidden Error when trying to post and put a axios request in a web app using Django and React
I am working on a web application with a backend in Django and a frontend in React. Currently I am able to create articles through my superuser account and list them on the frontend. I am now trying to create and update but I keep getting the following error: xhr.js:184 POST http://127.0.0.1:8000/api/ 403 (Forbidden) Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:69) In my research I believe that the error message deals with csrftoken. I have tried adding the following statements in my axios.post request: xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' And I have tried adding the following statements in my settings.py file: CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] INSTALLED_APPS = [ ... 'corsheaders', ... ] But I still have had zero success. Any help would be much appreciated! Thank you much in advance. import { Form, Input, Button } from 'antd'; import axios from 'axios'; axios.defaults.xsrfHeaderName = "X-CSRFToken" axios.defaults.xsrfCookieName = 'csrftoken' window.axios = require('axios'); /* window.axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('title') }; */ class CustomForm extends React.Component { onFinish = (values, requestType, articleID) => { console.log("Success:", values); const title = (values.title); const content = (values.content); console.log(this.props.requestType); const headers … -
(Django) It's possible to use a generic 'admin/' such as sb-admin bootstrap instead of the original one?
fellows. To answer this question properly you have to have good knowledge on Django Frameworks. I'm about to start this blog using Django, nothing serious, just playing around. All I want to know is if Django path('admin/', admin.site.urls) could be replaced by a generic admin page, such as this one. -
Django user.is_authenticated returns different results in different views
I have an API view (using DJ Rest Framework) that I am posting to via React in my frontend. request.user.is_authenticated returns True here (and returns the user I have attempted to sign-in as), however, in my view for rendering the login page template, request.user.is_authenticated returns False, and the user object is an AnonymousUser. Why is this? I've checked this question, but it only has information on templates. Here's the API view code: @api_view(['POST']) def login_api_view(request, *args, **kwargs): if request.user and request.user.is_authenticated: return Response({'message': 'User is already authenticated'}, status=400) username = request.data.get('username') password = request.data.get('password') if username is None or password is None: return Response({'message': 'Please specify a username and password'}, status=400) user = authenticate(request, username=username, password=password) if user is None: return Response({'message': 'Invalid credentials'}, status=401) login(request, user) return Response({'message': 'Successfully authenticated user'}, status=200) And here's the code for the template: def login_view(request, *args, **kwars): if request.user.is_authenticated: return redirect('/') return render(request, 'users/login.html') -
redirect author to his post after creating it and submitting its form with django
i want to redirect the user to the post after creating it with django forms in models.py class Text(models.Model): title = models.CharField(max_length=200, null=True) document = models.TextField(max_length=None, null=True) requirements = models.TextField(max_length=200, null=True) date_created = models.DateField(auto_now_add=True, null=True) deadline = models.DateField(null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.title in my view.py def text(request, pk): form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): text = form.save() text = Text.objects.get(id=pk) return redirect('text') text = Text.objects.get(id=pk) context = {'form': form, 'text': text} return render(request, 'main/text.html', context) in my forms.py class TextForm(ModelForm): class Meta: model = Text fields = ['title','document','requirements','deadline'] widgets = { 'title' : forms.TextInput(attrs={'placeholder':'Title','class':'form-control m-2 mb-4 pb-2'}), 'deadline' : forms.DateInput(attrs={'placeholder':'Deadline','type':'date','class':'form-control m-2 pt-2', 'id':'opendate'}), 'requirements' : forms.Textarea(attrs={'placeholder':ps_note,'class':'form-control col m-2','rows':'3'}), 'document' : forms.Textarea(attrs={'placeholder':ps_text,'class':'form-control'}), } in my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('text/<str:pk>', views.text, name="text"), path('signin/', views.signin, name="signin"), path('signup/', views.signup, name="signup"), path('logout/', views.logout, name="logout"), ] i had to add this so stackoverflow accepts my question because it said that it's mostly code even after saying all the details. -
how to get selected value detail from dropdown rest framework Django?
i am getting a dropdown menu of books from ManyToMany relation. i want to show the price of selected book from dropdown menu. how to make that type of query in backend if i select any book from dropdown menu then the price and created_on is show on frontend...? models.py class Book(models.Model): name = models.CharField(max_length=20) price = models.IntegerField(null=True) created_on = models.DateTimeField(auto_now_add=True) class Keeper(models.Model): saler_name = models.ForeignKey(User, on_delete=models.CASCADE) books = models.ManyToManyField(Book) serializer.py class BookSerialzer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' class KeeperSerializer(serializers.ModelSerializer): class Meta: model = Keeper fields = ['id', 'saler_name', 'books'] views.py class KeeperCreateApi(CreateAPIView): queryset = Keeper.objects.all() serializer_class = KeeperSerializer def perform_create(self, serializer): serializer.save(saler_name=self.request.user) -
Is channels required to use socket with django? Is there any other alternative or way?
I am using the django framework. I'll do the messaging part. I will do this with the socket. However, I always come across a channel library. Is there no other solution? -
Two lists. How to print members of one and not the other? Django tags
I have a situation where users adds products to Observed and then they can Purchase them. I want to print products that has been added to Observed but not Purchased. Products of name 1 2 3 4 were added to Observed but only 3 4 were Purchased. I want to print 1 2 only. I have little understanding of Django Tags but I aim to solve it, this is my company specific code so please share your thoughts and I might be able to make it work. Here is the code I tried, one of the dozens approaches: {% product_events event_type='add to observation' for_last_days=1 count=5 unique=1 order=-1 in_stock='true' as observe_list %} {% product_events event_type='purchase' for_last_days=1 count=5 unique=1 order=-1 in_stock='true' as purchase_list %} {% for event in observe_list %} {% if event.name not in purchase_list %} {{ event.name }} {% endif %} {% endfor %} -
Cant add slug, in django admin, using pre_save or save() admin form throws error
I have been trying too ad a slug field to my post model, in django. For the slug field i want to use a unique slug function, i have been trying to run it using both signals and overriding the save methods, but in either case the form gets invalidated in the admin page before its changed in the form. The form is invalidated both when slug is empty or when its not unique. Image from the admin rejecting the change My models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from .utils import unique_slug_generator class Post(models.Model): post_type = models.CharField(max_length=100, default='npc') title = models.CharField(max_length=100) slug = models.SlugField(unique=True) description = models.TextField() content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slug_generator(self) return super().save(*args, **kwargs) The signal i was trying instead from django.db.models.signals import pre_save from .utils import unique_slug_generator from django.dispatch import receiver from .models import Post @receiver(pre_save, sender=Post) def pre_save_post_receiver(sender, instance, *args, **kwargs): print("post reciver slug") if not instance.slug: instance.slug = unique_slug_generator(instance) And the unique slug generator i am trying to run from django.utils.text import slugify import random import string def random_string_generator(size=10, chars=string.ascii_lowercase … -
ckeditor_uploader stop working after deploy static files in google cloud storage
i work on a django app and right after i deploy the static files on google clouds the ckeditor and ckeditor_uploader stop working but every other static is working perfectly ckeditor settings : CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { 'default': { 'width': 'auto', 'toolbar': None, }, 'simple': { 'width': 'auto', 'toolbar': [ ['Undo','Redo','Find','Replace'], ['Bold','Italic','Underline','Strikethrough','Subscript','Superscript'], ['Link','Unlink'], ['Blockquote','TextColor'], ['Format','Font','Size'], ['Maximize'] ], }, } static and media and google cloud settings : STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "static/media/") ''' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] ''' # CONFIG # Google BUCKETS CONFIG # google credential from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR,'googlekey.json') ) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = '*****' GS_PROJECT_ID = '******' GS_DEFAULT_ACL = None GS_FILE_OVERWRITE = False GS_LOCATION = '' #MEDIA_URL = f'https://storage.googleapis.com/{GS_BUCKET_NAME}/' i ran 'python manage.py collectstatic' to upload all the files to google cloud if i remove google settings ckeditor run again without google settings with google settings -
AuthCanceled at /complete/azuread-tenant-oauth2/
I am using python social auth https://python-social-auth.readthedocs.io/en/latest/ and Azure backend https://python-social-auth.readthedocs.io/en/latest/backends/azuread.html for o365 login. However after entering all correct credentials i get authentication cancelled My error stack is below: Internal Server Error: /complete/azuread-tenant-oauth2/ Traceback (most recent call last): File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/utils.py", line 251, in wrapper return func(*args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/oauth.py", line 395, in auth_complete response = self.request_access_token( File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/oauth.py", line 373, in request_access_token return self.get_json(*args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/base.py", line 238, in get_json return self.request(url, *args, **kwargs).json() File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/base.py", line 234, in request response.raise_for_status() File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/requests/models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://login.microsoftonline.com/common/oauth2/token During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_django/views.py", line 31, in complete return do_complete(request.backend, _do_login, user=request.user, File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/actions.py", line 45, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/utils.py", line 254, in … -
Problem finding .env with WSGI using Django stack with dotenv
I have a Django app and I'm trying to secure my SECRET_KEY using dotenv. manage.py runserver works just fine but the site hosted with apache2 does not work and apache give me the error log: mod_wsgi (pid=32200): Failed to exec Python script file '/opt/bitnami/projects/accuhx/accuhx/wsgi.py'. mod_wsgi (pid=32200): Exception occurred processing WSGI script '/opt/bitnami/projects/accuhx/accuhx/wsgi.py'. Traceback (most recent call last): File "/opt/bitnami/projects/accuhx/accuhx/wsgi.py", line 23, in <module> application = get_wsgi_application() File "/opt/bitnami/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/bitnami/python/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py", line 196, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I'm assuming this is because my manage.py can find the .env but the wsgi.py cannot, but I have no idea why. My structure: accuhx | |-manage.py |-accuhx | | | |-settings.py |-.env |-wsgi.py WSGI.py: import os import dotenv from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accuhx.settings') application = get_wsgi_application() manage.py def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accuhx.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and … -
Presave form instance in order to use its many-to-many field Django
I am inheriting from CreateView and want to redefine it's form_valid() method so I could manually create relations between two models in my many-to-many field. My class looks like this: class CreateRecipe(CreateView): template_name = 'create_recipe.html' form_class = CreateRecipeForm success_url = reverse_lazy('index') def form_valid(self, form): recipe = form.save(commit=False) recipe.author = self.request.user ingredients = [self.request.POST[name] for name in self.request.POST.keys() if 'nameIngredient' in name] queryset = Ingredient.objects.filter(name__in=ingredients) for obj in queryset: recipe.ingredients.add(obj) slug = slugify(to_lower=True) recipe.Slug = slug(form.cleaned_data['name']) form.save_m2m() return super().form_valid(form) It returns an error which basically says that I first need to assign id to my recipe object before using it's many-to-many field. Isn't form.save(commit=False) what does that? I thought it was equal to: object = MyModel() so that you can assign values to it but it ain't actually saved unlike Model.objects.create(). How can I properly presave form instance to use it's many-to-many field? Thank you. -
Page not found "search/" Django
i'm trying to add a search bar to my project, i installed a Postgresql docker image, when i try to enter to http://127.0.0.1:8000/search/ i get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/search/ Raised by: blog.views.post_detail No Post matches the given query. this is my view: def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Post.published.annotate( search = SearchVector('title', 'body') ).filter(search=query) context = {'form': form, 'query': query, 'results': results} return render(request, 'blog/post/search.html', context) this is my search.HTML (i made it this easy to see if i can enter the page): {% extends "blog/base.html" %} {% block title %}Search{% endblock %} {% block content %} <h1>Search for posts</h1> <form method="get"> {{ form.as_p }} <input type="submit" value="Search"> </form> {% endblock %} this is my urls.py: from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), path('new_post/', views.new_post, name='new_post'), path('<slug:post_slug>/', views.post_detail, name='post_detail'), path('<slug:post_slug>/share/', views.post_share, name='post_share'), path('edit_post/<slug:post_slug>/', views.edit_post, name='edit_post'), path('delete_post/<slug:post_slug>/', views.delete_post, name='delete_post'), path('search/', views.post_search, name='post_search'), ] the problem should be on urls.py i guess, but not sure at all.. -
Is there a way to dynamically add django models/permissions
I have no idea how to solve this. I would like to have users give permissions to other users in a dynamically created "folder". For example, an editor makes a private folder called Newspaper (creates a new private dynamic link /Newspaper with some templates). He edits one of the templates and saves it to the db. He wants another user to be able to check and edit the template or upload new files etc. He gives another user in the app permissions to do so. How do I assign these edit permissions to a person, while the link was dynamically created by another user? Do I need a dynamic model or is there an easy fix? -
Query in production (https) does not work, while query in development server (http) does
When I run this in development the query returns the objects, when I do the same code in production on the server, there is nothing to be found. The development environment is using the same DB. It's weird because other queries on my production site work fine... videofilter = Video.objects.filter(video=video_path) videoId = videofilter[0].id videoName = videofilter[0].name associatedvideo = Video.objects.get(id=videoId) # video is a url: https://s3-us-west-2.amazonaws.com/bucketName/5b732630-bf8c-4fb3-a392-9caaa80b9f33.jpg Is there an issue with https and S3? or is the production environment have rules about queries that are different than development? -
Problems with ElasticSearch integration
I added elasticsearch to my project, and almost everything works, but now I can't add community object through admin panel. When I am trying to do that I am getting strange error related to elasticsearch. I tried to google, but didn't find any useful information. Maybe some of you faced the same problem and know how to fix it. error documents.py community_index = Index('coms') community_index.settings( number_of_shards=1, number_of_replicas=0 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @community_index.doc_type class CommunityDocument(Document): id = fields.IntegerField(attr='id') title = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) class Django: model = communities_models.Community serializers.py class CommunityDocumentSerializer(DocumentSerializer): class Meta: document = communities_documents.CommunityDocument fields = ( 'id', 'title', ) views.py class CommunityViewSet(DocumentViewSet): document = communities_documents.CommunityDocument serializer_class = communities_serializers.CommunityDocumentSerializer lookup_field = 'id' filter_backends = [ FilteringFilterBackend, OrderingFilterBackend, DefaultOrderingFilterBackend, SearchFilterBackend, ] search_fields = ( 'title', ) filter_fields = { 'id': { 'field': 'id', 'lookups': [ LOOKUP_FILTER_RANGE, LOOKUP_QUERY_IN, LOOKUP_QUERY_GT, LOOKUP_QUERY_GTE, LOOKUP_QUERY_LT, LOOKUP_QUERY_LTE, ], }, 'title': 'title.raw', } ordering_fields = { 'id': 'id', 'title': 'title.raw', } ordering = ('id') and here is the apps that I used 'elasticsearch_dsl','django_elasticsearch_dsl','django_elasticsearch_dsl_drf', elasticsearch config ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' }, } -
Having error while installing pip install 'python-decouple'
Collecting python-decouple Using cached python-decouple-3.3.tar.gz (10 kB) Using legacy setup.py install for python-decouple, since package 'wheel' is not installed. Installing collected packages: python-decouple Running setup.py install for python-decouple ... error ERROR: Command errored out with exit status 1: command: 'c:\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple\setup.py'"'"'; file='"'"'C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\slms_\AppData\Local\Temp\pip-record-aljfw6bc\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\python38\Include\python-decouple' cwd: C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple Complete output (16 lines): running install running build running build_py creating build creating build\lib copying decouple.py -> build\lib running egg_info writing python_decouple.egg-info\PKG-INFO writing dependency_links to python_decouple.egg-info\dependency_links.txt writing top-level names to python_decouple.egg-info\top_level.txt reading manifest file 'python_decouple.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'python_decouple.egg-info\SOURCES.txt' running install_lib byte-compiling c:\python38\Lib\site-packages\decouple.py to decouple.cpython-38.pyc error: [Errno 13] Permission denied: 'c:\python38\Lib\site-packages\pycache\decouple.cpython-38.pyc.2802584858032' ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple\setup.py'"'"'; file='"'"'C:\Users\slms_\AppData\Local\Temp\pip-install-awe0dvrf\python-decouple\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\slms_\AppData\Local\Temp\pip-record-aljfw6bc\install-rec -
Pip install commands error ConnectTimeoutError
I am trying to install Django 1.8.11 on my Windows 10 PC, but i am getting this error when run pip install django==1.8.11: Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001CE97C60D68>, 'Connection to xxxx.xxxx.xxx.xx timed out. (connect timeout=15)')': /simple/pip/ (xxxx.xxxx.xxx.xx Is an address that I use as proxy some times) I have Python version: 3.5.4 and pip version: 9.0.1 I have checked proxy settings with netsh winhttp show proxy Current WinHTTP proxy settings: Direct access (no proxy server). I am not behind any corporate proxy My system proxy settings are Automatically detect settings -> ON Use setup script -> OFF Use a proxy server -> OFF Also tried ping pypi.python.org Ping statistics for 151.101.4.223: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 92ms, Maximum = 102ms, Average = 95ms So, I have access to the internet Also i removed temp files If anyone knows where is that xxxx.xxxx.xxx.xx configured so I can remove it, don't know what else to do. -
Stripe Change Database Entry When Trial Ends
I have a database table 'User Memberships' with a column called 'Membership' where the values in that column could either be 'Free', 'Monthly', 'Yearly'. 'Free' is a free non-paying membership while 'Monthly' and 'Yearly' are paid memberships. Username |Customer id|Membership -------------------------------- testuser1|cust_id1 |Free testuser2|cust_id2 |Monthly testuser3|cust_id3 |Yearly When a user has a Stripe trial, I have to manually go into my database and change the user's 'Membership' column value to a paid membership value ('Monthly', 'Yearly') to give them temporary access to paid content. But there is no way to automatically change the database value from either 'Monthly' or 'Yearly' back to 'Free' as soon as the trial ends for that user. There are 2 scenarios where I would give a customer a trial. When they are already paying member and they want to pause payment on their account temporarily (where I do not want to change them back to 'Free' after their trial ends and instead keep them at 'Monthly' or 'Yearly'). Or they are a 'Free' customer and they want to try out the paid service temporarily (where I do want to change them back to 'Free' when their trial ends). I would like it to be done … -
DRF Validation: Unclear Generic Errors
I occasionally get this very generic DRF validation error that doesn't seem to be attached to a particular field. Does anyone know how to debug it, or make it more specific? In more complex serializers it becomes almost impossible to find the root cause. { "required": "This field is required.", "null": "This field may not be null.", "invalid": "Invalid data. Expected a dictionary, but got {datatype}." }