Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'user_accounts'
I'm using Django and the CSV built in library and calling/referencing the User Model. I get that error on the implementing line in my python(django) code. import csv from user_accounts.models import CustomUser with open('test_data.csv') as csv_file: csv_reader = csv.DictReader(csv_file) line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: try: user_search = CustomUser.objects.get( id=row["UserId"], username=row["UserName"] ) print('user: ', user_search) except: print('except returned') continue print( f'\t{row["Id"]} works in the {row["UserId"]} department, ' f'and was born in {row["UserName"]}.') line_count += 1 print(f'Processed {line_count} lines.') -
How do I filter from two models (one to one) in Django
I have two models with 1-1 relationship, User and deviceInfo. I am trying to query to get all Users with a specific device ID, and also only guests. My Models: class User(models.Model): userID = models.CharField(max_length=101,primary_key=True) guest = models.BooleanField() class deviceInfo(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE, unique = True) deviceID = models.CharField(max_length=101, default=None) So far I figured out how to filter by device ID. But im not sure how i'd filter this further because the guest value is in another model. What I have so far: (only filters device id) numIDs = LoggedUserInfo.objects.filter(deviceID=deviceId).count() What I tried: (doesn't work) User.objects.filter(loggeduserinfo = numID) I get the error "The QuerySet value for an exact lookup must be limited to one result using slicing." -
Class 'foodgrains' has no 'objects' member error in django
I'm getting this error i'm not finding solution because in earlier i did same things and that worked but now it is not working my views.py file def foodgrainviews(request): foodgrain =foodgrains.objects.all() return render(request,'foodgrains.html',{'foodgrain':foodgrain}) my models.py file #inherit TopList model class foodgrains(TopList): desc = models.TextField(max_length=5000) -
django button click email send
I am a beginner in Django. I want to send an email on button click. Button is delete button. when press on delete button, i want to send an email to receiver@gmail.com. As per the below code, email send when the page loaded. could you please help me to change the as email send on button click. views.py class delete_profile(View): print("nothing") def post(self, request, *args, **kwargs): print("nothing") template = loader.get_template("frontend/subscription-start.html") email_content = "deletion confirmation" send_mail( 'No Dowry Marriage - Subscription', email_content, 'sender@gmail.com', ['reciever@gmail.com'], html_message=email_content, fail_silently=False ) urls.py path('delete_profile', csrf_exempt(delete_profile.as_view()), name='delete_profile') user_profile.html <script> function delete_profile1() { var csrftoken = getCookie('csrftoken'); console.log("rhgrjhrj") $.ajax({ type: 'POST', url: '{% url "delete_profile" %}', data: { csrfmiddlewaretoken: csrftoken }, success: function () { toastr.info('Preference Updated Successfully') } }); } </script> THANKS IN ADVANCE!!!! -
How to insert json data in the form of a table into a webpage?
I have never done front end development before but I have a task where I would have to insert the data extracted from an existing JSON file into an existing webpage with https://........... link. The data has to be inserted inside a table which can be made in the empty webpage by just using the editing tools in that empty page. But the data has to be automatically inserted by appending from the JSON file into the table in that web link. This JSON file is generated from a Python script that I created and I would also need to call that frontend file as well from the python script which would automatically insert the required data from the JSON file into the empty webpage. I was thinking to maybe create an endpoint via Flask/django that will host the json and make an http request from the frontend to get the json. But if I have to make the changes from the fronend of that http:: website don't I need access to the frontend codebase of the webpage? It is since normally that website is secure so people usually use a username and password to log in. To be honest … -
Deserialization error. permission matching query does not exist
I'm trying to deploy my django web app to heroku and I get the deserialization error whenever i run the command 'Heroku run python manage.py loaddata project_dump.json'. Here is my github repo of the project ' https://github.com/hainhtat/carzone-github. Here is the screenshot of the error. Error screenshot -
Is there a Python library to generate a simple misleading web game? [closed]
I am creating a CTF challenge and I want to imbed the flag within the code of a misleading web game. Players might try to complete the game but it won't give them the flag. Is there a way to generate one of those games (like a maze) easily with a Python library? Or maybe somewhere I can copy paste the code from? I will be using the Django framework. -
Django-allauth manual linkup for existing users
I am using django-allauth for social login. But existing users doesn't have any Social account or Social application token..Is there any way to manually assign them Social Account and Social Application Token from python shell / admin-panel? -
How to escape SECRET_KEY in Django from environment file when generated SECRET_KEY begins with '$'?
In my Django project I have a .env file that contains the SECRET_KEY for the production settings. I generated the secret key by running a script from the command line (Here it just prints the generated key as an example). python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())' It just so happens that a secret key was generated that started with a '$' character. My .env file looked like this. DJANGO_SECRET_KEY=$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2% This is read in my production settings file in the following way import os import environ env = environ.Env() # BASE_DIR is the root level directory of the project env_file = os.path.join(BASE_DIR, '.env') if os.path.exists(env_file): environ.Env.read_env(env_file=env_file) # reading .env file SECRET_KEY = env('DJANGO_SECRET_KEY') When I run my Django project with this secret key I get the following error django.core.exceptions.ImproperlyConfigured: Set the *%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2% environment variable Because of the '$' character Django seems to think that the secret key value is an environment variable itself. This is understandable as environment variables in Bash have a '$' prefix. But when I try changing the .env file to DJANGO_SECRET_KEY='$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2%' or DJANGO_SECRET_KEY="$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2%" I get the same error. How do I escape the SECRET_KEY in an .env file on the off chance a secret key is … -
Django cursor.executemany what's the preferred batch size for each "executemany"
I use the following code to do bulk insert with extended "insert into". cursor = connections['default'].cursor() sql = "INSERT INTO %s (%s) VALUES ([xxx], [xxx], ...) " step = 1000 for l in range(0, len(values), step): s_values = values[l:l+step] cursor.executemany(sql, s_values) My question here is if I have a lot of rows to insert, for example, 100, 000: should I insert in one query. or call multiple executemany with fixed step, such as 1000. I read some articles, it is suggest to use 100. I test my code with 100, 000 records to insert. One executemany is faster than multiple. I am not sure what should I do. Not sure whether I miss understood something here. Please help to comment. Thanks. -
Could not import models from the same folder in Django
I cannot import my models in my api/views.py of my products app. Every folders and subfolders are shown in the image here. Products app Image My api\views.py is from products.models import * class CategoryAPIView(ListAPIView): queryset = Category (cant import Category) -
Return name of model an authenticated user belongs to
I have custom user models from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Meta: verbose_name = 'supplier' verbose_name_plural = 'suppliers' class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) is_hub_manager = models.BooleanField(default=False) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) class Meta: verbose_name = 'worker' verbose_name_plural = 'workers' Views.py class AccountType(APIView): permission_classes = (IsAuthenticated,) def get(self, request, format=None): print(type(request.user)) return Response({'account_type':"supplier"} , status=status.HTTP_202_ACCEPTED ) and I have created /auth/account_type which is supposed to return the type authenticated user I would like it to be able to return a response like { "account_type": "Supplier" } where the word Supplier is got from the name of the model class it belongs to. What is the best way to achieve this? -
How to extract PDF data in Django?
I have been trying to extract the data from pdf files, but not with any success. On the website, the user can upload a PDF file and that PDF file's data should save into the database. I am using the below model. from django.db import models class Document(models.Model): document = models.FileField(upload_to='documents/') My view is the following from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from .forms import DocumentForm def index(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'app/index.html', { 'form': form }) forms.py from django import forms from .models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) Template: <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <!--<![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> </head> <body> <center> <h1>Adcuratio Assignment {{ filename }}</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ … -
I'm getting errors when attempting to makemigrations and tables aren't being created
So I'm getting some errors when attempting to run "python3 manage.py makemigrations". A small snippet of the errors are as follows: Traceback (most recent call last): File "/home/vincentqchen/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "catalog_video" does not exist LINE 1: INSERT INTO "catalog_video" ("url", "title", "length", "view... ^ This is my models folder: from django.db import models import os from datetime import datetime #Google api import json from googleapiclient.discovery import build #Scheduler from apscheduler.schedulers.background import BackgroundScheduler class Video(models.Model): #youtube_cache = models.ForeignKey(YoutubeCache,on_delete=models.CASCADE) url = models.CharField(max_length=600, null=False, blank=False) title = models.CharField(max_length=600, null=False, blank=False) length = models.CharField(max_length=600, null=False, blank=False) views = models.IntegerField(null=False, blank=False) date = models.DateField(auto_now=False, auto_now_add=False) ytType = models.CharField(max_length=30, null=False, blank=False) # Create your models here. def ytCacheHelper(): youtube = build('youtube','v3',developerKey = Secret) #Most popular videos in the us YTrequest = youtube.videos().list( part="snippet,contentDetails,statistics", chart="mostPopular", regionCode="US" ) response = YTrequest.execute() #Python dictionary of all top yt videos items = response['items'] for x in range(len(items)): # Parts of video snippet = items[x]['snippet'] contentDetails = items[x]['contentDetails'] statistics = items[x]['statistics'] # Figure out length of video length = contentDetails['duration'] length = length[2:] #Figure out date of video date = snippet['publishedAt'] year = int(date[:4]) month = int(date[5:7]) day = int(date[8:10]) hour = int(date[11:13]) minute … -
Provide http_method_names based on REMOTE_ADDR?
I overwrite get_serializer_context method in Viewset and add IP whitelist. if request REMOTE_ADD not int whitelist only return http_method ['GET'], else return ['GET','POST','DELETE','PUT']. class TestModelViewSet(ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer def get_serializer_context(self): context = super().get_serializer_context() context.update({ 'address':['8.8.8.8'] }) return context def _allowed_methods(self): check = self.get_serializer().context['address'] if self.request.META['REMOTE_ADDR'] not in check: return ['GET'] return ['GET','POST','DELETE','PUT'] Now I get error: AttributeError:TestModelViewSet object has no attribute 'format_kwarg -
Is it Possible to create Django Admin form like change_form_template with the help of RESTApi
i want to replace the default form template with my new new_changeform.html with RESTApi with all POST, GET, PATCH,etc. class ContentAdmin(admin.ModelAdmin): change_form_template = "new_changeform.html" -
How add multiple data to Parent with ForeignKey(filter_horizontal) relation with Child in django admin?
I want to add multiple child data to the each parent where i can add and remove child data which belongs to the respective parents. Is it possible to do that thing without ManyToMany Relationship. class ParentIndustry(models.Model): name = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str(self.name) class Industry(models.Model): industry = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) parent_industry = models.ForeignKey( 'ParentIndustry', null=True, blank=True, related_name='parent_industry', on_delete=models.SET_NULL, default=None) def __str__(self): return str(self.market) How can i modify my admin so that i can do the above operation. I want to filter the child usingfilter_horizontal class ParentIndustriesAdmin(admin.ModelAdmin): list_display = ('id', 'name') search_fields = ['id', 'name', ] filter_horizontal = ['Have to add filter too'] ordering = ['-date_modified'] def save_model(self, request, obj, form, change): obj.modified_by = request.user obj.save() admin.site.register(ParentIndustry, ParentIndustriesAdmin) Thank you -
Page not found (Django)
I'm making website using Python Framework of 'Django'. I have some problems with Django about entering. The page for http://127.0.0.1:8000/blog/archive/2021/1%EC%9B%94/ should be uploaded when the January link is clicked, otherwise Page not found (404) will appear. I'd like to know what's wrong and how to fix it. blog/urls.py contains: from django.urls import path, re_path from blog import views app_name='blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<str:month>/', views.PostMonthArchiveView.as_view(), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] blog/views.py contains: from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field = 'modify_dt' make_object_list = True class PostMonthArchiveView(MonthArchiveView): model = Post date_field = 'modify_dt' class PostDayArchiveView(DayArchiveView): model = Post date_field = 'modify_dt' class PostTodayArchiveView(TodayArchiveView): model = Post date_field … -
How to raise errors in ListApiView DRF
class GetFollowers(ListAPIView): """ Returns the users who follw user,along with weather the visiter — the one who sent api request — follows them or they follow him/her """ permission_classes = [IsAuthenticated,] serializer_class = None def get_queryset(self,*args,**kwargs): user = self.request.data.get('user',None) if user is None: pass followers_obj, created = Follow.objects.get_or_create(user=user) all_followers = followers_obj.followers.all() Now , when a user sends a request , along with the one's username , in query_params, whose he/ she wants to get followes, how do I return an error if the sender doesn't follow the one whom he wants to get followers. -
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' in Jenkins
I am trying to deploy Django app in windows using Jenkins. It is getting "no such file or directory" but the file is exists. How do I solve that issue. anyone help me? -
django redis cache bytes
I use django redis. settings.py CACHES = { 'register': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': os.getenv('REDIS_REGISTER'), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } views.py def test(request): register_db = caches['register'] uuid4 = uuid.uuid4().hex image_path = f'./static/uploads/register/1/247688.jpg' print(f'uuid: {uuid4}, image_path: {image_path}') register_db.set(uuid4, image_path) print(register_db.get(uuid4)) output uuid: ddddc2e9b86940619d1b7cef2699bfe2, image_path: ./static/uploads/register/1/247688.jpg ./static/uploads/register/1/247688.jpg mytest.py register_db = redis.Redis(host='localhost', port=6379, db=1, decode_responses=False) for i in register_db.keys(): for key in register_db.keys(): print(f'key: {key}, value: {register_db.get(key)}') output key: b':1:ddddc2e9b86940619d1b7cef2699bfe2', value: b'\x80\x04\x95*\x00\x00\x00\x00\x00\x00\x00\x8c&./static/uploads/register/1/247688.jpg\x94.' Why is it different after Django puts in the data, redis takes it out? Is there any way to solve. I hope the result. value: ./static/uploads/register/1/247688.jpg' -
I'm integrating Stripe payment gateway in my app, but neither token nor the ref_code is being generated?
Please let me know if anyone has the idea how to use it? Thanks in advanced. class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False, 'STRIPE_PUBLIC_KEY': settings.STRIPE_PUBLIC_KEY } return render(self.request, 'payment.html', context) else: messages.warning(self.request, "You've not added billing address.") return redirect('e_commerce:checkout') def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total()*100) # cents try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token ) # order.ordered = True # create the payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.ordered = True order.payment = payment # TODO assign ref code order.ref_code = create_ref_code() order.save() # print("your order placed!") messages.success(self.request, "your order was successful.") return redirect("/e_commerce") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught body = e.json_body err = body.get('error', {}) messages.warning(self.request, f"{err.get('messages')}") return redirect("/e_commerce") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.warning(self.request, "Rate limit error") return redirect("/e_commerce") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.warning(self.request, "Invalid parameters ,Please try again!") … -
django.db.utils.OperationalError: no such table in SQLite3 database
I am getting the following error when trying to migrate my data, which I am trying to troubleshoot but I cannot identify where the error is occurring. For context, I created a new app within my project for a webpage on change impacts, and I copied most of the code from my book app to start it out. It looks like somewhere, my code is mixing the two apps (must've been somewhere that I forgot to update) and is trying to add data into a table that doesn't exist (and shouldn't). Any idea how to identify where this is happening, or any flags to look out that would be causing this? Operations to perform: Apply all migrations: admin, auth, books_cbv, books_fbv, books_fbv_user, change_impacts, communications, contenttypes, sessions Running migrations: Applying books_cbv.0006_auto_20210107_2150...Traceback (most recent call last): File "C:\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: books_cbv_changeimpacts The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python38\lib\site-packages\django\core\management\base.py", line 323, in … -
How to settup django login in the header?
I am trying to setup user login in the header, that way, the user can login/logout at any point in the web. However I must have missunderstood the Django tutorials. I am kind of a newbie with Django and I am not entirely sure of how to accomplish this, so any help is welcome. I would like to clarify also, that I do not wish to redirect to another template. If possible, just reload the current page with the user already authenticated. I tried 2 things: add action="{% url 'sign_in' %}" in the header form add action="{% url 'accounts_login' %}" in the header form And neither seems to work. My app name is 'web' My project name is 'core' # core/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('django.contrib.auth.urls')), path('rest/', include('rest_framework.urls')), path('', include('web.urls')) ] # web/urls.py from django.contrib.auth.views import LoginView from django.urls import path from . import views urlpatterns = [ path('', views.base), path('sign_in', views.sign_in, name='sign_in'), path('accounts/login/', LoginView.as_view(template_name='base.html'), name='accounts_login') ] # wev/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.contrib.auth import authenticate, login, logout import requests def base(request): context = { 'user': request.user } return … -
Custom user model in django to use phone and email both for sign up
By default django uses the USERNAME_FIELD for authentication but it takes only one field. But i want my signup form to let users sign up by using phone number or by their email, like it happens in facebook . Can anybody help me how can i achieve this ?