Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to solve OS Error in Django Project
I started learning Django recently. I first ran the virtual enviroment, then installed Django and then python manage.py runserverbut im recieving this error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' Traceback (most recent call last): File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\base.py", line 371, in execute … -
Trying to do a calculation on django models
i have two integer fields that i want to divide to get the value of 3rd field. @property def Pallets_Count(self): return self.CASES/self.CasesPerPallet but the result in the database always shows null . -
Change value in views before rendering it at html page
I have a listview in my Django's project like: class KaoiroView(ListView): template_name = 'main/show-kaoiro.html' queryset = Kaoiro.objects.all() context_object_name = 'kaoiro' paginate_by = 10 where Kaoiro has one column called checkTime = models.BigIntegerField() in models.py. this checkTime is a unixtime like one big number. I would like to convert this time when user get above page from my views.py, but because I'm using a listview I don't know how to access this data -
TypeError: join() argument must be str or bytes, not 'Request'
Hi I am new to django rest framework can any one help me to download file from server as file path is store in db .How can I get file using api in django rest framework ..please help -
How to continuously keep displaying a timer on django?
I am developing a website using django framework and i am kinda new to it. I want to display an item from the database for a specific time on the webpage. I have a custom filter to implement the timer logic , however I am trying to understand that how can I display the actual timer on the page. Below is the logic for timer :- @register.filter(name="time_left") def time_left(value): t = value - timezone.now() days, seconds = t.days, t.seconds hours = days * 24 + seconds // 3600 minutes = (seconds % 3600) // 60 seconds = seconds % 60 st = str(minutes) + "m " + str(seconds) + "s" return st -
Do some function in repeated interval in django
I am working on django website through which a user can send notifications to registered user on app. Here I have a class Notification in models.py with following fieldfield sender = models.ForeignKey(User, on_delete=models.PROTECT, related_name="notifications_sent") class_group = models.ForeignKey(Classes, on_delete=models.PROTECT, related_name="class_notification") topic = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) seen = models.ManyToManyField(User, related_name="recieved_notif") reciepent = models.ManyToManyField(User, related_name="notif_reciepent") Now until acknowledged by all its reciepent I want to send this notification again to the remaining reciepent. I am using pyfcm for sending notification. How to achieve this task -
django.db.utils.ProgrammingError: relation "client_apps_externalkeys" does not exist
I was trying to save stripe keys to database for convenience of customers to edit it, have created models and saved to db. But when I try to print the keys getting this error. This is the code class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True) public_key = ExternalKeys.objects.first().public secret_key = ExternalKeys.objects.first().secret webhook_secret_key = ExternalKeys.objects.first().webhook_secret print(public_key) print(secret_key) print(webhook_secret_key) -
user profile with django
what would be the steps to create a user profile other than the administrator user please, I am a newbie. I leave the model class of which I want to be a user profile enter image description here -
django.core.cache.lock doesn't work in a Celery task
I have the following (tasks.py): from celery import shared_task from django.core.cache import cache @shared_task def test(param1: str) -> None: with cache.lock("lock-1"): print("hello") When I do a test.delay(), nothing is printed, which makes me believe that there is something wrong with cache.lock("lock-1"). I'm using Redis as my cache and Celery backend, and this is configured in settings.py. What is wrong here? If django.core.cache cannot be used as a locking mechanism (to ensure that only one test runs at a time, what could be used instead?) Thank you! -
Cracking django/python interviews
I've been working in TCS as an embedded system developer (2.5+ years). For the past 3 months I'm learning django/python. is it going to be hard for me to crack interviews since I'm trying to switch to a completely different domain? What are the concepts in django/python I should be strong in? My current package is 4.2 LPA. But if I'm starting new as a django developer, is it fair to demand 6.5. Or 7 LPA? Does MNCs like wipro or Infosys recruit django developers? If yes, how to apply? (I'm an average coder) Please do respond. Thanks in advance! -
Handling Django Rest Framework 404 page directed to react app's home/index
I have DRF project and the react project is also within the Django project as an application. The name of the react application is frontend. INSTALLED_APPS = [ .... 'frontend' ] The structure of the frontend is as follows, The only code in the project is in views, def index(request): return render(request, "build/index.html") And the URL is, from frontend.views import index urlpatterns += [path("", index, name="index")] Now what I was trying to do is, if the browser's URL response is 404, then instead of showing django's 404 page I would like to go the home/index of the frontend react app. I tried to add handler404 = 'frontend.views.index' in urls.py, but it shows 500 internal error instead of 404 or the index of react app. Any help would be really appreciated. Thanks in Advance. -
Django raw sql statement with params and likes search
I have a problem when performing a raw sql in Django. res = [] start = '2017-12-08T01:56:56.701Z' end = '2020-12-08T01:56:56.701Z' with connection.cursor() as cursor: raw_sql = ''' select case when content like '%products%' then 'Products' else 'Others' end as name, count(id) as times from mytable where somefield LIKE "%somefieldcontent%" and created between '%s' and '%s' ''' cursor.execute(raw_sql, [start, end]) res = cursor.fetchall() It raise this error: unsupported format character ''' (0x27) I tried to perform this sql directly in mysql, it works. But it does not work in the Django environment. I think must be something wrong I do about the string. Basically I want to use params instead concat to build the SQL statement. Any ideas? Thanks! -
Django Filtering Many-to-Many relationship without ManyToManyField "through" relationship
Given these models: class Event(models.Model): name = models.CharField() class Project(models.Model): name = models.CharField() class EventProject(models.Model): event= models.ForeignKey(Event) project= models.ForeignKey(Project) Is there a way to get all the Events for each Project like this: with the property project.events = [<array of Event>]? I found a similar question, however one of the tables has the members = models.ManyToManyField(Person, through='Membership') relationship so it's easier to do. I can't do as in the related question and add a relationship as I'm not allowed to change the model. -
Serializer Including Reverse Relationship
I have been searching for the answer on SO for hours at this point and still haven't found the answer. What I am trying to achieve is this: In my chat function, I would like to show the list of chat channels with the owner, member, and the last message written. So far, I have been able to show the owner and member list. However, the last message does not show whatever I do with the serializer... Below is the models.py for the models in question. models.py class ChatUser(models.Model): id = models.IntegerField(primary_key=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField( auto_now=True) status = models.IntegerField(default=1) is_logged_in = models.BooleanField(default=True) username = models.CharField(max_length=100, default='') password = models.CharField(max_length=255) login_token = models.CharField(max_length=255, blank=True, null=True) session_token = models.CharField(max_length=500, blank=True, null=True) channel = models.ManyToManyField("ChatChannel", related_name="users", null=True, through="ChatChannelMembership" ) class ChatChannel(models.Model): channel_types = ( ('private', '비공개'), ('public', '공개') ) id = models.CharField(primary_key=True, max_length=255) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100, blank=True, null=True) owner = models.ForeignKey(ChatUser, on_delete=models.DO_NOTHING) type = models.CharField(choices=channel_types, max_length=10) is_frozen = models.BooleanField(default=False) member = models.ManyToManyField(ChatUser, related_name="channels", null=True, through="ChatChannelMembership" ) class ChatMessage(models.Model): message_types = ( ("text", "글자"), ("custom", "사용자 임의") ) id = models.AutoField(primary_key=True) talkplus_message_id = models.CharField(max_length=255, blank=True) created_date = models.DateTimeField(auto_now_add=True) channel = models.ForeignKey(ChatChannel, on_delete=models.CASCADE, related_name="messages") sender = … -
Environment Isolation in django-server on user side
I have been working on an Online Competing and Development Environment project on django, and one of the requirements is environment isolation, i.e. the server needs to be unaffected ,even if the user runs some malicious code ,such as equivalent of "rm -rf /" from python. I know the implementation is related to the use of docker, but i am unable to figure out the environment isolation on the user side, after reading several web articles too. Any references or help will be highly appreciated. Thanks for reading -
Reverse Queryset Order in Django for pagination
I have some technique to share with reverse queryset and pagination import your_model from django.core.paginator import Paginator array = your_model.objects.order_by('id').values().reverse() or array = your_model.objects.order_by('create_at').values().reverse() p = Paginator(array, 15) => 15 is number of data in pagination p.num_pages => check number of page p.get_page(page).object_list => get data each page -
Fail to pass dict data to jquery. Error display as: Uncaught SyntaxError: missing ) after argument list)
I have issue on reading data that pass from a Django template in jquery .js file. The data in my Django view: print({0}, {1}\n'.format(init_data[1], type(init_data[1])))) // this will print: 'Counter({'pass': 15, 'fail': 2}), <class 'collections.Counter'> context = {"data":init_data[1].items()} return HttpResponse(template.render(context, request)) In my index.html template I'm able to read the data out as such {% block content %} <h3> {{data}} </h3> // this printed dict_items([('pass', 15), ('fail', 2)]) <div class="tab"> <button class="tablinks" onclick="openResult(event, 'TabForm')" id="defaultOpen">Form</button> <button class="tablinks" onclick="openResult(event, 'TabChart', {{data}}')">Statistic</button> </div> <div id="TabChart" class="tabcontent"> {% include 'result/tab_statistic.html' %} </div> {% endblock %} In result/tab_statistic.html, I want to use the 'data' as dynamic data for a chart in jquery, but the 'data' seem not readable in jquery script as I get bug complaining: (index):18 Uncaught SyntaxError: missing ) after argument list Here is my simple jquery script just to show the data is not readable when called from function openResult() above function openSummary(evt, tabName, a ) { if (typeof(a)==="undefined") a = "None"; console.log('CHECK a=' + a); return It seems to be it don't allow 'data' to be passed directly as the way I do because if I replaced the {{data}} with any argument 'abc' , it just working. Pls gives me … -
Python - Access a model, with a name that is dependant on a variable value
I'm trying to access a model, with a name that is dependant on a variable value. If have a series of models based on a country identifier. e.g. Student_??? where ??? is the country identifier. If I want to print out details of each student for each country, is there a way of looping through the code to access each model dynamically. I could perform the task through an if statement, but that would require hardcoding each country code into the program, which I want to avoid. As an example. My views.py looks like: mystudentcountry = {'AU', 'US', 'UK', 'EU'} for country in mystudentcountry: mystudent = Student_AU.objects.all() for student in mystudent: print(f'{student.name} is {student.age} years old and studies in {country}') On the third line of code "mystudent = Student_AU.objects.all()" is it possible to replace the "AU" with each country as identified in the loop. Thank You for your support. -
Why indentation of Retun statement is not under form here?
the code below is correct, however, I want to know why the return statement is not functioning when indented under form? def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('websitehome') else: form = UserCreationForm() return render(request, 'user/register.html', {'form': form}) -
How do I handle this error : __init__() got an unexpected keyword argument 'book_category'
I am trying to input some book data and save it to my database using django(trying to make a web library) But I encounter this kind of error: init() got an unexpected keyword argument 'book_category' The error seems to be in this line of code : form = CategoryForm(book_category= book_category) This is the code of my views.py class AddBook(View): def post(self, request): form = BooksForm(request.POST, request.FILES) if form.is_valid() book_category = request.POST.get('book_category') firstname = request.POST.get('Firstname') lastname = request.POST.get('Lastname') author = Author.objects.filter(Q(firstname__icontains = firstname) & Q(lastname__icontains = lastname)) if author: print(author) else: form = AuthorForm(firstname=firstname, lastname=lastname) form.save() category = Category.objects.filter(Q(book_category__icontains = book_category)) if category: print(category) else: form = CategoryForm(book_category= book_category) form.save() author = Author.objects.filter(Q(firstname__icontains = firstname) & Q(lastname__icontains = lastname)) for a in author: print(a.book_author_id) for c in category: print(c.book_category_no) book_title = request.POST.get('book_title') book_cover = request.FILES.get('book_cover') book_file = request.FILES.get('book_file') book_year = request.POST.get('book_year') book_tags = request.POST.get('book_tags') book_summary = request.POST.get('book_summary') form = Books(book_title = book_title, book_author_id = Author.objects.get(book_author_id = a.book_author_id), book_cover = book_cover, book_file = book_file, book_year = book_year, book_summary = book_summary, book_category_no = Category.objects.get(book_category_no = c.book_category_no), is_bookmarked = 0, is_downloaded = 0, is_read = 0, is_deleted = 0) form.save() return HttpResponse('Book Saved!') else: print(form.errors) return HttpResponse('Not Valid') And here is my models.py: class … -
Django with sqlalchemy + alembic + django.contrib.auth
How can I customize auth user with SQLAlchemy, instead of Django ORM? Django built-in auth features are so useful but it assumes built-in User or one extended with Django ORM. There's no instruction how to do it with SQLAlchemy AFAIK. I'm newbie of Django but found some articles/blogs pointing out that Django ORM is not good from data analysis standpoint. Therefore I'm thinking of fully using SQLAlchemy instead of Django ORM.To make things simpler, I don't like to use both of them. I've investigated tutorials/articles/blogs regarding Django + SQLAlchemy but most of them seem obsolete(like 5 - 10 years ago). Perhaps it's standard to use Django ORM even for apps of data analysis in recent days? -
How should I avoid this race condition?
I have a piece of code like below: bargained_count = BargainLog.objects.filter(bargain_start_log=bargain_start_log).count() total_bargain_count = 10 # money = '%.2f' % (goods_price / 10) # TODO:接入砍价算法 money = calc_single_bargain_money( bargain_start_log=bargain_start_log.id, total_bargain_money=round(float(goods_price), 2), leftover_bargain_money=round(float(goods_price) - float(total_bargain_money), 2), total_bargain_count=total_bargain_count, leftover_bargain_count=total_bargain_count - bargained_count, is_new_user=False ) print('money', money) ... BargainLog.objects.create(bargain_start_log=bargain_start_log, money=money, ...) bargain_count is a parameter of func calc_single_bargain_money. But, because of the race condition. I am not sure if this is one kind of race condition. I may get bargain_count as same values which will affect the result of calc_single_bargaiN_money. So, how should I avoid it, please give me some advice. -
TypeError: entry() missing 1 required positional argument: 'title' (Django Help)
With Django I'm creating an encyclopedia website similar to Wikipedia, for a class. I've played around with this for quite a while but still cannot solve this - I keep getting the error: entry() missing 1 required positional argument: 'title' The error occurred when I clicked to create a new page on the site. This pertains to the function 'newpage' but I think the issue might be in the function 'entry.' I did the exact steps (but using 'title') from this Stack Overflow suggestion but it did not work: TypeError at /edit : edit() missing 1 required positional argument: 'entry' In urls.py I've tried both: path("wiki/<str:entry>", views.entry, name="entry"), path("wiki/<str:title>", views.entry, name="entry"), Just can't figure out how to get past the error. Any info is appreciated, as I'm new to Django. urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path("", views.index, name="index"), path("wiki/<str:title>", views.entry, name="entry"), path("newpage", views.entry, name="newpage"), ] views.py file: class CreateForm(forms.Form): title = forms.CharField(label='title') text = forms.CharField(label='text') def index(request): """Homepage for website""" return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, title): """ Displays the requested entry page, if it exists """ entry_md = util.get_entry(title) if entry_md != None: # Title exists, convert md to HTML and return rendered template … -
OperationalError, No such table: accounts_user
I'm working on a Django backend for a simple to-do list website. The website authenticates users by asking them to put in their email, sending them a link with a token, then using that token to log them in when they click on the link, redirecting them back to the homepage. When I try and run the development server, I always get a debug screen saying OperationalError at / no such table: accounts_user. I have two apps that are part of the overall project, lists and accounts. Solutions to similar errors I've come across on StackOverflow haven't worked for me. Both apps are listed in INSTALLED_APPS under core.settings. I tried deleting my sqlite database, all my __pycache__ and migrations folders, and running makemigrations and migrate again, to no avail. I even ran it for the accounts app, and ran it using --run-syncdb, and that still didn't work. The error is thrown during template rendering, on line 17 of my base.py, specifically the one that says, {% if user.email %}. I'm using Django 1.11.29 and Python 3.6.8. The database is a simple sqlite file in the project directory. Here's my models and views, along with the website's base template: lists/models.py from … -
why cv2.imread returns none when using django python?
i use opencv-python in django, but when i use cv2.imread, it just returns nonetype. How can i solve this problem? Exception Value: bad argument type for built-in operation