Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google Cloud Run, Django and "no such table" during build
I am following this tutorial to upload my existing Django project running locally on sqlite to Google Cloud Run / Postgres. I have the cloud_sql_proxy service running and can sign into Postgres. I am at the point of running the command gcloud builds submit --config cloudmigrate.yaml \ --substitutions _INSTANCE_NAME=INSTANCE_NAME,_REGION=REGION It runs for a while making good progress but then fails with: Step #2 - "apply migrations": django.db.utils.OperationalError: no such table: registration_setting Finished Step #2 - "apply migrations" ERROR ERROR: build step 2 "gcr.io/google-appengine/exec-wrapper" failed: step exited with non-zero status: 1 I do have a settings table in my registration app. But I don't understand where its missing from. Is this just the first table it's trying to create? Do I have to do something first to have it create the initial tables in Postgres? When I inspect Postgres I don't see any tables created in it. I tried wiping out my migration and pycache folders and recreating them. -
Use django-taggit package with graphene mutations
I'm using the package django-taggit with graphene-django. Initially, I was getting the error specified in this question (Don't know how to convert the Django field skills (<class 'taggit.managers.TaggableManager'>); but thanks to the answers there, I resolved the issue. However, there's another issue! I have the following mixin: class GrapheneRenderTaggitTags: """ Use this mixin to enable graphene-django correctly render django-taggit tags (as a list of strings). The corresponding model of the graphene type using this mixin should have a property `get_tags` that returns the tags of the model (e.g. obj.tags.all()) """ # Make django-taggit's TaggableManager interpretable to graphene @convert_django_field.register(TaggableManager) def convert_field_to_string(field, registry=None): print(field) print("i'm in the taggit parser function") return List(String, source='get_tags') When I use this mixin with the DjangoObjectType from graphene, it works flawlessly. However, when it comes to mutations, it raises the error Don't know how to convert the Django field skills (<class 'taggit.managers.TaggableManager'>) ! By the way, to prevent manually creating CUD mutations, I tried external packages such as graphene_django_extras, graphene_model_mutations, graphene_django_cud; but all of them raise the same error with or without the aforementioned mixin. Note that I get this error only when using the mutation classes provided by these packages. Please, what can I do to … -
How to Make Rest API Views and EndPoint URL of following Django Modol Code
it's my Django Web Code of Friend Request Functionality. We are moving to making RestAPIs of same functionalities in DjangoREST Framework. Confused how to make serializes, urls and API Views in DjangoREST API. Please Help. Code from django.db import models from userAuth.models import UserAuth class FriendList(models.Model): user = models.OneToOneField(UserAuth, on_delete=models.CASCADE, related_name="user") friends = models.ManyToManyField(UserAuth, blank=True, related_name="friends") def add_friend(self, account): """ Add a new friend. """ if not account in self.friends.all(): self.friends.add(account) self.save() def remove_friend(self, account): """ Remove a friend. """ if account in self.friends.all(): self.friends.remove(account) def unfriend(self, removee): """ Initiate the action of unfriending someone. """ remover_friends_list = self # person terminating the friendship # Remove friend from remover friend list remover_friends_list.remove_friend(removee) # Remove friend from removee friend list friends_list = FriendList.objects.get(user=removee) friends_list.remove_friend(remover_friends_list.user) def is_mutual_friend(self, friend): """ Is this a friend? """ if friend in self.friends.all(): return True return False class FriendRequest(models.Model): """ A friend request consists of two main parts: 1. SENDER - Person sending/initiating the friend request 2. RECEIVER - Person receiving the friend request """ sender = models.ForeignKey(UserAuth, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(UserAuth, on_delete=models.CASCADE, related_name="receiver") is_active = models.BooleanField(blank=False, null=False, default=True) timestamp = models.DateTimeField(auto_now_add=True) def accept(self): """ Accept a friend request. Update both SENDER and RECEIVER friend lists. … -
Server Error (500) heroku-django after deveployed to heroku
After I host my site to heroku and change DEBUG = False its says: Server Error (500) even in the production Enviroment its shows me: Server Error (500) how can i solve that please ? i sees alot of docs but because i have seen it occur in different ways, solving it can be a complex things for a juniour web developer. I try to fix that by adding my domain name in the settings.py file: DEBUG = False ALLOWED_HOST = ['example.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', #Scial liogin Module 'social_django', #My App Module 'itouch', #Bootstrap Module 'bootstrap5', #cloudinary Module 'cloudinary', ] I install whitenoise correctly MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'),) STATIC_URL = '/static/' MEDIA_URL ='/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' my urls.py in myapp: from django.urls import path from . import views urlpatterns = [ path('', views.login, name='login'), path('home', views.home, name='home'), path('logout', views.logout, name='logout'), path('add/', views.addPhoto, name='add'), path('view/<str:pk>/', views.viewPhoto, name='Photo'), ] -
How to log production database changes made via the Django shell
I would like to automatically generate some sort of log of all the database changes that are made via the Django shell in the production environment. Our code base is version controlled so if we introduce a bug, it's easy to track it back. But if a developer in the team changes the database via the Django shell which then introduces an issue, at the moment we can only hope that they remember what they did or/and we can find their commands in the Python shell. I'm particulalry interested in a solution that works with Python/Django. Ideally we would log also the Python code that triggered the data change. -
Django: how to check if user has permission before create or upadte and object
Context we have three types of users: owner, host and admin. The owner has a property that a host manages. a host should be able to create and/or update expenses to some property related to himself I already created some filters for GET method, but couldn't figure it out how to validate user before POST or PATCH... any help will be appreciated Codes here is Expense model: class Expenses(models.Model): """Model for property expenses """ property = models.ForeignKey('property.Property', on_delete=models.CASCADE) register_date = models.DateField() expense_date = models.DateField(blank=True, null=True) reason = models.CharField(blank=True, max_length=1024) description = models.CharField(blank=True, max_length=1024) supplier = models.CharField(blank=True, max_length=1024) value = models.DecimalField(decimal_places=2, max_digits=50, default=0) refund = models.DateField(blank=True, null=True) statement_image = models.ForeignKey(FileItem, on_delete=models.CASCADE) maintenance_image = models.ForeignKey(FileItem, on_delete=models.CASCADE) owner_approval = models.BooleanField(blank=True, null=True) class Meta: verbose_name_plural = "Expenses" def __str__(self): return f"Expense id: {self.id}" Serializer: class ExpensesSerializer(serializers.ModelSerializer): statement_photo = f_serializers.FileItemSerializer(required=False) maintenance_photo = f_serializers.FileItemSerializer(required=False) class Meta: model = models.Expenses exclude = [] def to_representation(self, instance): representation = super().to_representation(instance) print(instance.refund) if instance.refund is None: # condition representation['refund'] = "Pending" return representation return representation ViewSet class ExpensesViewSet(viewsets.ModelViewSet): queryset = models.Expenses.objects.all() serializer_class = serializers.ExpensesSerializer http_method_names = ['get', 'post', 'patch'] permission_classes = (IsHost | IsAdmin | IsOwner,) def get_queryset(self): user = self.request.user property_id = self.request.query_params.get('property_id') register_date = self.request.query_params.get('register_date') refund = … -
It is required that you pass in a value for the "algorithms" argument when calling decode()
The following pages are the code of projects: If i am using token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8') statement then 'str' object has no attribute 'decode' error is occuring. Also, when I am removing and using it without .decode('utf-8') and proceeding with the further code. it is working fine. But when I am applying payload = jwt.decode(token, 'secret', algorithm=['HS256']) then It is required that you pass in a value for the "algorithms" argument when calling decode()" This above-mentioned error is occurring. Please Help me to rectify this error. This is the mentioned error that saying algorithms argument when calling decode() error should be rectified. View Page: from django.http import request, response from django.shortcuts import render from rest_framework import serializers from rest_framework.views import APIView from myusers.serializers import UserSerializer from rest_framework.exceptions import AuthenticationFailed from rest_framework.response import Response from .models import User import jwt, datetime # Create your views here. class RegisterView(APIView): def post(self,request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): def post(self,request): email=request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User Not Found!!!') if not user.check_password(password): raise AuthenticationFailed('Incorrect Password!!!') payload={ 'id':user.id, 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat':datetime.datetime.utcnow() } token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8') response = Response() response.data={ "jwt":token } response.set_cookie(key='jwt', value=token, … -
Form wiht post method return almost fully empty queary dict python django
I am doing small project with python and django. This is my login.html: <form action="chats/login" method="post"> {% csrf_token %} <label for="usrname">Username:</label><br> <input type="text" id="usrname" name="usrname" required><br> <label for="usrname">Password:</label><br> <input type="password" id="pass" name="pass" required><br><br> <input type="submit" value="Login"> </form> <input type="button" href="register.html" value="Register"> and this is my views.py: def login(request): if request.method == "POST": username = request.POST['usrname'] password = request.POST['pass'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return render(request, "index.html", {'fname': username}) ... else: return render(request, "index.html", {'fname': username}) ... else: return render(request, "login.html") The problem here is that when I send the post method the querydict has only this: <QueryDict: {'csrfmiddlewaretoken': ['dcATRguCVcOKWy15aRRwpmTj46B1op5xu4aBxZHg3WzxiS2gYCaioauxHx2Oyaxe']}> and nothing else. Can someone explain where is my mistake? PS: Thats my urls if matters: urlpatterns = [ path('', views.index, name='index'), path('login', views.login, name='login') ] -
Django Rest Framework OAuth2 Access Token Guidance Required
I'm trying to implement OAuth and jwt token login in Django Rest Framework for practice. I'm using social-auth-app-django and djangorestframework_simplejwt. I use the basic documentation and successfully created a user using GitHub (Checked that in Django Admin) and I also created a user using Simple CreateAPIView. For login purposes, I can use simple jwt to login and retrieve the access token to call the other authenticated APIs, but how can I do the same using an OAuth logged-in user account. Another problem I'm facing is, whenever to visit http://localhost:8000/api/auth/login/github/ in the browser is prompts my login screen, after login, it redirects me to http://localhost:8000/api/auth/complete/, which returns 404 because it's not the right endpoint as per the Django default error page. It represents api/auth/complete/<str:backend>/ [name='complete'] as one of the available endpoint. When I visit /api/auth/complete/github/ the error that comes up is AuthMissingParameter at /api/auth/complete/github/. I don't have any idea what is happening. My settings.py configurations are: INSTALLED_APPS = [ --- # Plugins "rest_framework", "corsheaders", "oauth2_provider", "social_django", "rest_framework_social_oauth2", --- ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "rest_framework_social_oauth2.authentication.SocialAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), } AUTHENTICATION_BACKENDS = ( "rest_framework_social_oauth2.backends.DjangoOAuth2", "django.contrib.auth.backends.ModelBackend", "social_core.backends.github.GithubOAuth2", "social_core.backends.spotify.SpotifyOAuth2", "django.contrib.auth.backends.ModelBackend", ) -
Updating model with signals
now i'm trying to update field from my model with help of post_save signal. All works well in the admin page, but the field "number_of_photos" updates only after i click save button in the second time. Why is this happening? Signal code: @receiver(post_save, sender=PhotoAlbum) # noqa def count_photos(sender, created, instance, *args, **kwargs): # noqa instance.number_of_photos = instance.photos.count() signals.post_save.disconnect(count_photos, sender=PhotoAlbum) instance.save() signals.post_save.connect(count_photos, sender=PhotoAlbum) -
how to render data in django template that has been queried in backend using "__contains"
I am using django multiselect field in my model that is used to upload cases. Now I have a field in my model where the admin can select multiple categories for the same case. I have seperate pages to render this data according to the categories selected for them. I am filtering the data like this views.py law_data= Laws.objects.all().filter(sub_law_type__contains = 'ipc').order_by('-date') for law in law_data: print("\n these are the available cases : ", law.title," with sub law types : ", law.sub_law_type, "\n") return render(request, 'citation_ipc.html', {'law_data': law_data} ) here I want to filter all the cases that has ipc in it. And the result I am getting is this, which is accurate these are the available cases : dfsdf with sub law types : ipc, pocso, pmla, ni_act these are the available cases : dfgdfg with sub law types : ipc Now I am trying to render out this data in my html like this html <div id="sclimitations" class="tabcontent"> {% for data in law_data %} {% if data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} <div class="tab"> <div class="judge-content"> <a class="judge-ttle" href="{% url 'doc' data.pk %}">{{data.title|safe}} &nbsp <i class="fas fa-external-link-alt"></i></a><br/><br/> <p> <strong> {{data.sub_title|safe}} </strong> </p> <div … -
How to run my local django server using poetry
I am new to python/django and I am coming into an existing codebase that uses the package manager poetry. My question is simple; how do I start my local django server using poetry run? If not using poetry I understand I can just use python manage.py runserver, but when I run that in my project, I get ImportError: No module named django.core.management. The other most relevant command I ran was poetry run python manage.py runserver, but that yielded ModuleNotFoundError: No module named 'django_q'. I am literally just trying to figure out how to run poetry commands, and in this instance, start my local django server. I am decently lost, so any help with django/poetry would be very helpful. Thank you all in advance! -
Can not create super user, because foreign key can not be null
How to assign foreign key value, when creating super user in Django? I want to make new superuser using python manage.py createsuperuser command, but I get an error: ValueError: Cannot assign "<QuerySet [<Company: Company object (1)>]>": "Worker.company" must be a "Company" instance. Here is the code: class CompanyAccountType(models.Model): accountTypeName = models.CharField(max_length=50) accountTypeValue = models.IntegerField() class Company(models.Model): city = models.ForeignKey(City, on_delete=models.RESTRICT) category = models.ForeignKey(Category, on_delete=models.RESTRICT) companyAccountType = models.ForeignKey(CompanyAccountType, on_delete=models.RESTRICT) class MyAccounManager(BaseUserManager): def create_user(self, username, password): user = self.model( username=username, ) #I tried this for testing (real I would like to send id throught request), but I get error #ValueError: Cannot assign "<QuerySet [<Company: Company object (1)>]>": "Worker.company" must be a "Company" instance. companyObj = Company.objects.filter(id=1) user.company = companyObj user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password): user = self.create_user(username=username, password = password, ) #user.company.id = 1 user.save(using=self._db) return user class Worker(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, default="user") password = models.CharField(max_length=300, default="password") company = models.ForeignKey(Company, on_delete=models.RESTRICT) #blank=True workerName = models.CharField(max_length=50) workerProfileImage = models.ImageField(upload_to='images/', default = "images/defaultUser.png", null = True) USERNAME_FIELD = 'username' #REQUIRED_FIELDS = ['company'] objects = MyAccounManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) -
Download multiple files as zip in Django shows memory error
I am trying to download multiple files as a zip in Django. It works well when file sizes are small. If the file size is more than 1GB, it's showing memory error: Traceback (most recent call last): x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1764, in write x-xxx-xx: shutil.copyfileobj(src, dest, 1024*8) x-xxx-xx: File "/usr/lib64/python3.7/shutil.py", line 82, in copyfileobj x-xxx-xx: fdst.write(buf) x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1131, in write x-xxx-xx: self._fileobj.write(data) x-xxx-xx: MemoryError x-xxx-xx: During handling of the above exception, another exception occurred: x-xxx-xx: Traceback (most recent call last): x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner x-xxx-xx: response = get_response(request) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response x-xxx-xx: response = self.process_exception_by_middleware(e, request) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response x-xxx-xx: response = wrapped_callback(request, *callback_args, **callback_kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view x-xxx-xx: response = view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func x-xxx-xx: response = view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 231, in inner x-xxx-xx: return view(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/views/decorators/cache.py", line 31, in _cache_controlled x-xxx-xx: response = viewfunc(request, *args, **kw) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view x-xxx-xx: return view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/current/fileupload/views.py", line 519, in downloadScanView x-xxx-xx: zf.write(tmp.name, zip_path) x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1764, in write … -
ignore fields on update view
I have a very large form that I have an update view for. The issue is when the users submits an update it says some fields are required such as author and post date. I don't want users to change these fields. The fields are manually rendered How can I ignore these fields in the update view. I have tried to set the requirements to false def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['author'].required = False self.fields['date_posted'].required = False But this throws a null value in column "author" of relation "blog_post" violates not-null constraint Alot of posts said to add null=True but these fields cannot be null view: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post form_class = PostFormUpdate def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.id == post.author_id: return True return False form: class PostFormUpdate(ModelForm): class Meta: model = Post fields = '__all__' -
ImportError : cannot import name 'ugettext_lazy'
I'm trying to install suit, I entered this command : pip install https://github.com/darklow/django-suit/tarball/v2 and wrote this code : from suit.apps import DjangoSuitConfig class SuitConfig(DjangoSuitConfig) : layout = 'horizontal' And added it : INSTALLED_APPS = [ 'products.apps.SuitConfig', .....] But when I added this last code I had this error : InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'suit.templatetags.suit_menu': cannot import name 'ugettext_lazy' from 'django.utils.translation' (C:\Users\hp\environments\env3\lib\site-packages\django\utils\translation_init_.py) note : django 4.01 -
Stripe 'card-element' isn't visible (Python/Django)
this is my first time using this site to ask a question. I'd appreciate the help, I have to turn in this bit of the project today as part of my course :( I'm following this tutorial: https://www.youtube.com/watch?v=ncsCnC3Ynlw (chapter: stripe elements) When I visit my checkout page, the card element isn't showing up. I am at the stage around 3:45:00, and when looking at the checkout, the div for the card element is just a thin, empty bar. Could anyone help me find where I made a mistake? I think it might be the connection between the script and the template or just the script itself, but I'm losing my mind trying to figure out what I've done wrong. My views.py: def BasketView(request): carrinho = Carrinho(request) total = str(carrinho.gettotal()) total = total.replace('.', '') total = int(total) stripe.api_key='sk_test_[...]' intent = stripe.PaymentIntent.create( amount=total, currency='brl', metadata={'integration_check': 'accept_a_payment', 'userid': request.user.id} ) return render(request, 'pedido/pedido_novo.html', {'client_secret': intent.client_secret}) My html template: {% load static %} {% block title %}Livraria Aquaflora | Novo Pedido{% endblock %} {% block adtscripts %} <script src="https://js.stripe.com/v3/"></script> <script src="https://unpkg.com/imask@6.0.7/dist/imask.js"></script> <script src="{% static 'js/orderform.js' %}"></script> <script src="{% static 'js/payment.js' %}" data-rel-js></script> {% endblock %} {% block conteudo %} <div class="container-fluid"> <div class="row no-gutter"> … -
How to get all objects with certain interval of time in django
I want to get all objects which has time to live next 5 seconds with django python ORM. I'm trying in a following way and I don't know why that is not working or what i'm doing wrong... def ttl_expire_list(self): query = self.filter(is_remove=False,ttl__range=[timezone.now() + timedelta(seconds=5), timezone.now()]).order_by("-ttl") # query = self.filter(is_remove=False).order_by("-ttl") return query' -
Django how to find if the object is referenced by ForeignKey from another class in model.py
I have two classes shown below, I wanted to add a function to File to check if the file is referenced by any data inside the Project class (similar how "was published recently" is done here: https://docs.djangoproject.com/en/4.0/_images/admin12t.png ). class File(models.Model): def __str__(self): return self.name file = models.FileField(upload_to='uploads/') class Project(models.Model): def __str__(self): return self.name project = models.ForeignKey(Project, on_delete=models.CASCADE) -
Index not being used for django desc
I have a django model with the following indexes: class Meta: indexes = [ models.Index(fields=['-current']), models.Index(fields=['current']), ] These were added and I ran the migration and saw the results: companies/migrations/0294_auto_20220110_1155.py - Create index companies_c_current_f2c815_idx on field(s) -current of model company - Create index companies_c_current_c8bcb7_idx on field(s) current of model company I've found that running a django-rest-framework query with ordering=current is ~5x faster than with ordering=-current. Using PSQL explain I get the following: # explain select * from company order by current desc nulls last limit 100; QUERY PLAN -------------------------------------------------------------------------------------------------------- Limit (cost=41028.75..41040.42 rows=100 width=1223) -> Gather Merge (cost=41028.75..68747.19 rows=237570 width=1223) Workers Planned: 2 -> Sort (cost=40028.73..40325.69 rows=118785 width=1223) Sort Key: current DESC NULLS LAST -> Parallel Seq Scan on companies_company (cost=0.00..35488.85 rows=118785 width=1223) (6 rows) # explain select * from company order by current asc nulls last limit 100; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------ Limit (cost=0.42..49.79 rows=100 width=1223) -> Index Scan Backward using companies_c_current_f2c815_idx on companies_company (cost=0.42..140727.06 rows=285084 width=1223) (2 rows) It seems clear from the above that the asc is using the index while the desc is not, which explains the time difference. My question is: why not? Is there a different way the index needs to be added to make sure … -
NoReverseMatch at /search/ Reverse for 'entry' not found. 'entry' is not a valid view function or pattern name
NoReverseMatch at /search/ Reverse for 'entry' not found. 'entry' is not a valid view function or pattern name. I´m trying to make an search engine for my website in django, via views.py, but Django always says that there's an exception in views.py Views.py def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entries(request, entry): if entry not in util.list_entries(): raise Http404 content = util.get_entry(entry) return render(request,"encyclopedia/entry.html", {"title": entry, "content": Markdown().convert(content)}, ) def search(request): query = request.GET.get("q", "") if query is None or query == "": return render( request, "encyclopedia/search.html", {"found_entries": "", "query": query}, ) entries = util.list_entries() found_entries = [ valid_entry for valid_entry in entries if query.lower() in valid_entry.lower() ] if len(found_entries) == 1: return redirect("entry", found_entries[0]) return render( request, "encyclopedia/search.html", {"found_entries": found_entries, "query": query}, ) But Django says: "if len(found_entries) == 1: return redirect("entry", found_entries[0]) have an "NoReverseMatch" error" Urls.py from django.urls import path from . import views, util urlpatterns = [ path("", views.index, name="index"), path("entries/<str:entry>", views.entries, name="entries/{{ entry }}"), path("search/", views.search, name="search"), ] handler404 = 'encyclopedia.views.error_404_view' Layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a … -
How could i redirect a user to a specific primary key
Good evening everyone, I am writing a forum where there are different rooms, in each room a user can leave a comment and also update it as needed. After updating the comment, i want to redirect the user to the same room where this comment was. I tried: 1.Reverse + HTTPResponseRedirect def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all().order_by('created') participants = room.participants.all() if request.method == 'POST': message = Message.objects.create( user=request.user, room=room, body=request.POST.get('body') ) room.participants.add(request.user) return redirect('room', pk=room.id) context = {'room': room, 'room_messages': room_messages, 'participants': participants,} return render(request, 'base/room.html', context) @login_required(login_url='login') def updateMessage(request, pk): message = Message.objects.get(id=pk) form = MessageForm(instance=message) if request.user != message.user: return HttpResponse('Unable to edit message') if request.method == 'POST': form = MessageForm(request.POST, instance=message) if form.is_valid(): form.save() return HttpResponseRedirect( reverse( "room", kwargs={ "pk": "13" } ) ) return render(request, 'base/message_form.html',{'obj':message, 'form': form}) but it's working out to return the user only when I manually write the id of the room in which the comment is. Is there a way to bind the id of the comment and the id of the room? I tried to search for similar material and looked for similar projects on github repos, but I can't figure out how to do it, the … -
NGINX serve static files - django project has no styling
I managed to deploy my Django app but I can not pass the static files with Nginx. I have followed all the instructions for deploying to production. When I inspect the page all I see is empty static folder Can anyone spot the mistake? Thanks a lot nginx.conf 10 upstream app_upstream { 9 server app:8080; 8 } 7 6 server { 5 listen 80; 4 listen 443; 1 server_name #######; 2 3 location /static/ { 4 alias /static/; 5 } 6 7 location /media/ { 8 alias /media/; 9 } 10 11 location / { 12 proxy_set_header Host $host; 13 proxy_pass http://app_upstream; 14 } 15 } settings.py 14 13 STATIC_URL = '/static/' 12 STATIC_ROOT = '/static/' docker-compose.yml .... 12 app: 13 build: . 14 ports: 15 - 8000:8000 16 - 8080:8080 17 env_file: 18 - db_${RTE}.env 19 volumes: 20 - .:/app/ 21 - static:/static/ 22 - media:/media/ 23 depends_on: 24 - db 25 26 nginx: 27 build: nginx/ 28 ports: 29 - 443:443 30 - 80:80 31 volumes: 32 - ./nginx/${RTE}/conf.d/:/etc/nginx/conf.d/ 34 - static:/static/ 35 - media:/media/ 36 depends_on: 37 - app 38 39 volumes: 40 static: ... Error message when I docker-compose: nginx_1 | 2022/01/10 16:26:17 [error] 10#10: *8 … -
How to resolve an Import error when using markdownx with Django?
I'm attempting to use markdownx in my code and keep getting an error when running migrations/runserver as shown in extract below: https://i.imgur.com/lzWkM9r.png I've done some searching and everything I have found lists the steps as: pip install django-markdownx Reference in urls.py & settings use in code - models/views py update migrations & run my code currently: settings.py https://i.imgur.com/74n6rPn.png main urls.py (cookbook is app name) https://i.imgur.com/fXIez51.png app/models.py https://i.imgur.com/cJVwBuq.png package versions https://i.imgur.com/t7n5ukS.png The link I have been referencing as a tutorial is: https://dev.to/vladyslavnua/how-to-build-a-django-web-app-from-scratch-tutorial-5bp0 If I comment out the path line relating to the markdownx in main urls.py all works except for a missing import error embedded in page and in server console ' "POST /markdownx/markdownify/ HTTP/1.1" 404 3590 Not Found: /markdownx/markdownify/' I've not used markdownx previously so not sure how to resolve; any help greatly appreciated. Thanks -
Register button won't disappear when user logs in(django, html, css, bootstrap)
Why is this code showing the register button regardless of whether or not a user is logged in? (this is for Django with bootstrap) ''' {% if user.is_authenticated %} <li class="nav-item"> <span class="navbar-text"}">Study hard, {{ user.username }}.</span> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:logout' %}">Log out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'users:register' %}">Register</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:login' %}">Log in</a></li>'''