Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post Method not allowed in CBV dispatch method when form is invalid
When creating a view using FormView class and using dispatch method to fetch some data during class initialization, Error is received when the form gets invalid {'detail': ErrorDetail(string='Method "POST" not allowed.', code='method_not_allowed')} here is the code :- class TestView(LoginRequiredMixin,FormView): form_class = TestForm template_name = 'test.html' def dispatch(self, request, *args, **kwargs): self.data = TestViewSet.as_view({'get': 'list'})(self.request).data return super(TestView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(CredentialsView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: context['username'] = self.data['username'] context['firstname'] = self.data['firstname'] context['lastname'] = self.data['lastname'] return context def form_valid(self, form): password = form.cleaned_data['password'] if form.is_valid(): return self.query_api(password) else: return super(TestView, self).form_valid(form) Here is the trace :- django: {'detail': ErrorDetail(string='Method "POST" not allowed.', code='method_not_allowed')} Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "./ssh/views.py", line 91, in post return self.form_invalid(form, **kwargs) File "./ssh/views.py", line 77, in form_invalid context = self.get_context_data(**kwargs) File "./ssh/views.py", line 97, in get_context_data kwargs['username'] = data['username'] KeyError: 'username' How … -
fromtimestamp returns me Invalid argument
I'm trying to convert an int variable (timestamp) to datetime but django returns me fromtimestamp Invalid argument date_time = datetime.fromtimestamp(int(request.data["time"])) Exception Type: OSError Exception Value: [Errno 22] Invalid argument How to solve this problem ? -
Nested for loop string equivalent in separate Django model Tables
I have a nested for loop to see where a field from Table Clock equals the field from table Employee, and when this happens run some condition. This seems extremely intuitive however i seem to be making a fundamental error. My if statement does not execute. I have printed out the each tables values and confirmed that some are equal I have also confirmed that both fields types are strong. Please help. ''' queryClock = Clock.objects.all() queryEmployee = Employees.objects.all() if queryClock.count() > 0 : for x in queryClock: for y in queryEmployee: # print(type(x.EmployeeNoC),type(y.EmployeeNo)) # print(x.EmployeeNoC, y.EmployeeNo) if x.EmployeeNoC == y.EmployeeNo: print("yay") x.hourlyRate = y.rate x.save(update_fields=['hourlyRate']) break ''' -
How to convert '2021-08-24T11:00:19Z' to datetime and find days between it and the current time in django
I get the following publishedAt string '2021-08-24T11:00:19Z' from youtube's api for the video object. But I don;t understand how to convert it into a datetime object and find the hours between it and current. I tried the below code but it didn't work view.py from django.utils import timezone from datetime import datetime today = timezone.now() publish_date = datetime.fromtimestamp('2021-08-24T11:00:19Z') diff = today - publish_date But I am getting the below error at this line publish_date = datetime.fromtimestamp('2021-08-24T11:00:19Z') TypeError: an integer is required (got type str) I don't understand how to convert the string to datetime object and get the difference. -
how can I create json data structure in mongodb like this?
I am having a problem to create this structure inside my mongodb. I'm using django. Djongo is the model i used to try and create this but I cant seem to find a way. I've tried using Arrayfield and embeddedfield as well but I'm stuck. Kindly help me if anyone of you know how. Thank you. -
Django nginx gunicorn how they connect together?
I want to deploy my django app on a linux server. For this I use gunicorn (version 20.1.0) nginx/1.18.0 Django==3.0.5 sites-available/bunn_nginx.conf upstream django { server unix:///home/app/bunn/auth/auth.sock; } server { server_name example.com www.example.com; # max upload size client_max_body_size 75M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/app/bunn/auth/static/; } location / { include proxy_params; proxy_read_timeout 300; proxy_connect_timeout 300; proxy_pass http://unix:/home/app/bunn/auth/auth.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/thermal.d-d-s.dk/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name example.com; return 404; # managed by Certbot } uwsgi.ini [uwsgi] # full path to Django project's root directory chdir = /home/app/bunny/auth/ # Django's wsgi file module = auth.wsgi # full path to python virtual env home = /home/app/bunny/env/ # enable uwsgi master process master = true # buffer size buffer-size = 72000 # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /home/app/bunny/auth/auth.sock # socket permissions chmod-socket = 666 # clear environment on exit … -
json.dumps takes too much time to convert the data
I am using json.dumps to make some reports from my Django model. start = time.process_time() items = Allotment.objects.all().order_by('dispatch_date') print("allotments", len(items)) serializer = AReportSerializer(items, many=True) items_json = json.dumps(serializer.data) print("allot time", time.process_time() - start) I have checked the time of query and serialization and it comes too small to even notice but json.dumps takes too much time, sometimes it's even in the minutes. What should I do to reduce this processing time? -
How do I get all for-looped values from a Django template
I am new to django. I want to use this django form to get number_of_days for all {{ name }} values <div> <form action="change_number_of_days" method="post"> {% csrf_token %} {% for name in filenames %} <input type="number" name="number_of_days" id="number_of_days" value=200> <label for="number_of_days"> {{ name }} </label> <input type="hidden" value="{{ name }}" name="name_of_file"><br><br> {% endfor %} <button type="submit"> Gem </button> </form> </div> Currently Im only getting the values of the LAST loop(Pizzaria, 200), but I want to get all looped inputs as a POST request This is my VIEW.py def change_number_of_days(request): if request.method == 'POST': days = request.POST['number_of_days'] print(cleaning_days) filename = request.POST['name_of_file'] print(filename) return render(request, 'price_calculation_complete.html') return HttpResponse("error") -
How to get the 'id' of PATCH request in django?
The PATCH request looks something like this "PATCH /api/details/43/ HTTP/1.1". I want to get the id from that request viz. 43. I am using ModelViewSet and overriding partial_update. I tried to MyModel.objects.get() inside partial_update but its returning more than one objects. -
django mongodb connections by using djongo and pymongo
Can I use djongo to connect with Mongodb database and for complex queries i want to use Pymongo in my django project. please let me now if it is possible. As I wanted to do fulltext search in my project which is possible by pymongo. ''' details = collection_name.find({"$text": {"$search": "python"}},{"score": {"$meta": "textScore"}}).sort([("score",{"$meta":"textScore"})]) ''' -
User foreign key in same model getting updated together in sql database
models.py class test(models.Model): a_names = models.ForeignKey(User, related_name='a_names', on_delete=models.DO_NOTHING, blank=True, null=True) b_names = models.ForeignKey(User, related_name='b_names', on_delete=models.DO_NOTHING, blank=True, null=True) forms.py class Test1ModelForm(forms.ModelForm): class Meta: model = Test1 fields = ('id', 'a_names') views.py def Testing(request, pk): form = Test1ModelForm(instance=pk) if form.is_valid(): form.save() the problem is, when the data is getting updated in the database, both a_names and b_names is getting updated. -
'int' object has no attribute 'encode' error while sending mail in django
[this error i get while sending email][1] def registration(request): if request.method == 'POST': username = request.POST['username'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] password = request.POST['password'] if User.objects.filter(username = username).exists(): messages.info(request,'Username taken') return redirect('registration') elif User.objects.filter(email = email).exists(): messages.info(request,'Email id is already registered') return redirect('registration') else: user = User.objects.create_user(username=username, password= password, email= email, first_name = first_name,last_name = last_name) user.save() auth_token = str(uuid.uuid4()) print('done') print(auth_token , email) send_mail_after_registration(auth_token , email) profile_obj = Profile.objects.create(user=user , auth_token = auth_token ) profile_obj.save() return render(request, 'token_check.html') else: return render(request, 'registration.html') def send_mail_after_registration(ctoken , email): print("hiii") subject = 'Your account need to verified- MyTrip' message = 'Hello, \n We are excited to have you get started. First, you need to confirm your account. Just press the Link below. \n Or paste the link in browser to verify `your account http://127.0.0.1:8000/verify/'+ctoken + '\n \n If you have any questions, just reply to this email—we are always happy to help out. \n Cheers, \n The MyTrip Team' email_from = settings.EMAIL_HOST_USER recipient_list = [email] print("hii") #msg=EmailMessage(subject,message,to=recipient_list) #msg.send() send_mail(subject, message, email_from, recipient_list) error discription: AttributeError at /registration/ 'int' object has no attribute 'encode' Request Method: POST Request URL: http://127.0.0.1:8000/registration/ Django Version: 3.2.6 Exception Type: AttributeError Exception Value: 'int' … -
How to fetch specific data from database using react hooks
I'm trying to make it so that I can just fetch a specific title for the page from the database and have it displayed on the webpage. Here is what I have so far. It fetches the entire list of the titles. const GettingStarted = () => { const classes = useStyles(); const [title, setTitle] = useState([]); const [paragraph, setParagraph] = useState([]); useEffect(() => { const fetchData = async () => { try { const res = await axios.get(`http://localhost:8000/api/text/`); setTitle(res.data); } catch (err) { } } fetchData(); }, []); const getTitle = () => { let result = []; title.map(titledata => { console.log(titledata.title) return result.push( <h1>{titledata.title}</h1> ) }) } return ( <main className={classes.content}> <Helmet> <title>Getting Started</title> </Helmet> <div className={classes.toolbar} /> {getTitle()} </main> ) } For this page, I just want to fetch 'Getting Started' from the list of titles stored in the database. How do I do this? -
I have scrapped a website and stored the data's in json file. The whole project is in Python/Django. I don't know how to display data on my webpage
I am creating a project in Python/Django. I scrapped some data's from another website and stored in json file. Now I want to show those data's in my webpage. Any ideas for displaying those datas on a webpage? -
How to access value of queryset's all value_list values in HTML?
I am working on django currently. I have many-many relationship in models. Suppose one user can have several computer systems, IP, ports, etc. I am able to get all such values by providing the username. Problem: I am getting a queryset like this: <QuerySet [(1, '828234y8y', 'hn', 'hbhb', 'bhjh', 'hbj'), (2, '9299338uu8u', 'hbhb', 'hbhb', 'bhb', 'bhbh')]> after I use this command: selected_user = User.objects.get(username=username) all_mac = selected_user.userl.all().values_list() The main problem is that i want to pass these values to HTML as context so that for each value in queryset I have a row. Example, a row with ('828234y8y', 'hn', 'hbhb', 'bhjh', 'hbj'), then a row with ('9299338uu8u', 'hbhb', 'hbhb', 'bhb', 'bhbh') and so on. What I have tried: I tried to put queryset result in a list. So it became a list of tuples. all_mac = list(all_mac) But, if I pass this list of tuples to HTML like: return render(request, "users/showMachines.html", {'machines': all_mac}) I use it in HTML like: {% for user in machines %} {% for mac in user %} <tr> <td>{{ mac }}</td><tr> I see empty rows in my table. I also tried accessing like mac.0 using index in hope that it shows something but no luck. Help … -
Django Postgres app works perfectly on localhost but fails to load on Heroku after deployment from GitHub (error code H10, status 503)
I have a Django app using PostgreSQL that works perfectly on localhost, but fails when deployed to Heroku. I deploy via GitHub. Although I can successfully deploy the Django app, I cannot access any url. I have received various errors along the way. The current one is HTTP status 503, although I was getting 500 for quite a while. I have tried resetting my Heroku PostgreSQL database, deleting and recreating my database, running heroku run python manage.py collectstatic post-deployment, performing migrations manually post-deployment (also using release: python manage.py migrate --noinput in my Procfile), heroku reset, and resetting my migrations and redeploying, but to no avail. At one point, I had half of the admin working (this was before I finally figured out that my custom models weren't being migrated on heroku because I didn't include the migration files in the deployment.) Now that I finally have the Django apps installed on heroku, I can't even load the admin, much less anything else: 2021-08-26T07:21:03.486150+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin/" host=XXXXXXX.herokuapp.com request_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx fwd="171.xxx.xxx.xxx" dyno= connect= service= status=503 bytes= protocol=http The webpage displays the following error message: Application error: An error occurred in the application and your page could not be … -
Returning django form as json response?
Hello I'm new in django. Is there any way to return django form as a json response? I want to use this response in js to paste it to my html template. Any hint? -
404 page not found in django localhost when try to click on image url
I created menu objects from Django default admin panel on which one of the fields is an image. I have successfully uploaded the image as well. But in the response api, if I clicked on image url, it says 404 not found. The api response is like this. Both image_url and image are 404 not found. I added image_url just to see if it works, but it didn't work as well. My model: class Menus(models.Model): category = models.CharField(max_length=50,choices=CATEGORY,default='main courses') food_name = models.CharField(max_length=100,blank=True, null=True) image = models.ImageField(blank=True,null=True) rating = models.FloatField(blank=True, null=True) description = RichTextField(blank=True, null=True) price = models.FloatField(blank=True, null=True) My serializers: class MenusSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField('get_image_url') def get_image_url(self, obj): request = self.context.get('request') image_url = obj.image.url return request.build_absolute_uri(image_url) class Meta: model = Menus fields = ['category','image', 'image_url','food_name', 'description','price','rating'] My settings: # BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') # MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"media") MEDIA_URL = '/media/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) My project urls:py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I tried many things, putting just urlpatterns for media. Also,I commented out the media_root … -
What is the best practice for Dependency Injection in Django/Python?
I work on a Django-based product that works as a middleman/proxy between an enterprise ERP and some mobile clients. So it supposes to have scalability and easy maintenance in long run. One challenge I'm facing right now is the ability to have multiple versions both on API I expose to clients, and also API I consume from the ERP. I have my business logic in a separate module in each app named *_usecase.py, essentially I should implement versioning by having a base UseCase class and override methods for each version and provide the right class instance to view through DI based on request/response header values. So I've reached this package python-inject. It has pretty neat decorators to inject instances based on configuration you have and type annotation for method parameters. something like: # in view.py @inject.autoparams() def send_notification( request, use_case: SendNotificationUseCase, # as many type annotated parameters you required ): pass # in binder.py binder.bind_to_provider( SendNotificationUseCase, self.provide_send_notification_use_case ) def provide_send_notification_use_case(self): # some check and logic to evaluate appropriate version return SendNotificationUseCaseV1() # v1 implementation of usecase So this package does the job eventually, although I had some minor issues with it here and there but, since it doesn't have that … -
How to authenticate User from mysql in django?
I want to implement login app. all the users information are in table named 'admin_users'. I am using mysql server by xampp. when i am authenticating using user = authenticate(username=username,password=password) On printing user I am getting None. I am beginner in django and I could not find out whats wrong. If I am doing AdminUsers.objects.all() I can print all the table information. models.py class AdminUsers(models.Model): username=models.CharField(max_length=50) firstname=models.CharField(max_length=50) department=models.CharField(max_length=50) name=models.CharField(max_length=50) mail=models.CharField(max_length=50) id=models.IntegerField(primary_key=True) password=models.CharField(max_length=200) class Meta: db_table="admin_users" view.py def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username,password=password) print(user) return render(request,'AdminUsers/login.html') my index.html contains simple forms with username and password. settings.py """ Django settings for python_test project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j*uh&s1$j-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # … -
For loops in HTML Tables (for var in var)
I am trying to print some database values onto an HTML page. The html code is run through a for loop that counts the amount of description values. However it prints the entire database for each entry of Debit , Credit and Account Number. I'm pretty sure the problem is inside the for loop structure , please assist. Home.html: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> {% extends "main/base.html"%} {% block content%} <h1> Kyle Database </h1> <h2>Trial Balance</h2> <br> <br> <table> <th>Account</th> <th>Description</th> <th>Debit</th> <th>Credit</th> {% for description in description %} <tr> <td>{{ accountNo }}</td> <td>{{ description }}</td> <td>{{ debit }}</td> <td>{{ credit }}</td> </tr> {% endfor %} </table> {% endblock %} Views.py: def home(request): return render(request , 'main/home.html') def Kyletrb(request): desc = "SELECT Description FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor = cnxn.cursor(); cursor.execute(desc); description = [tup[0] for tup in cursor.fetchall()] accNo = "SELECT Account FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor.execute(accNo); accountNo = [tup[0] for tup in cursor.fetchall()] deb = "SELECT Debit FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor.execute(deb); debit = [tup[0] for tup in cursor.fetchall()] cred = "SELECT Debit FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor.execute(cred); credit = [tup[0] for tup in cursor.fetchall()] return render(request , 'main/Kyletrb.html' , {"description":description … -
Django app while dockerizing gives "Starting development server at http://0.0.0.0:8000/" but doesn't show up on browser
So I am a beginner in docker and Django. What I have here is a django app which I am trying to dockerize and run. My requirements.txt has only django and gunicorn as the packages. I am getting the below in terminal after building and running the docker image: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 26, 2021 - 06:57:22 Django version 3.2.6, using settings 'myproject.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Below is my Dockerfile: FROM python:3.6-slim ENV PYTHONUNBUFFERED=1 RUN mkdir /Django WORKDIR /Django ADD . /Django RUN pip install -r requirements.txt EXPOSE 8000 CMD python manage.py runserver 0.0.0.0:8000 The commands I am using are: docker build . -t myproj docker run -p 8000:8000 myproj I have tried adding allowedhosts = ['127.0.0.1'] in settings.py but still I am getting "The site can't be reached. 127.0.0.1 refused to connect. Not able to see the "Congratulations" screen. Please help me out with this. P.s: I am using windows machine -
Django model object changed after update
I have a simple model as follows: class Invite(models.Model): status = models.CharField() .... .... In my view, I update an Invite entity: invite_obj = Invite.objects.get(pk=id) // currently invite.status = "OLD" print(invite_obj.status) // prints OLD invite_serializer = CustomSerializer(invite_obj) // a custom serializer which updates the instance status from "OLD" to "NEW" if invite_serializer.is_valid(): invite_serializer.save() print("after update", invite_obj.status) // prints NEW variable invite_obj got modified after update. How did the variable storing the original entity is modified? -
How I generate qr code in django rest framework api
i want to make scannable qr code api generate qr code and put text inside qr code response in image formate models.py .... qr_code = models.ImageField(upload_to='qr_codes', blank=True) ... -
DRF FILE UPLOAD IN NESTED SERIALIZER
I have a three models company, company_contact,company_logo where i have to insert a data in three tables at once. i can upload a company and company_contact but not a company logo. DRF is deleting a nested serializer file itself. while i can see a data in request.data but when i put in serializer it automatically remove that field. here is my serializers class CompanySerializer(serializers.ModelSerializer): company_contact = CompanyContactDetailsGet(many=True,required=False) company_logo_details = CompanyLogoGet(many=True,required=False) class Meta: model = company_details fields = ('id','company_name','company_address','company_email','company_contact','company_logo_details') def create(self,validated_data): print("company_data",validated_data) company_contact_no = validated_data.pop('company_contact') print("company_contact",company_contact_no) # company_logo_data = validated_data.pop('company_logo_details') with transaction.atomic(): company = company_details.objects.create(**validated_data) # company_logo.objects.filter(Q(is_deleted_flag='n') | Q(company=company)).update(is_deleted_flag='y') # for data in company_logo_data: # companyLogo = company_logo.objects.create(company=company,**company_logo_data) for contact in company_contact_no: print("contactsss",contact,company) # contact['company'] = company company_contact_details.objects.create(company=company,**contact) return validated_data and here is my views.py @api_view(['POST']) # @parser_classes([MultiPartParser]) def add_company_all(request): serializer = CompanySerializer(data=request.data) if serializer.is_valid(): serializer.save() result = { 'data':serializer.data, 'msg':"Company Details Added Successfully!!" } return Response(result,status=status.HTTP_200_OK) result = { 'data':serializer.errors, 'msg':"invalid data!!" } return Response(result,status=status.HTTP_400_BAD_REQUEST) here is the data that comes in request in views.py <QueryDict: {'company_name': ['new company'], 'company_address': ['new baneshwor'], 'company_email': ['new@gmail.com'], "comapny_contact[0]['company_contact_no']": ['9867543450'], "company_logo_details[0]['company_logo']": [<InMemoryUploadedFile: 2016-08-27-10-59-56-187.jpg (image/jpeg)>]}> here is the data which goes in serializers company_data {'company_name': 'new company', 'company_address': 'new baneshwor', 'company_email': 'new@gmail.com'}