Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Struggling to get celery worker to run locally
I am running Django 1.8 and Celery 3.1 (not up to me, please refer from comments). I'm trying to get celery to work locally just as it would on production, asynchronously. In one of my Django views I'm sending a potentially long-running task to celery: long_running_task.delay(*args) Which I am defining as a shared_task: @shared_task def long_running_task(*args): # does stuff return { 'success': not error, 'error': error } Then I am having the client polling periodically with ajax requests and depending on response.status act accordingly (show error to the user, refresh relevant parts of the page, etc). @require_GET @login_required def long_runniing_task_poll(request): task_id = request.GET.get('task') if not task_id: return JsonResponse({'error': unicode(_("'Missing task_id parameter.'"))}, status=400) task = long_running_task.AsyncResult(task_id) return JsonResponse({'status': task.status, 'result': task.get()} However, the actual task doesn't seem to be run by celery at all. This is what I get when -------------- celery@DESKTOP-TPGU0DO v3.1.25 (Cipater) ---- **** ----- --- * *** * -- Windows-10-10.0.22621 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: mysite:0x42b7c88 - ** ---------- .> transport: django://localhost// - ** ---------- .> results: - *** --- * --- .> concurrency: 3 (prefork) -- ******* ---- --- ***** ----- [queues] -------------- .> celery exchange=celery(direct) key=celery This … -
How to filter an object based on string from another view
I'm displaying a list of drinks in a template. The drinks model has a many-to-many field with tags that group drinks together. I now want to filter the list of drinks based on this tag. I've made the tag model like this: class Tag(models.Model): drink_tag = models.CharField(max_length=255, blank=False) def __str__(self): return f"{self.drink_tag}" def get_tag_link(self): return reverse('rhumSite:drinkDetailTag',kwargs={'tag':self.drink_tag}) This way, each tag has a link to a page that will display all the drins with said tag. In my URLS.py file the path looks like this: path('cocktails/<str:tag>/',DrinksFilteredListView.as_view(template_name='rhumSite/drinks.html'),name='drinkDetailTag'), When I click on a tag the url is indeed cocktails/tagname so that works well. I now want my listview to take that tag and display all drinks from the drinks model with this tag. My view looks like this: class DrinksFilteredListView(ListView): model = DrinkRecipe context_object_name = 'drinks' def get_queryset(self): return DrinkRecipe.objects.filter(drink_tag__drinkrecipe=self.kwargs['tag']) def get_context_data(self, **kwargs): context= super(DrinksListView, self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() context['tastes'] = TagTaste.objects.all() context['bottles'] = Bottle.objects.all() return context I know I have to use get_queryset(self): but I still struggle with getting the query right. The current code leads to an error in get_context_data: super(type, obj): obj must be an instance or subtype of type specifying this line: context= super(DrinksListView, self).get_context_data(**kwargs) This also prevents me … -
Unable to design login page in HTML for django
I have created a login page using HTML as Django templates. Somehow the box sizes and shapes are not equal. I have tried so hard to make it beautiful but unable to do so. I am new in HTML and Django. I need help how to do this. Need to add more style with good visual. My code is given below: <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> body { font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } /* style the container */ .container { position: relative; border-radius: 5px; background-color: #f2f2f2; padding: 20px 0 30px 0; } /* style inputs and link buttons */ input, .btn { width: 100%; padding: 12px; border: none; border-radius: 4px; margin: 5px 0; opacity: 0.85; display: inline-block; font-size: 17px; line-height: 0.85 px; text-decoration: none; /* remove underline from anchors */ } input:hover, .btn:hover { opacity: 1; } /* add appropriate colors to fb, twitter and google buttons */ .fb { background-color: #3B5998; color: white; } .twitter { background-color: #55ACEE; color: white; text-align: center; } /* style the submit button */ input[type=submit] { background-color: #55ACEE; color: white; cursor: pointer; } input[type=submit]:hover { background-color: #55ACEE; } /* Two-column layout */ .col { … -
Django Password Expiry
If HR add a user with first_name, last_name, email, username, and password. after setting the password the password must only access for 5 minutes, after the time period the password is not usable for login purpose. Does anyone know how to solve this problem in django -
AttributeError: 'Project' object has no attribute 'remark_set'
I am new to django, was following a tutorial and trying to use 'model_set.all()' but I don't understand the error. I tried changing it to 'project_content_type.remark_set.all()' (thinking it's an error with the related name. Error: response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lavis\Desktop\aai\env\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lavis\Desktop\aai\base\views.py", line 80, in project project = project.remark_set.all() ^^^^^^^^^^^^^^^^^^ AttributeError: 'Project' object has no attribute 'remark_set' models.py class Project(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) #p_id = name = models.CharField(max_length=200) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) totalamount = models.IntegerField(null=True, blank=True) payments_todate = models.IntegerField(null=True,blank=True) description = models.TextField(null=True,blank = True) updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated','-created'] def __str__(self): return self.name class Remark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project,related_name='project_content_type', on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] views.py def project(request, pk): project = Project.objects.get(id=pk) remark_made = project.remark_set.all() context = {'project':project, 'remark_made':remark_made} return render(request, 'base/project.html',context) -
Are there some elegant ways to partially save a huge form on Django?
This is more of a conceptual question rather than specifically a technical one. I have a Model that has like 20-30 entries on the database, there are 5-6 required fields and currently I'm driving my Form class from ModelForm. We have designed a somewhat elegant UI at Front-End in our template that takes these fields step by step so we don't overwhelm the user with a giant fieldset on a single response. Now the problem is our Required Model fields are scattered through these steps (Single-Page Accordion UI) and we are trying to save the actual data on a step by step basis so the end user will be able to continue filling the form from the last checkpoint later on. How do we approach this situation, considering the Model also has a UUID that will be Not Editable, So I'm assuming I can't just use some temporary tables in between the process, or can I? -
Django: cors different subdomain host development
I am on a project with django version 3.2.8. the site is hosted on example.com, we plan to register a subdomain host work.example.com to dump all work stuff in. the main reason is that work.example.com would make CORS apply, which some dangerous request is not accessiable even when authenticated when you are on work.example.com the company currently host the web on a rented server, we do not want interupting the running server for development and it is really a lot of work to boot another server. sorry that I have little knowledge on this aspect, I realize that there is little relative resouces and doubt if it’s practical at all. I want a developing environment to test the sub domain url routing and views. I have tried: (on a MacOS Montery 12.6 Intel Core i9) sudo nano /etc/hosts # add this to the end 127.0.0.1 example.com 127.0.0.1 work.example.com # save and close the file and refresh DNS sudo dscacheutil -flushcache then I refresh browser cache started django server, 127:0:0:0 Still works but example.com This site can't be reached, seems example.com still did not point to my localhost. I wonder if it is possible to develpe this subdomain host functionality with … -
How to configure Nginx reverse proxy in Docker
I'm trying to configure Nginx as reverse proxy for my docker container but doesn't work with local subdomains. docker-compose.yml: services: nginx: container_name: tmc_nginx_ctnr ... ports: - '80:80' - '443:443' authentication: container_name: tmc_authentication_ctnr hostname: authentication.localhost ... command: python manage.py runserver 0.0.0.0:8000 ports: - '8002:8000' authentication.conf: server { listen 80; server_name authentication.localhost; location / { proxy_pass http://authentication:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } Inside Nginx container I run these command: $ curl http://authentication.local:8000 curl: (6) Could not resolve host: authentication.local $ curl http://authentication:8000 <!DOCTYPE html> ... Any idea how to fix it ? -
Django: Access the entire pk_set of pre_add and pre_remove of M2M Signal
I have two models Group and Child as defined below, The Group has a M2M relation to the Child. When the m2m field children in the Group model is changed then all the add events and remove events are separated into different action class Child(models.Model): name = models.CharField(max_length=100) req_categories = ArrayField(models.CharField(choices=Categories.choices, max_length=100)) class Group(models.Model): name = models.CharField(max_length=100) categories = ArrayField(models.CharField(choices=Categories.choices, max_length=100)) children = models.ManyToManyField(Child, blank=True) I want a way to access the pk_set of pre_add and pre_remove at a single place to perform some validation currently I have a validation rule that says atleast N number of children should exist so if I place the validation on pre_remove for an action where i removed some child and added some child then the validation error will be thrown even though the upcoming pre_add action will take care of the contraint @receiver(m2m_changed, sender=Group.children.through) def child_models_changed(sender, instance, action, **kwargs): if action == "pre_add": do validation .... if action == "pre_remove": do validation .... -
My Django is suddenly showing KeyError when I add a new document
My API used to work perfectly whoever now whenever I add a new document I get KeyError message (It didn't do that before and I haven't change anything on my python code :(...) the message is something as follows: KeyError at /domain/ 'jXLTurf56ECMhhbNJB9w' Request Method: POST Request URL: my url Django Version: 4.1.5 Exception Type: KeyError Exception Value: 'jXLTurf56ECMhhbNJB9w' Exception Location: /app/My_API/views.py, line 632, in post Raised during: My_API.views.My_RS_ModelBased Python Executable: Python Version: 3.10.9 I tried deleting whatever new document I added and it started working again -
Where does "AttributeError: 'VendorAlias' object has no attribute 'find_spec'" come from?
I'm currently trying to update a larger codebase from Python 3.8 to Python 3.11. I use pyenv to manage my Python versions and poetry to manage my dependencies: pyenv local 3.11.3 poetry update When I run pytest I immediately get: python -m pytest -n 1 Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1074, in _find_spec AttributeError: 'VendorAlias' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/martin/.cache/pypoetry/virtualenvs/web-backend-4tJQ0X3K-py3.11/lib/python3.11/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/home/martin/.pyenv/versions/3.11.1/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1076, in _find_spec File "<frozen importlib._bootstrap>", line 1049, in _find_spec_legacy ImportWarning: VendorAlias.find_spec() not found; falling back to find_module() During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1074, in _find_spec AttributeError: 'VendorAlias' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/home/martin/.cache/pypoetry/virtualenvs/web-backend-4tJQ0X3K-py3.11/lib/python3.11/site-packages/pytest/__main__.py", … -
I am getting a TypeError that my Django ChoiceField's choices are unhashable Type: 'list'
I'm new to Django. I use formset and form via TabularInline. First, I'll show you my forms.py code. DISCONN_BLANK = ((None, '---disconnect---'),) CONN_BLANK = ((None, '---connect---'),) class MyFormSet(BaseInlineFormSet): def get_form_kwargs(self, index): kwargs = super(MyFormSet, self).get_form_kwargs(index) kwargs.update({'parent': self.instance}) return kwargs class MyForm(select2_modelform(Conninfo)): class Meta: model = Conninfo fields = ['mgr_id', ] parent_value = None def __init__(self, *args, **kwargs): instance = kwargs.pop('parent') if instance: self.parent_value = instance print('MyFrom __init__ parent_value {}'.format(self.parent_value)) super(MyForm, self).__init__(*args, **kwargs) conn_queryset = tuple(Conninfo.objects.filter(client_id=self.parent_value).values('mgr_id').values_list('mgr_id', 'mgr_id')) disconn_queryset = tuple(Devicemanager.objects.exclude(mgr_id__in=Conninfo.objects.all().values('mgr_id')).values_list('mgr_id', 'mgr_id')) mgr_id_widget = select2_modelform(Conninfo)().fields['mgr_id'].widget choices = DISCONN_BLANK + tuple(disconn_queryset) + CONN_BLANK + tuple(conn_queryset) print(choices) print(type(choices)) self.fields['mgr_id'] = forms.ChoiceField(choices=choices, widget=mgr_id_widget) Does it seem very complicated..? The point is the conn_queryset and disconn_queryset and choices parts. The type of choices is tuple, and when I try to print ((None, '---disconnect---'), (('id1', 'id1'), ('id2', 'id2'), ... ('id10', 'id10'), ( None, '---connect---'), ('id14', 'id14'), ('id15', 'id15')) It comes in the form of a tuple. But what about the results? TypeError at unhashable type: 'list' where is the list? Isn't list {}? I really don't know. And the strange thing is that if you take the last code out of the init function from conn_queryset, it will be executed. Of course, it doesn't give me the … -
Django: Can I use Subquery with more than one database?
I have two 2 tables in different databases. # Database A class Category(models.Model): name = models.CharField(max_length=100) # Database B class Hero(models.Model): # ... name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) benevolence_factor = models.PositiveSmallIntegerField( help_text="How benevolent this hero is?", default=50 ) Can I use Subquery like this: hero_qs = Hero.objects.filter( category=OuterRef("pk") ).order_by("-benevolence_factor") Category.objects.all().annotate( most_benevolent_hero=Subquery( hero_qs.values('name')[:1] ) ) Actually, I found this: https://books.agiliq.com/projects/django-orm-cookbook/en/latest/subquery.html but no example with different databases. -
On using Multipartparser or formparser classes Swagger documentation won't load, the error - "cannot instantiate nested serializer as Parameter"
I am using a nested serializer as shown below - class Documents_ManagerSerializer(serializers.ModelSerializer): class Meta: model = Documents_Manager fields = ['id', 'doc_type', 'doc_name'] class IndexDetailsCreateSerializer(serializers.ModelSerializer): methodology_file = Documents_ManagerSerializer() Factsheet_file = Documents_ManagerSerializer() Indexvalues_file = Documents_ManagerSerializer() class Meta: model = IndexDetails fields = ['id', 'Tab_id', 'Name' ,'methodology_file','Factsheet_file','Indexvalues_file'] I am using parser classes = Multipartparser and formparser to upload files in swagger documentation, following is my views code - @method_decorator(name='create', decorator=IndexDetailsSwagger.create()) @method_decorator(name='partial_update', decorator=IndexDetailsSwagger.update()) class IndexDetailsView(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = IndexDetails.objects.filter(Valid=True).all() serializer_class = IndexDetailsSerializer http_method_names = ['get', 'post', 'patch'] def get_serializer_class(self): if self.action in ["create"]: return IndexDetailsCreateSerializer elif self.action in ["partial_update"]: return IndexDetailsPatchSerializer else: return self.serializer_class def retrieve(self, request, *args, **kwargs): try: instance = self.get_object() return super().retrieve(request, *args, **kwargs) except: return Response({"message": "Instance doesnot exists"}, status=status.HTTP_404_NOT_FOUND) def partial_update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: self.get_object() except: return Response({"message": "Instance doesnot exists"}, status=status.HTTP_404_NOT_FOUND) if serializer.is_valid(): if len(serializer.data.keys()) < 2: return Response({"message": "please provide somedata to update"}, status=status.HTTP_400_BAD_REQUEST) else: super().partial_update(request, *args, **kwargs) return Response({"message": "Data updated Successfully"}, status=status.HTTP_200_OK) else: return Response({"message": serilizer_validation(serializer)}, status=status.HTTP_400_BAD_REQUEST) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"message": "data created successfully"}, status=status.HTTP_201_CREATED) else: return Response({"message": serilizer_validation(serializer)}, status=status.HTTP_400_BAD_REQUEST) and following is the swagger auto schema code - … -
Django ORM aggregate tax sum
I have a Django project. There are Store model and Analytics model. I want to calculate taxes sum for each store. Is it possible to aggregate it by Django ORM in one request to DB? Without any loop by stores list? I don't want smth like this: for store in stores: taxes_sum = store.sales_sum*store.tax/100 I want smth like this: taxes_sum = StoreAnalytics.objects.filter(store__user=self.request.user).aggregate( sales_sum=Sum(F("accruals_sum"))*Sum(F("tax"))/100) but each store has its own tax percent (6%, 15%, 20%....) class Store(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=128, blank=True, default="", verbose_name="Name") class StoreAnalytics(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name="store_id") sales_sum = models.DecimalField( max_digits=10, decimal_places=2, default=Decimal(0), verbose_name="Sales") tax = models.IntegerField( default=6, validators=[MaxValueValidator(20), MinValueValidator(0)], verbose_name="Tax %" ) Is there any methods to calculate taxes sum? -
GET request returning "Authentication credentials not provided" Django REST Framework
I'm trying to test my very-early-development stage Django REST Framework API by retrieving data of a authentication restricted view from Postman. I'm using Djoser and djangorestframework-simplejwt for handling authentication. My initial post request to log in returns two tokens, 'active', and 'refresh' which I think it is expected behavior. But then I try to use the 'active' token to access a login protected view and I get the "detail": "Authentication credentials were not provided." error. I'm passing the token as a 'Header' with Authorization: Bearer <active token>. Why it keeps saying I don't provide auth credentials? How should those be provided? This is my view and settings: settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } view: class UserItemsViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated, ] serializer_class = UserSerializer def get_queryset(self): user = self.request.user queryset = user.items.filter(active=True) return queryset -
Cookies set by Django not showing in Firefox and Safari
I recently noticed my Django set cookies in Edge not persisting on refresh and so I tried Firefox. The problem I see here now is that they are not even showing up in the cookies tab and so is the same in Safari. It works fine in Chrome and I must add the page works fine in Firefox as when I send a request the cookie values are visible (I catch them in a middleware). On the other hand Safari does not save them at all making it inconsistent accross all browsers. I am not sure why this is the case but I am using Django for the backend and React for the frontend. This is the line of code for settign the cookie response.set_cookie('auth1',token_header, httponly=True, samesite='None',secure=True, max_age=600) Same occurs with a csrf cookie and I have the following in settings CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'None' Any ideas of the issue? -
How to configure my django project: Template Does Not Exist Error?
I am new to the Django framework trying to work through a youtube tutorial to better understand. I created a simple blog post webiste, which was working correctly until I attempted to update my urls.py, views.py, and home.html files respectively. Now when I go to to test the URL on my local machine I am returned with a 500 internal server error, which I do not understand. To my belief my project was configured correctly as I had configured all the variables on my settings.py file. I've added my blog name to the INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '**DrewThe1stBlog**', ], ROOT_URLCONF = 'DrewsBlog.urls':url config Can anyone provide any insight to what I have done wrong. I have tried to debug the code but I am unable to understand the stack trace. Some simple research on Stack Overflow I have tried adding my python path to the the Templates_DIR amongst other things which have not worked. StackTrace below: Environment: > > Request Method: GET > Request URL: http://localhost:8000/ > > Django Version: 4.1.7 > Python Version: 3.8.5 > Installed Applications: > ['django.contrib.admin', > 'django.contrib.auth', > 'django.contrib.contenttypes', > 'django.contrib.sessions', > 'django.contrib.messages', > 'django.contrib.staticfiles', > 'DrewThe1stBlog'] > Installed Middleware: … -
Django web application
I am using django and mysql for web application,web browser storing user visited templates in chache,when user logout from application user is accessing the templates I used never cache to stop browser from caching,problem is it works fine when user logout but before logout also user can't access his visited templates by back button -
Using GCS for media storage on Railway.app
I'm deploying my Django app to Railway.app and am hosting media on GCS (I like the free tier). I've created the service account and received the .json of the credentials. On my local system for dev, I have the .json file in the directory and refer to it like this: GS_CREDENTIALS = service_account.Credentials.from_service_account_file(".gcs_credentials.json") No problems and files upload great. I'm not passing the credentials file through Github (for safety reasons) but now I'm stuck. Is there a way to save this JSON file as an environment variable in Railway.app? For all of my other variables, I'm using django-environ and everything is working great. I just can't find anything online about passing credentials in JSON form to a deployment on Railway. Thank you in advance. -
Where does Django check framework functions live?
The django framework allows you to write your own checks https://docs.djangoproject.com/en/4.2/topics/checks/ but it says nothing about where that code should live and how it is hooked into the check framework. Any ideas on how this is done? -
Django Follow / Unfollow button does not change
I am trying to create a generic social media platform with django. The follow button works functionally, but doesn't text from "follow". The follower and following counts get updated appropriately. You can follow and unfollow people from the button. I just need the text to change. Models.py: class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following', related_query_name='follower') followed_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers', related_query_name='followed') created_at = models.DateTimeField(auto_now_add=True) Views.py: @login_required def follow(request, username): user_to_follow = get_object_or_404(User, username=username) follow, created = Follow.objects.get_or_create(user=request.user, followed_user=user_to_follow) if not created: follow.delete() return redirect(request.META.get('HTTP_REFERER', 'home')) def unfollow(request, username): user_to_unfollow = get_object_or_404(User, username=username) try: follow = Follow.objects.get(user=request.user, followed_user=user_to_unfollow) follow.delete() except Follow.DoesNotExist: pass return redirect(request.META.get('HTTP_REFERER', 'home')) URLS.py: path('follow/<str:username>/', views.follow, name='follow'), path('unfollow/<str:username>/', views.unfollow, name='unfollow'), Profile.html: {% extends 'base.html' %} {% block content %} <div class="profile"> <h2>{{ user.username }}</h2> <p>Followers: {{ user.followers.count }}</p> <p>Following: {{ user.following.count }}</p> {% if request.user in user.followers.all %} <form method="post" action="{% url 'unfollow' user.username %}"> {% csrf_token %} <button type="submit">Unfollow</button> </form> {% else %} <form method="post" action="{% url 'follow' user.username %}"> {% csrf_token %} <button type="submit">Follow</button> </form> {% endif %} </div> {% endblock %} -
Erro: GET / HTTP/1.1" 404 2281 - Python / Django
Boa noite! Ao tentar executar no terminal: python manage.py runserver, o seguinte erro é apontado: "GET / HTTP/1.1" 404 2281, a aplicação não inicia no navegador, acusando que: Usando o URLconf definido em , Django tentou estes padrões de URL, nesta ordem: type_event.urls admin/ usuarios/ eventos/ O caminho vazio não correspondia a nenhum desses. Revisei toda a parte de urls do projeto, de app por app e não consegui identificar a causa da falha. Tentei ver pelos arquivos estáticos também, mas não identifiquei a divergência. -
NoReverseMatch at /addpost/
I recently finished my schooling on Django, and now im building a simple travel blog website that will serve as a project and a portfolio for my job search. My reverse match was working but all the sudden it throws this error NoReverseMatch at /addpost/ Reverse for 'article_detail' with arguments '('1', '4')' not found. 1 pattern(s) tried: ['article/(?P[0-9]+)\Z'] it looks like my posts in my model are automatically being assigned two IDs as their primary key but my code is only built to take a single PK so im not sure whats going on or how to fix it here? i read about 20 other stack overflow posts with similar questions but im still struggling to see what i need to do to fix this. below i posted my models.py, views.py and urls.py please let me know if you need to see anything else. the error appears to be at the bottom of my post model where redirect for adding a post is. Here is my model from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date from ckeditor.fields import RichTextField class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, … -
Integrate reCAPTCHA Enterprise with Android apps and Python as Backend
I want to Integrate reCAPTCHA Enterprise on Front-end (Android) and with Back-end Python on Login. I have implemented on Android and perfectly generating reCAPTCHA response. Problem I send reCAPTCHA generated response to Back-end (Django) in HTTP/POST API call to verify on Back-end. On Back-end I call 'https://www.google.com/recaptcha/api/siteverify' and binded the reCAPTCHA response with GOOGLE_RECAPTCHA_SECRET_KEY to verify the user generated reCAPCHA. But I get message [invalid-input-response] reCAPTCHA in response of 'https://www.google.com/recaptcha/api/siteverify'