Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to get data from database using python Django but got an error
Hello everyone I am trying to get data from database but it give me error in case when I am trying to get single data from db as shown below wahid = Webapp.objects.get(title="Ecommerce Website") Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1258, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1084, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1481, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'title' into field. Choices are: created, demo_link, description, id, review, source_link, tags, tiltle, vote_ratio, vote_total It will work only on getting all data from db as shown in image -
How to run python-socketio with django?
I am using python socket io in django rest framework. When i try to connect to socket through postman socketio I get following error. Can anyone help me. Not Found: /socket.io/ server.py import os import socketio sio = socketio.Server(async_mode="eventlet") @sio.event def connect(sid, environ): print(sid, "connected") wsgi.py import os import socketio application = get_wsgi_application() from .socketio_config.server import sio socket_application = socketio.WSGIApp(sio, wsgi_app=application) -
Unable to set form choices from view Django
I learned how to do this from Django Form ChoiceField set choices in View in Form initial However it doesn't seem to work correctly, choices are given view: form_class = AskMCQuestionForm() mc_choices = [] if question.One: mc_choices.append(tuple((1, question.One))) if question.Two: mc_choices.append(tuple((2, question.Two))) if question.Three: mc_choices.append(tuple((3, question.Three))) if question.Four: mc_choices.append(tuple((4, question.Four))) if question.Five: mc_choices.append(tuple((5, question.Five))) mc_choices = tuple(mc_choices) print(mc_choices) form_class.fields['user_answer'].choices = mc_choices form_class.fields['assignment'].initial = assignment form_class.fields['exam'].initial = question.exam form_class.fields['correct_answer'].initial = question.correct_answer form_class.fields['text'].initial = question.text print("About to render page for MC question") return render(request, 'Exam/ask_question.html', {'question': question, 'form': form_class}) form: class AskMCQuestionForm(forms.ModelForm): class Meta: model = MC_Question fields = ('text', 'user_answer', 'assignment', 'correct_answer', 'exam',) widgets = { 'text': forms.TextInput(attrs={'class': 'form-control', 'readonly': True}), 'user_answer': forms.Select(attrs={'class': 'form-control'}), 'assignment': forms.Select(attrs={'class': 'form-control'}), 'correct_answer': forms.HiddenInput(), 'exam': forms.HiddenInput(), } model: class MC_Question(models.Model): One = models.CharField(max_length=200) Two = models.CharField(max_length=200) Three = models.CharField(max_length=200, blank=True, null=True) Four = models.CharField(max_length=200, blank=True, null=True) Five = models.CharField(max_length=200, blank=True, null=True) class Answers(models.IntegerChoices): one = 1 two = 2 three = 3 four = 4 five = 5 text = models.CharField(max_length=200) correct_answer = models.IntegerField(choices=Answers.choices, blank=True, null=True) user_answer = models.CharField(max_length=200) exam = models.ForeignKey(Test, on_delete=models.CASCADE) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=True, null=True) question is an object of MC_Question, the same as what the form is creating. Apologies if I … -
Deploying Django App to Heroku Fail to Push
I am trying to deploy my app to heroku and am running into errors. I'm directly following the walkthrough on Heroku's site, with no luck. error: error: src refspec master does not match any error: failed to push some refs to cmd line: https://imgur.com/a/RVDNUzx Any thoughts? -
How bad is it if I do not use Django_tenants in a SAAS app with multiple users?
So I wish I would of known about Django_tenants earlier. I have written a SAAS (Software as a service) app in Django and the user data is separate by foreign key on the DB. See example. class Company(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) . . class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) . . How bad is this? Am I going to have major problems in the future? Is the data going to get contaminated in any way? Is sqlite3 the appropriate DB? Django_tenants uses Postgresql I have reasearched Django_tenants framework, and it is absolutely the safeguard I would need. But since my app is already written, I realize that to implement Django_tenants, it will basically be a complete rewrite, which I don't really want to do. So, I would really appreciate an opinion from someone with experience in the matter. Thank you. -
Why is Annotate Count function is not populating result?
I hope someone can help me out here - I have to models in Django one called 'Likes' and one called 'Foods', each record in Like contains a FK from Foods. I have the following function in python: def matches(request, eventId): matches = Food.objects.annotate(Count('like__event')) return JsonResponse([match.serialize() for match in matches], safe=False) The above returns a json response, however, I do not see the count of likes in it - I would expect to see at least "like__count": 0 but not even that, it's almost as if the annotate piece is being completely ignored. I think this is because my module is serialized that I don't see it in the JsonResponse. But then what would be the workaround? Thank you in advance! -
Heroku server error 500 after hosting Django app
I have this project, where details are fetched from API LINK COWIN It works completely fine when I run it in localhost, but after hosting it in Heroku, it is showing Server Error 500 settings.py: ALLOWED_HOSTS = ['*'] 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', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static/css', ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' if os.getcwd() == '/app': DEBUG = False django_heroku.settings(locals()) I am trying to host it from Github. github repo link: Github link for project -
User Specific Page in TODO List
I am making a simple todolist application but while I am trying to create user specific pages, I am unable to add a new task probably beacause database is not getting all required datas(i.e. owner of the task). models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class value(models.Model): task=models.CharField(max_length=200) complete=models.BooleanField(default=False) created=models.DateTimeField(auto_now_add=True) owner=models.ForeignKey(User,on_delete=models.PROTECT) def __str__(self): return self.task views.py from http.client import HTTPResponse from urllib import response from django.shortcuts import render,redirect from todo.models import value from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User # Create your views here. from .forms import TitleForm from django.urls import reverse from django.contrib.auth.models import User def home(request): values=value.objects.all() form=TitleForm() if request.method=='POST': form=TitleForm(request.POST) if form.is_valid(): new_data=form.save(commit=False) new_data.owner=request.user() new_data.save() return HttpResponseRedirect('/') context={'form':form,'values':values} return render(request,'home.html',context) #update def update(request,id): ggwp=value.objects.get(id=id) form=TitleForm(instance=ggwp) if request.method == 'POST': form=TitleForm(request.POST,instance=ggwp) if form.is_valid: form.save() return redirect('home') context={'form':form,} return render(request,'update.html',context) #delete def delete_data(request, id ): if request.method=="POST": ggwp=value.objects.get(id=id) ggwp.delete() return HttpResponseRedirect(reverse('deldata', kwargs={'id':id})) return redirect("/") forms.py from django import forms from django.forms import ModelForm from .models import value from django import forms class TitleForm(forms.ModelForm): class Meta: model= value fields='__all__' urls.py(app) from django.conf.urls import url from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home'), path('delete/<str:id>', views.delete_data,name='deldata'), path('update/<str:id>',views.update,name='update') ] … -
How to pass one of the form field's data to another page using class based views in Python/Django?
I am working on a project where I present a form to the user asking about their sports interests to help them find local players to play with. Then I want to return other users who play the same sport. I am using a CreateView when presenting this form and have one model called UserCharacteristics asking these questions. I want to pass the sport the user chose to the ShowMatched view so I can filter the result based on the matching/same sport. In views.py, for the first class based view I am doing: class EnterInfo(LoginRequiredMixin, CreateView): template_name = 'myapp/enterinfo.html' fields = ['name', 'age', 'cityfrom', 'gender', 'sport'] model = UserCharacteristics def form_valid(self, form): form.instance.user = self.request.user return super(EnterInfo, self).form_valid(form) def get_success_url(self): return reverse('showmatched', kwargs={'sport': self.kwargs['sport'] }) For the second class based view in views.py I am doing: class ShowMatched(TemplateView): template_name = 'myapp/showmatched.html' model = UserCharacteristics context_object_name = 'allentries' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['allentries'] = UserCharacteristics.objects.filter(kwargs = {'sport' : self.sport}) return context In urls.py I am doing: path('enterinfo/', EnterInfo.as_view(), name='enterinfo'), path('showmatched/<str:sport>/', ShowMatched.as_view(), name ='showmatched'), In enterinfo.html file I am doing: <p>You are logged in as: {{request.user}}</p> <form action="{% url 'showmatched' sport.id %}" method="post"></form> {% csrf_token %} {{ form.as_p }} <input … -
Fastapi starlette Image Crop
i just wanna image crop in image called UploadFile in starlette. @app.post("/analyze/{type}") def analyze(type: str, image: UploadFile = File(...)): # type value validate if type not in AVAILABLE_TYPES: return {"status": "error", "data": {"error": f"type `{type}` is not supported."}} # req id gen req_id = uuid.uuid4() # save file input_dir = f"{DATA_BASE_DIR}/input/{type}" os.makedirs(input_dir, exist_ok=True) image_path = f"{input_dir}/{req_id}.jpg" with open(image_path, "wb") as buffer: shutil.copyfileobj(image.file, buffer) # send message to rabbitmq send_message(req_id, type, image_path) # return req id return {"status": "done", "data": {"request_id": req_id}} my code is here, i was used bytesIO and pillow library. but it doesn't worked. what should i do? -
nginx and django deployment issues
I seem to be having issues with my django and nginx deployment. Everything was running as normal, i'd navigate cd into /srv/www/repo do the usual git pull origin mybranch activate my venv and run python manage.py collectstatic This was my process, it has worked fine..until now. It seems that the database has shat the bed and I have no idea why. The issue first started when I did python manage.py migrate it was complaining django.db.utils.OperationalError: attempt to write a readonly database. I thought this was odd, but ultimately thought nothing of it. Then another issue popped up that files were missing when running python manage.py collectstatic Anyway, when I tried to take a look at the deployed changes it seems like the database has been completely wiped. I'm not even able to create user to start populating the db again as I'm getting django.db.utils.OperationalError: attempt to write a readonly database I'm not sure what to do? Really hoping someone can point me in the right direction -
Reorder Not Working with Filtered Data Ajax
I implemented a filtered view into my app and now my reordering ajax is not working. My app is a simple view of a data table that is filtered to a user and week (e.g. Rob makes a pick selection for the same group every week). I am using my reorder to allow the user to click and drag their selections into the order that they want. The data is already loaded for all weeks/users, and the user is not creating/deleting options, only ranking them. This was working on non-filtered data, but now it's not responding. ajax: class AjaxReorderView(View): def post(self, *args, **kwargs): if self.request.is_ajax(): data = dict() try: list = json.loads(self.request.body) model = string_to_model(self.kwargs['model']) objects = model.objects.filter(pk__in=list) # list = {k:i+1 for i,k in enumerate(list)} for object in objects: object.rank = list.index(str(object.pk)) + 1 model.objects.bulk_update(objects, ['rank']) # for key, value in enumerate(list): # model.objects.filter(pk=value).update(order=key + 1) message = 'Successful reorder list.' data['is_valid'] = True # except KeyError: # HttpResponseServerError("Malformed data!") except: message = 'Internal error!' data['is_valid'] = False finally: data['message'] = message return JsonResponse(data) else: return JsonResponse({"is_valid": False}, status=400) pick_list: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} … -
Render multiple objects from Django model using request function
Working on adding some job listings to the front page of my django site. There are currently 20 jobs listed for testing purposes. I have a fairly simple django model which contains attributes of the such as job status (active, inactive, archived) and the time at which the job listing was created, so that I can order these chronologically. I want to be able to display only the 4 most recent jobs at the tope of the page, whilst displaying the remaining 16 jobs in a list below this. Here's what I've got so far... Models.py from django.db import models class Job(models.Model): ACTIVE = 'active' INACTIVE = 'inactive' ARCHIVED = 'archived' CHOICES_STATUS = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), (ARCHIVED, 'Archived') ) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=ACTIVE) created_at = models.DateTimeField(auto_now_add=True) In order to then render the jobs on the frontpage of the site I then refer to the job model in a view like below. Views.py from django.shortcuts import render, redirect from apps.job.models import Job def frontpage(request): jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at')[0:4] all_jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at') return render(request, 'core/frontpage.html', {'jobs': jobs, 'jobs':all_jobs}) This does make jobs appear on the frontpage however it seems that the configuration is dictated by the last request, i.e. all_jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at'). I know this because … -
avoid error: 'NoneType' object has no attribute in django model admin
I need to show if a client is having a related contract active or no in customized field in django model admin I tried to use try: but it does not work unfortunately here the original code: class ClientAdmin(ExportModelAdminMixin, ModelAdmin): model = Client menu_icon = "pick" menu_order = 100 exclude_from_explorer = False list_display = ["name", "is_active"] search_fields = ["name"] list_filter = [ClientFilter] index_template_name = "wagtailadmin/export_csv.html" csv_export_fields = ["name"] def is_active(self, client: Client) -> bool: any(site.current_contract.is_active for site in client.sites.all()) is_active.boolean = True # type: ignore is_active.short_description = _("active confirmation") # type: ignore I got the error: File "/home/oladhari/reachat-v4/Reachat-v4/backend/crm/admin.py", line 61, in is_active any(site.current_contract.is_active for site in client.sites.all()) File "/home/oladhari/reachat-v4/Reachat-v4/backend/crm/admin.py", line 61, in <genexpr> any(site.current_contract.is_active for site in client.sites.all()) AttributeError: 'NoneType' object has no attribute 'is_active' to resolve this error I tried to use try: and changed the customized field to this: def is_active(self, client: Client) -> bool: try: any(site.current_contract.is_active for site in client.sites.all()) except ObjectDoesNotExist: return False else: return any(site.current_contract.is_active for site in client.sites.all()) but still having the same error unfortunately please could you help me to avoid this error, thank you -
What is the best way to build Django model?
I want to make a website that gives a visualization of football game statistics. Functionality: The user checks a list of games. Selects game to see details. Can select a particular player. If there is no game he/she is interested in, the user uploads a datafile of the game and adds it to the main list of games. I have a script that cleans data and gives me DataFrame with columns: ['Shots', 'SCA', 'Touches', 'Pass', 'Carries', 'Press', 'Tackled', 'Interceptions', 'Blocks'] if I do the Django model is it ok if I simply do model with these columns, or do I need to do a proper database with separate tables like: Is my UML is ok or do I need to fix something? here is link to my UML https://drawsql.app/xml-team/diagrams/football-game-stats -
Auto token refresh and background web scraping in Django Flask project?
I'm working on a personal project using the Django Flask framework and there are two functionalities I'm trying to implement now. Firstly, I'm using a API service that has 30-minute expiry duration on the authentication token. I'd like to store that token in my database and programatically request a new token once every 25 minutes, most tutorials make mention of a JWT refresh token but that is not offered by the API I am using. What other libraries/functions should I be looking to in order to achieve this? Secondly, Each user has a table of items stored in a sqlite3 database (100+), I would like to programatically perform a google maps search using one column and return the category of the first location returned. Currently I am following a selenium tutorial for web scraping but I am unsure if this is the most appropriate service as I would like this process to happen in the background or a hidden div, I'm also wondering if there are any other better ways to achieve my second goal. Thank you for your time and effort in helping as this is my first time attempting a project using Flask/Django -
how to create a Django project that has a Python environment inside lib and what's the difference to have it inside or in another directory?
I'm deepening my Django knowledge and in the process, I discover that when I do some errors (in this case it doesn't matter what the errors are), Django's engine looks for files outside the project folder. Example of error: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\b2b\Desktop\Python moje projekty\Dev\Apiarena_django\src\templates\product\product_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\b2b\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\templates\product\product_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\b2b\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\templates\product\product_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\b2b\Desktop\Python moje projekty\Dev\Apiarena_django\src\products\templates\product\product_detail.html (Source does not exist) I have two questions: how to create a Django project that has python inside lib folder? What's the difference to have it inside or in another directory as I have now? Does it a bad idea and if so, why? -
Django-crontab is not working on in ec2 ubuntu virtual environment
i use django-crontab library in mac m1 bigsur # settings.py INSTALLED_APPS = [ 'django_crontab' ] CRONJOBS = [ ('*/5 * * * *', 'diagnoses.croncode.ChangeRegisterView') ] # croncode.py def ChangeRegisterView(): and i used python manage.py crontab add It was installed in a virtual environment. and It works well in a local environment. however it's not working at ec2!! The virtual environment anaconda python=3.8.11 version is installed and used by aws ec2. like this Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.2/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.2/dist-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/usr/local/lib/python3.2/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.2/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.2/dist-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/lib/python3.2/importlib/__init__.py", line 124, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/usr/lib/python3.2/importlib/_bootstrap.py", line 824, in _gcd_import raise ImportError(_ERR_MSG.format(name)) ImportError: No module named django_crontab i want to two things. I want to do a cronlog path in ec2 Ubuntu environment. I want to turn django-crontab in ec2. help bros!! -
Edit Django Filter Style
I am struggling to edit the following filter to do a few things: Remove the field name from outside of the TextInput and use that as the Hint Text Keep all filters on a single line within a flex container (currently, the week filter is the entire page-wide and the submit button is on a third line) Make WEEK_CHOICES based on unique values within the field Week, rather than hardcoded to weeks 1-3 (e.g. once an entry with Week 4 is submitted, auto-include this in the filter) Any help is appreciated. filters.py class PickFilter(django_filters.FilterSet): WEEK_CHOICES = ( ('Week 1', 'Week 1'), ('Week 2', 'Week 2'), ('Week 3', 'Week 3'), ) name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control text-white text-center'})) week = django_filters.ChoiceFilter(choices=WEEK_CHOICES, widget=forms.Select(attrs={'class': 'form-control form-control-sm'})) class Meta: model = Pick fields = ['name','week',] pick_list.html {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} {% endblock title %} {% block content %} <div style="font-size:24px"> {{ title }} </div> <div style="font-size:14px; margin-bottom:15px"> Click on the arrows on the right of each contestant and drag them up or down to reorder them based on how far you think they are going to go. </div> <form method="get"> {{ … -
Question regarding taking input from a form in Django and transferring that data to a SQL database
I have 2 html/CSS forms set up and I also have a SQL database set up with values for everything on the forms. What steps would I need to do to ensure that the form and the database are linked? P.S I already created a model and migrated stuff to the SQL database. -
Validate Specific Google ReCaptcha on the backend with multiple ReCaptchas on the Same Page
I have a form page with Google ReCaptcha validation on my Django backend. I also have a small email form on the footer where I would like to add a separate ReCaptcha. They both seem to be rendering fine. Although I don't know exactly how to tell if the invisible ReCapatcha has actually been rendered correctly. On my backend I have attempted to get the Captcha response with request.POST.get('g-recaptcha-response') Do I need to somehow specify which recaptcha element it should check or will it automatically submit the correct one since it is in the form that is being submitted? I'll include my pertaining code below in case the error is in my implementation. <script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script> <script type="text/javascript"> const RenderCaptchas = function() { const siteKey = "{{ GOOGLE_RECAPTCHA_SITE_KEY }}"; const hiddenSiteKey = "{{ GOOGLE_HIDDEN_RECAPTCHA_SITE_KEY }}" const captcha_elements = document.getElementsByClassName('captcha'); const hidden_captcha_elements = document.getElementsByClassName('hidden-captcha'); for (let i = 0; i < captcha_elements.length; i++) { grecaptcha.render(captcha_elements[i].id, {'sitekey': siteKey}) } for (let i = 0; i < hidden_captcha_elements.length; i++) { grecaptcha.render(hidden_captcha_elements[i].id, {'sitekey': hiddenSiteKey}) } } window.CaptchaCallback = RenderCaptchas; </script> <form id="email_subscription_form" class="form-inline float-right" method="post" action="/ajax/email-subscription/"> <div class="form-group"> <label for="id_email_address" class="d-none">Email Address</label> <input type="email" id="id_email_address" class="g-recaptcha hidden-captcha form-control border-0 rounded-0" name="email_address" value="" placeholder="Email … -
Head object forbidden
Whenever I try to submit my form with files it does not work. It worked at first but now it shows me this error. I have no idea what I changed to make it give me this error. I did accidentally put the Access key of my user on GitHub and got a bunch of emails from AWS. but I removed that access keys and even added a new user. So I made a new IAM user and also s3 bucket but it still shows me this. I do have a Risk IAM quarantine alert but the effected key does not exist anymore ClientError at / An error occurred (403) when calling the HeadObject operation: Forbidden Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.0.1 Exception Type: ClientError Exception Value: An error occurred (403) when calling the HeadObject operation: Forbidden Exception Location: C:\Users\Athenix\.virtualenvs\ComsForm-rXtbVY0K\lib\site-packages\botocore\client.py, line 719, in _make_api_call Python Executable: C:\Users\Athenix\.virtualenvs\ComsForm-rXtbVY0K\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\\Users\\Athenix\\Desktop\\ComsForm\\home', 'C:\\Users\\Athenix\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Athenix\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Athenix\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Athenix\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\Athenix\\.virtualenvs\\ComsForm-rXtbVY0K', 'C:\\Users\\Athenix\\.virtualenvs\\ComsForm-rXtbVY0K\\lib\\site-packages'] Server time: Tue, 18 Jan 2022 02:17:26 +0000 Internal Server Error: / Traceback (most recent call last): File "C:\Users\Athenix\.virtualenvs\ComsForm-rXtbVY0K\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Athenix\.virtualenvs\ComsForm-rXtbVY0K\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
When ever I log in and I am redirect to the 'next' parameter, a trailing slash is automatically added to the url, making it double slashes
I have created views in Django that use LoginRequiredMixin. However, whenever I log in and am to be redirected to another url, the url I am redirected to ends with multiple slashes instead of the usual 1 slash at the end of a django url. One of my views: class BookListView(LoginRequiredMixin, ListView): model = Book # paginate enables the list view to fetch a certain number of records per page. This is # useful when the records are plenty and it is not possible to display all in one page. paginate_by = 3 My login.html template: {%extends 'catalog/base_generic.html'%} {%block content%} {%if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {%if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access. </p> {% else %} <p>Please login to view this page.</p> {% endif %} {% endif %} <form method="POST", action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{form.username.label_tag}}</td> <td>{{form.username}}</td> </tr> <tr> <td>{{form.password.label_tag}}</td> <td>{{form.password}}</td> </tr> </table> <input type="submit" value="Login"/> <input type="hidden" name="next" value={{next}}/> </form> <P> <a href="{% url 'password_reset' %}">Forgot Password?</a> </P> {% endblock %} When I am just logging in, … -
Docker compose. Make DRF container visible only for frontend container
I'm creating a project using docker compose with 3 containers: db, django and frontend. I would like to have django endpoints usable only for frontend container, and frontend container accessible from everywhere. How can I do this? -
Django FOREIGN KEY constraint failed after submitting form
Good day, just learning Django since 3 day now. After typing something in the form, clicking the submit button, I want the title to be assigned to a user. But I'm getting this error: IntegrityError at /todo/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://localhost:8000/todo/ Django Version: 4.0.1 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed In the Admin Dashboard, the form is also saved and "Author" dropdown is displayed, but no user is assigned to the author. // models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class User(models.Model): username = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) def __str__(self): return self.username class Todos(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title \forms.py from django import forms from django.contrib.auth import get_user_model # check for unique email & username from .models import Todos User = get_user_model() class RegisterForm(forms.Form): username = forms.CharField() email = forms.EmailField() password1 = forms.CharField( label='Password', widget=forms.PasswordInput( attrs={ "class": "form-control", "id": "user-password" } ) ) password2 = forms.CharField( label='Confirm Password', widget=forms.PasswordInput( attrs={ "class": "form-control", "id": "user-confirm-password" } ) ) class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput( attrs={ "class": "form-control" })) password = forms.CharField( widget=forms.PasswordInput( attrs={ "class": …