Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
where find job for python developer in 2024?
I’m very interested in the question of where an IT specialist can look for work in the USA in 2024 and what services I can generally provide, given that a lot of this is already being replaced by artificial intelligence I tried to find work on popular sites, but to no avail -
Django Limit Queryaset Objects by Foreign Key
Sorry for this question but I'm reasonably new to Django and it's eluding me. I am updating a system (think school) with users, classes (the teachable kind), etc. I have classes from the legacy system I want to bring into the new system, and I need to limit the list by a legacy_user_id. So far, I have this in models.py from account.models import Profile, LegacyUser class OldClassesManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(LegacyUser.legacy_id) class OldInstructables(models.Model): legacy_user_id = models.IntegerField(null=False) name = models.CharField(max_length=100, blank=False) [other stuff] objects = models.Manager() SOMETHING = OldClassesManager() def __str__(self): return self.name And this in views.py class OldClassList(ListView): model = OldInstructables I think my problem is that I don't know what goes where I put SOMETHING. Any help or insight would be much appreciated. -
As in django I am getting the intermediate all auth page after applying this thing also SOCIALACCOUNT_LOGIN_ON_GET = True?
As in django I am getting the intermediate allauth page after applying this variable also SOCIALACCOUNT_LOGIN_ON_GET = True it is not directly rendering me to the google mails...... Provide me the right approach to solve this error. The solution to the my question -
People to practice django?
Does anyone know if there are discord groups or places where I can find people to work on github projects with django or different frameworks to simply practice, it would help me a lot to learn from people who have more knowledge or experience Practice with people to gain experience -
Stream saved video in django
This is my Video Model class Video(models.Model): id = models.IntegerField(unique=True, primary_key=True) saved_location = models.FileField(upload_to="videos/") def __str__(self): return self.id This is my post methods which saves video inside media/videos class Video_api(APIView): permission_classes=[AllowAny] video_serializer = serializers.video_serializer def post(self,request): try: video_data = self.video_serializer(data=request.data) video_data.is_valid(raise_exception=True) data = video_data.validated_data video_instance = Video.objects.create( id = data.get('id'), saved_location = data.get('video') ) video_instance.save() return Response({"success":True}) except Exception as e: return Response({"success":False,"message":str(e)}) Now I want to stream the saved video inside the media/videos on get request. I don't want to download the video. I just want to stream the video when user performs get request. Please give me solution or any documentation related to it. -
RuntimeError: Failed to lock Pipfile.lock while installing django
I am trying to install django on my system using this command pipenv install django before this step, first i installed pipenv itself using pip pip install pipenv now i made my directory and when i try to install django in it, i get this error Installing django... Resolving django... Added django to Pipfile's [packages] ... Installation Succeeded Pipfile.lock not found, creating... Locking [packages] dependencies... Building requirements... Resolving dependencies... Locking Failed! [ ] Locking... No Python at '"E:\python installed\python.exe' Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\user\AppData\Local\Programs\Python\Python312\Scripts\pipenv.exe\__main__.py", line 7, in <module> # when invoked as python -m pip <command> ^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 1157, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\cli\options.py", line 58, in main return super().main(*args, **kwargs, windows_expand_args=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 1078, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\decorators.py", line 92, in new_func return ctx.invoke(f, obj, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\cli\command.py", line 209, in … -
setting up pgadmin4 on a VPS running ubuntu. Configuring it from nginx
The final instructions for configuring nginx for pgadmin4 read: location / { proxy_pass http://unix:/tmp/pgadmin4.sock; include proxy_params; } but I already had that proxy_pass configured for this: location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; <----HERE } the app_server refers to: upstream app_server { server unix:/home/boards/run/gunicorn.sock fail_timeout=0; } so, the proxy_pass is sort-of already taken. The instructions come from digitalocean -
Bootstrap JS giving an Uncaught TypeError, using modal and dropdown that requires js
I am developing a Blog App for a Project, i have noticed that for some reason i am no longer able to use my Modal toggle and my dropdown on my navbar. I am using the Bootstrap navbar and modal from bootstrap. Day or so ago i had it all working and no problems what so ever all working as excpted. Today i noticed a console error in my live preview that was giving due to a Null error. Console Error Bootstrap alert.js error Bootstrap Script link in html -
How can Django not see a defined url?
I've recently started learning Django for my course project, and my app works perfectly on my local machine. However, when another person clones the project from GitHub and runs it via Docker Compose, he gets an error 404 (trying to access the form/): Using the URLconf defined in app.urls, Django tried these URL patterns, in this order: admin/ api/ trText/ [name='tr_text'] The current path, api/form/, didn’t match any of these. The app/urls.py is: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path('api/', include('aitranslate.urls')), ] The aitranslate/urls.py is: from django.urls import path from .views import tr_text, translator urlpatterns = [ path('trText/', tr_text, name='tr_text'), path('form/', translator, name='translator'), ] Why does it see trText/ but doesn't see form/? And how can it work on my local machine without this problem? I would appreciate any help. -
I need help, first time learning Python
I am currently learning python and I am starting this small website using django. I typed in the terminal the following code $ django-admin startproject pyshop and I get this error. I am following a tutorial and I type it just as the tutorial shows, but I continue running into this error. At line:1 char:8 + $django-admin startproject pyshop . + ~~~~~~ Unexpected token '-admin' in expression or statement. At line:1 char:15 + $django-admin startproject pyshop . + ~~~~~~~~~~~~ Unexpected token 'startproject' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken Please any advice or help will be highly appreciated Thank you I've followed the tutorial, I tried to write the code several times, I searched online. -
Django custom domains feature
I'm currently working on a Django project that allows our users to create their own websites. One of the main features I've been working with is setting up custom domain capabilities. Here's what I did: I initially set the ALLOW_HOST setting to "*", then I've since devised a middleware to manage domain routing: First, it checks whether the host (using request.get_host()) corresponds to www.domain.com. If so, the middleware directs the request to the homepage application using the request.urlconf attribute. Next stop is checking if the host matches dash.domain.com. If it does, voila! The request gets routed to the dash app. And here's where it gets interesting. If neither of the above conditions is met, the middleware dives into the database to see if the host matches any of the registered site domains. If it finds a match, it redirects to the sites app with all the site-specific info. If not, it gracefully returns a 404 error. I've been thinking about the safety aspects of this configuration since ALLOW_HOST setting is "*", and I'd like your opinion. Do you think this approach is robust enough? -
Could not store data to custom user model from django shell
This is custom user model class class User(AbstractUser, BaseUserManager): username=None name = models.CharField(max_length=255) created_by =models.ForeignKey('self',on_delete=models.CASCADE,null=True,blank=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_superuser= models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField() USERNAME_FIELD = 'email' REQUIRED_FIELDS=['password'] objects = ContentManager() def __str__(self): return self.email This is my manager.py for User model class ContentManager(BaseUserManager): use_in_migrations=True def create_user(self, email,password, **extra_fields): if not email: raise ValueError("Email must be set") email = self.normalize_email(email) user = self.model(email=email,**extra_fields) user.set_password(password) user.save(using=self.db) return user def create_super_user (self,email, password,name, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_admin',True) extra_fields.setdefault('is_superuser',True) return self.create_user(email,password,**extra_fields) The problem is when I wanted to create the user from django shell by following method. python manage.py shell from api.models import Users user = User.objects.create_user(name="roshan",email="example@example.com",password="password") Even if put some data in name field, it is showing django.db.utils.IntegrityError: (1048, "Column 'name' cannot be null") error. I couldn't figure out where I went wrong. Please help. -
Django 5.0 login failing using admin as well as django.contrib.authLoginView and authenticate()
I have a problem in Django regarding logging my users in. I have created some users using the python manage.py makesuperuser. However, when trying to log one of them in it fails. This holds true for logging in to the admin page as well as my own login page: # I am using the django.contrib.auth.LoginView here, passing my own template urlpatterns = [ path("auth/login/", LoginView.as_view(template_name="login.html"), name="login"), ] With the following html: <h2>Login</h2> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Login"> </form> I have also tried using the django.contrib.auth.authenticate method, but it returns None when passing seemingly valid parameters for debugging purposes. def dashboard(request): print(type(authenticate(request, username = "user3", password = "user3_password"))) return render(request, "dashboard.html") # Prints nonetype If it is of any help, the code is inside Onedrive and when hosted on another computer it runs fine. I am using a python virtual environment with Django 5.0 installed. Any help would be appreciated. -
How to Set Event Reminders in Google Calendar for Multiple Users using Python API without Explicit Consent?
I'm developing an application where I need to set event reminders in multiple users' Google Calendars without explicitly asking for their permission. When exploring the Google Calendar API in Python, I encountered limitations due to privacy and security restrictions. I'm seeking insights into whether it's possible to set reminders for users' events without direct access or explicit permission for each calendar. Any guidance, code examples, or alternative methods using the Google Calendar API or other approaches that might help achieve this functionality would be highly appreciated. -
Сelery starting task every milisecond
Celery task schedule worked fine considerate amount of time. Now one of tasks launches and finishes successfully every couple of milliseconds. Did some search at git/stack and found that some older celery versions suffered from this, but now its fixed. Some users experienced this problem due to celery and django TZ difference, but this is not the case. celery version - 5.2.7 broker - redis flower screen -
The transition effect in in sign in and sign up page not working in django
My friend created a Sign in and sign up page which changes dynamically [https://github.com/codecxAb/anytimeFitness] I have done the django integration but it doesn't seem to change dynamically and instead giving and error "GET /signin/%7B%%20static%20'js/signin.js'%7D HTTP/1.1" 404 2792 My django project [https://github.com/RynoCODE/Gym-Website] -
Django graphene performance issue not related to the db but to the rendering
In Sentry APM I am able to see that most of the time spent was in the view.render I am assuming that this part is where the result from the db are being formatted but can't understand why it is taking a lot of time: -
Like count not showing in html and want to know if my models are set up properly
This is my models.py and index.html and views.py I tried the above and I am expecting to get total like count in my index page but i am only getting 0 likes why is that happening. And how do I fix it. `from django.contrib.auth.models import AbstractUser from django.db import models from datetime import datetime from django.contrib.auth import get_user_model class CustomUser(AbstractUser): profile_picture = models.ImageField( upload_to="profile_pics/", blank=True, null=True ) # Add any other custom fields as needed def __str__(self): return self.username class Post(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=1000) content = models.TextField() created_at = models.DateTimeField(default=datetime.now, null=True, blank=True) likes = models.ManyToManyField( get_user_model(), related_name="liked_posts", blank=True ) class Like(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return f"{self.user.username} likes {self.post.title}"` and this is my index.html `{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <h2>Welcome to the Home Page!</h2> {% for post in posts %} <!-- Display post details as needed --> <div> <h3>{{ post.title }}</h3> <small>{{post.created_at}}</small> <p>{{ post.content }}</p> <form id="likeForm{{ post.id }}" data-post-id="{{ post.id }}" method="post"> {% csrf_token %} <input type="submit" value="Like post"> <span id="likeCount{{ post.id }}">{{ post.likes.count }}</span> Likes </form> </div> {% endfor %} <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function () { $('form[id^="likeForm"]').submit(function (event) { … -
Django Auth Ldap on Windows
Is there any way to make django ldap authentication I am trying to pip install django-auth-ldap but keep getting Could not build wheels for python-ldap, which is required to install pyproject.toml-based projects then I searched and find this project but those settings configuration wont work. Reading docs. but when I try to install ldap but it isn't working... Any help would be appreciated, thanks from now :) I've tried installing django-auth-ldap and django-python3-ldap but neither installing or configuring didn't work... -
Calculating fees for smart contracts, such as USDT-TRC20, on the Tron blockchain
I'm currently engaged in a blockchain project, and one of the key components involves the creation of withdrawal transactions. However, I'm facing the challenge of displaying the transaction fee before broadcasting it to the blockchain. I am well aware of the intricacies involved in calculating smart contract fees on the Tron blockchain. Do you have any suggestions on how to obtain the necessary energy and bandwidth for a withdrawal and how to calculate the transaction fee? I am using tronpy and haven't found a helpful method for this purpose I did not found any helpful way for get contracts fee -
Django Q implement to send periodic emails
I have a Django project with several merchant accounts. When they log in using a URL, a certain view is called that aids with login and authentication. In addition, the same method determines if the merchant's plan expires in a month. If so, the function notifies you by email about the same problem. The problem now is that the view function won't execute if the user doesn't log in, which means he won't get any mail. Can I then have an automatic feature that delivers the mail and verifies each merchant? To notify merchants of their plan expiration even if they don't log in, I want a function in Djnago-Q to run even if the URL is not hit and after a set amount of time. -
Django Custom User Model Admin
In a simple self-training using Django, I'm facing the following problem: 1- I've written a custom user model with two extra fields: phone +fuck 2- I've created a custom admin using custom forms 3- In settings: added AUTH_USER_MODEL = "accounts.CustomUser" where accounts is the app name 1- In admin panel, when trying to add a new user, it doesn't display any of the extra fields and this is a problem, also in the case of editing an existing user. 2- In admin: the last statement is: admin.site.register(CustomUser, CustomUserAdmin) but if i replace it with: admin.site.register(CustomUser), every thing is well and it executed as expected enter image description here [[enter image description here](https://i.stack.imgur.com/qgh3r.png)](https://i.stack.imgur.com/mXrK4.png) -
Create a for loop in python django with 20 teams of 100 matches of 10 rounds of matches
Create a for loop in Python Django with 20 teams, each playing 100 matches of 10 rounds. Ensure that no matches are repeated, and in each rounds, no teams are repeated across the 10 rounds. if n == 2: pair = [(1, 3), (4,5), (6,7), (8,9), (10,11),(12,16),(14,15),(13,17),(18,19),(2,20)] elif n == 3: pair = [(12,13), (16,17), (2,8), (9,14), (4,19),(10,15),(5,11),(14,20),(1,7),(3,18)] elif n == 4: pair = [(4,6), (5,7), (8,10), (15,20), (13,16),(14,18),(3,9),(1,19),(2,12),(11,17)] elif n == 5: pair = [(12, 15), (7, 9), (17, 19), (4, 8), (6, 10), (13, 18), (2, 3), (14, 16), (11, 20), (1, 5)] elif n == 6: pair = [(10, 13), (5, 9), (2, 7), (14, 19), (1, 8), (6, 12), (17, 20), (4,18), (11, 15), (3, 16)] elif n == 7: pair = [(4, 15), (9, 20), (3, 14), (1, 10), (7, 17), (2, 16), (5, 18), (6, 8), (11, 13), (12, 19)] elif n == 8: pair = [(4, 14), (9, 18), (5, 17), (1, 11), (7, 16), (3, 19), (6, 20), (8, 15), (10, 17), (2, 13)] elif n == 9: pair = [(3, 13), (9, 19), (1, 16), (5, 10), (6, 11), (2, 4), (8, 12), (7, 14), (15, 17), (18, 20)] elif n … -
Button troubleshooting in Django
By pressing the button, the sale is over and the highest price is announced as the winner. Here, the button performs the function of the button defined at the beginning of the template file. views.py: def page_product(request, productid): product = get_object_or_404(Product, pk=productid) off = Bid_info.objects.get(product=product) bid_max = Bid_info.objects.filter(product_id=productid).latest('bid_price') if request.user == off.seller: close_button = True off.bid_price = bid_max Bid_info.checkclose = True messages.success(request, f"The offer was closed at {bid_max} $") else: close_button = False context = { 'product' : product, 'form': form, 'off' : off, 'close_button' : close_button, 'bid_max' : bid_max } return render(request, 'auctions/page_product.html', context) def bid(request, bidid): product = get_object_or_404(Product, pk=bidid) if request.method == 'POST': user = request.user if user.is_authenticated: bid_price = Decimal(request.POST.get("bid_price", False)) other_off = Bid_info.objects.filter(product=product).order_by("-bid_price").first() if Bid_info.checkclose == True: messages.warning(request, "it sells.") else: Bid_ = Bid_info(product=product, seller=request.user, bid_price=bid_price) Bid_.save() return redirect('page_product', bidid) page_product.html: <form method="post"> {% csrf_token %} {% if close_button %} <button type="submit" class="btn btn-primary">Close</button> {% else %} <p> {{off.seller}} is seller!</p> {% endif %} </form> -
Trying get excel table with using padnas from django project
I try get data from table in my Django project from local server But have a problem after run programm with pandas code: c:\Users\kadzutokun\Desktop\tables.py:3: FutureWarning: Passing literal html to 'read_html' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object. tables = pd.read_html( C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py:666: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup. soup = BeautifulSoup(udoc, features="html5lib", from_encoding=from_encoding) Traceback (most recent call last): tables = pd.read_html( File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 1245, in read_html return _parse( File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 1008, in _parse raise retained File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 988, in _parse tables = p.parse_tables() File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 248, in parse_tables tables = self._parse_tables(self._build_doc(), self.match, self.attrs) File "C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py", line 603, in _parse_tables raise ValueError("No tables found") ValueError: No tables found PS C:\Users\kadzutokun> & C:/Users/kadzutokun/AppData/Local/Programs/Python/Python310/python.exe c:/Users/kadzutokun/Desktop/tables.py c:\Users\kadzutokun\Desktop\tables.py:3: FutureWarning: Passing literal html to 'read_html' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object. tables = pd.read_html( C:\Users\kadzutokun\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\html.py:666: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass …