Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I get Is the server running on host "db" (192.168.176.2) and accepting TCP/IP connections on port 5433? when adding AUTH_USER_MODEL to settings
I have django web app with authentication. It all worked fine when I worked with sqlite and pipenv, but now I switched to docker and postgres and I constantly get an error: web_1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (192.168.176.2) and accepting web_1 | TCP/IP connections on port 5433? If I remove line with AUTH_USER_MODEL in settings.py this error goes away but I get other errors: web_1 | django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: web_1 | web_1 | ERRORS: web_1 | accounts.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'accounts.User.groups' clashes with reverse accessor for 'auth.User.groups'. web_1 | HINT: Add or change a related_name argument to the definition for 'accounts.User.groups' or 'auth.User.groups'. web_1 | accounts.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'accounts.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. web_1 | HINT: Add or change a related_name argument to the definition for 'accounts.User.user_permissions' or 'auth.User.user_permissions'. web_1 | auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'accounts.User.groups'. web_1 | HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'accounts.User.groups'. … -
Is it possible to convert this Python CLI application into a Django app?
I created a python application that takes input from a user for hours and minutes and then displays an onscreen notification when the system has reached the time of the total hours and minutes. I wanted to turn this into a web application with the use of Django is this possible? import time import os from threading import Thread def userTimeSet(): while True: try: hours = int(input("Number of hours? ")) minutes = int(input("\nNumber of minutes? ")) if hours > 0 and minutes > 0: interval_sec = (hours*3600)+(minutes*60) print(f"hours and minutes to seconds checking: {interval_sec}") elif hours > 0 and minutes == 0: interval_sec = (hours*3600) print(f"hours to seconds checking: {interval_sec}") elif hours == 0 and minutes > 0: interval_sec = (minutes*60) print(f"minutes to seconds checking: {interval_sec}") else: print("invalid.") futureTime = timeConfirmation(hours, minutes) # create and start the daemon thread print('Starting background task...') daemon = Thread(target=timeCheck, args=(futureTime, interval_sec,), daemon=True, name='Background') daemon.start() print('Main thread is carrying on...') time.sleep(interval_sec) print('Main thread done running.') break except ValueError: print("Enter a number.") def timeConfirmation(hours, minutes): print(f"{hours}:{minutes} (hours:minutes)") currentDateTime = time.ctime() print(f"\n Current Date and Time: {currentDateTime}") timeInSeconds = (hours * 3600) + (minutes * 60) futureTime = time.time() + timeInSeconds print(f"\n Timer Ends at: {time.ctime(futureTime)}") return … -
Trying to pass two arguments to celery from django
Im quite new to celery and im trying to pass two arguments from django to a celery task to use them. If i try to pass one argument, task works fine but if i add a second argument the whole thing collapses. Any idea? My original working view-celery look like this: view: def detection(request): if request.method == 'GET': . . . . . . . elif request.method == 'POST': stress = AddImg(request.POST, request.FILES) if stress.is_valid(): stress = stress.save(commit=False) try: stress.stressImg = request.FILES['stressImg'] stress.save() Detection.delay(stress.pk) # Celery Task except: print("Something went wrong! Try again.") task: @shared_task(bind=True) def Detection(self, stressID): print("\n\n\n\n\n\n===============START===============\n\n\n\n\n\n") print(stressID) I tried changing my view but still no result: username = request.user.username Detection.apply_async(args=[stress.pk, username]) # Celery Task It does not work if i use .delay(stres.pk, username) and def Detection(self, stressID, username): as it says it finds 3 arguments instead of two even though it doesnt say the same when argument is one less . Any help would be appreciated. -
why I can not link these two pages in my django project
I have 2 models named developer and skill and I maid a page for all of the developers to show them all and after that I want to make a link for any of them to navigate to the page that shows that specific developer informations the page that shows all the developers url is 'developers/' and its name is developers and the url of the second page is 'developers/id' and its name is developer but I have no idea because it navigates to 'developers/developers/id' I tried the page that shows the informations of a certain developer and it was ok but I have problem with this one cause it won't navigate pleassseee helpp here are my codes : views.py from django.shortcuts import render from .models import Developer, Skill # Create your views here. def show_developers(request): query = Developer.objects.all() context = {'devs': query} return render(request, 'users/devs.html', context=context) def show_single_developer(request, pk): query = Developer.objects.get(id=pk) context = {'dev': query} return render(request, 'users/single_dev.html', context=context) models.py from django.db import models # Create your models here. class Skill(models.Model): choices = ( ('Beginner', 'Beginner'), ('Junior', 'Junior'), ('Senior', 'Senior'), ) name = models.CharField(max_length=50) level = models.CharField(choices=choices, max_length=10) class Developer(models.Model): full_name = models.CharField(max_length=50) username = models.CharField(max_length=50) intro = … -
Django Server on Raspberry Pi
I got an Raspberry Pi 3 Model B+ and I already installed DJango. But I have an already existing Django Projekt on my Computer. Does anybody know, who I put my existing Django Server on my Raspberry Pi. Or does someone have a video recomendations for my problem? Thans alot! -
Can we create a superuser in django without SHA256 hashing?
I am trying to create a superuser in django. but i dont want hashing, can we do it? or how to decrypt SHA256 using hash and key? -
Should the calculated values be placed in the database?
In the project I use django, django-rest-framework, postgresql database + react/next on frontend. While developing the application, I came across a problem which, for lack of more experience, I am not able to solve on my own despite reading dozens of similar topics. In every topic one statement manifests itself: it depends. Keep the calculated totals in the database or calculate them with each query? The application is the simplest WMS (goods receipt, orders, goods release, invoices, etc.) with the ability to display reports with charts. The problem, however, is the volume of data totals I have never encountered. 1000 orders per day * 40 products on order * 25 work days * 12 months = 12 000 000 rows and from this data will be made calculations for example charts about profit, total revenue, amount of tax, etc. Documents will not be changed practically ever, totals values also. However, I will read the values quite often, whether in the customer panel about invoices, orders or charts.... I'm afraid that recalculating these values every time will be a bad solution. On the other hand, these values used for later calculations are quite a lot ~20/30, maybe more. I will certainly … -
Django - Flexible DateTimeField precision with timezone
I have a database model that includes a DateTimeField as below: class Person(models.Model): .... date_of_birth = models.DateTimeField() date_of_birth_precision = models.CharField(max_length=3, choices=( ('Y', 'Year'), ('M', 'Month'), ('D', 'Day'), ('H', 'Hour'), ('Min', 'Minute'), ('S', 'Second'), ('MS', 'Millisecond') )) I have USE_TZ = True in my settings.py. My indentation is to give the user the flexibility to input the date_of_birth with the precision he wants according to the selected date_of_birth_precision, and I have already handled the picker format according to the selected date_of_birth_precision. So, for an instance, the input could be 1992, 1992-07, 1992-07-28, 1992-07-28 15, 1992-07-28 15:33, or 1992-07-28 15:33:45 depending on the selected precision. To be able to accept those different formats in my form, I have extended the accepted formats in settings.py as below: DATETIME_INPUT_FORMATS += ( "%Y", "%Y-%m", "%Y-%m-%d %H", ) So far, everything is working fine except some time zone problems: As the time zone settings is enabled, the date_of_birth is converted from my local time zone to UTC before saving to database, and the application will translate it back to the user's local time zone wherever he/she is when trying to show the object details. This is working fine if I have time fractions in my input … -
can not create virtual environment for a django project
I'm trying to create a Django project from scratch. I executed django-admin startproject autoshine in my zsh terminal. Then I opened pycharm and run pipenv install in its local terminal to create a virtual environment for this project. But I got this error: raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/home/mohsen/.local/share/virtualenvs/autoshine-YDp111VE/bin/python' I realized that in the above directory, it can create a virtual environment but unfortunately it doesn't have any bin file. I don't know how to solve this problem. Thank you for your answers in advance. -
How to run commands in CLI with Railway.app
I have Django project deployed to Railway.app. I've installed Railway CLI, but can't understand how to run python manage.py makemigrations and so on in its CLI to make Django runnig. My laptop is running Windows 10 Home. Ho do I? -
python3 flasktest.py * Serving Flask app 'flasktest' * Debug mode: off Permission denied
**Whenever this error comes while running the flask **> python3 flasktest.py > * Serving Flask app 'flasktest' > * Debug mode: off Permission denied**** make sure you have Authenticated Admin Mode. or you can change port if the port used is 80 which is already a Reserved/custom port you might get this error. change the port and try the issue will be resolved. Error Occurs - enter image description here Error Resolved - enter image description here -
KeyError at /api/rooms/create-grade/ 'grade'
I don't understand this error one bit, I'm trying to do a basic create method but i get a KeyError This is serializer.py code class GradeCreateSerializer(serializers.ModelSerializer): grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display") class Meta: model = Grade fields = ["grade"] # ordering = ['-created_date'] def create(self, validated_data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user try: perms = Perm.objects.get(user=user) except: perms = None if user.role in ['OWNER', 'PARTNER']: school = user.owns.first() elif perms is not None: if user.role == 'STAFF' and perms.can_crt_grade_class: school = user.works instance = Grade.objects.create( grade=validated_data['grade'], school=school, ) instance.save() return instance what am i doing wrong?? -
Django custom management command to populate a many to many table
I am learning python and Django. I loaded a pretty big amount of data from csv files to my database. One of the csv files is describing a many to many relation. # models.py class Provider: name = models.CharField(max_length=25) product = models.ManyToManyField("Product", related_name="vendor_products") class Product: name = models.CharField(max_length=25) The generated database tables are core_provider, core_product and core_provider_product. I already have the data for the core_provider_product | provider_id | product_id | |-------------|------------| | 3 | 1001 | | 1 | 1003 | | 3 | 1007 | | 2 | 1001 | | 1 | 1002 | | 1 | 1001 | # etc and I am feeding them to the database with this custom management command: class Command(BaseCommand): # add_arguments snip def handle(self, *args, **options): for file in options["csvfile"]: with open(file) as f: reader = csv.reader(f) for row in reader: myprovider = row[0] myprovider_obj = Provider.objects.get(pk=myprovider) myproduct = row[1] myproduct_obj = Product.objects.get(pk=myproduct) myprovider_obj.product.add(myproduct_obj) which works fine. (takes about 6 mins to complete for a ~6000 lines file) But it feels terribly sloppy and inefficient. What is a better way to do this? I suspect Django already has a way to achieve this, but my search skills fail me and I … -
Group results from QuerySet
I am trying to collect the scores of each football match into a single list of the team points across the season. something like {1,3,3,3,1,....} My model is: class MatchScores(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True) game = models.ForeignKey('game', on_delete=models.CASCADE, blank=True) points = models.SmallIntegerField(blank=True, null=True) ... def __str__(self): return str(self.team) class Meta: verbose_name = "Match Scores" <QuerySet [<MatchScores: Red Team>, <MatchScores: Blue Team>,... >] The data added to the model is not in order, for example: Red Team 1 ... Red Team 3 ... Blue Team 1 ... Gren Team 1 ... Red Team 3... So i'm not sure how I collect each point for each team and group it together. I've tried points = MatchScores.objects.filter(profile__user=profile.user) all_points = [] for team in points: if "points" in team: all_points.append(team["points"]) but this returns TypeError: argument of type MatchScores' is not iterable -
Cannot access staticfiles using Pycharm Community Edition
I am using Pycharm Community Edition and I am new to this and Django as well. I am trying to fetch the background image for my webpage using a CSS file. This is the html file for that specific webpage. <!-- load the path to your static file--> {% load static %} <link rel="stylesheet" type="text/css" href="{% static '/music/style.css}"/> {% if all_albums %} <h3>Here are all my albums:</h3> <ul> {% for album in all_albums %} <li><a href="{% url 'music:detail' album.id %}">{{ album.album_title }}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any albums</h3> {% endif %} Here is the CSS file: body{ backgroud : white url("images/background.jpg"); } I have also changed the settings file like this: import os STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) You can see my project tree as under for more clarification: There are two errors that I am getting whenever I am refreshing the page: Please help me out! Is this because of COMMUNITY EDITION? -
Django notification for new chat message using ajax
I have used this code to send messages for my chat app, but when I add notifications it doesn't work. help me please Note: i use django-notifications-hq def send(request): if request.user.is_anonymous or request.user.is_active == False: return redirect('/accounts/login') if request.method == 'POST': sender = request.POST.get("username") receiver = request.POST.get("friend") message = request.POST.get("message") message = message.strip() if (message == "") or (request.user.username != sender): return redirect('/room/'+receiver) if sender == receiver: return redirect('/') newmessage = Message(sender=sender, receiver=receiver, message=message) newmessage.save() if newmessage.save(): sender = request.POST.get("username") receiver = request.POST.get("friend") message = request.POST.get("message") notify.send(sender, recipient=receiver, verb='Message', description=message, level='light') return HttpResponse("message sent") return redirect('/') -
Not able to change account details and not sending email once edited - Django
So... My main intention is that when a user edits his/her account and changes the email, the system has to change all the other info except email and send an email to the new email (inputted by the user) with a confirmation link. And once clicked, the system has to redirect the user to another page and change the email for that account. My code was changing all the information (without sending emails) before I added all the email thingy. After I add it, it doesn't change the other details from the account or send a confirmation email. view (I know there is some incomplete code which I need to add): class NormalUserEditView(generic.UpdateView): form_class = EditProfileFormNormal template_name = 'authentication/edit_normalprofile.html' success_url = reverse_lazy('profile') def form_valid(self, form): me = self.request.user.id myuser = User.objects.get(email=self.request.POST['email']) if myuser.email == myuser.email: return redirect('profile') else: current_site = get_current_site(self.request) email_subject = "Email has been changed for", myuser, " - some website" email_message = render_to_string('authentication/email_confirmation.html', { 'name': myuser.first_name, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(myuser.pk)), 'token': generate_token.make_token(myuser), }) email = EmailMessage( email_subject, email_message, settings.EMAIL_HOST_USER, [myuser.email], ) email.fail_silently=True email.send() messages.success(self.request, f'Account Edit: Successful') return super().form_valid(form) def get_object(self): return self.request.user -
For Loop in Django Template
I am working on a Django project. It has two Apps, one for explaining the topic, which has its own model, and views, and the second app is a quiz app, which has its own model and view, which will test the ability / learning of the students on each topics. The main idea is that for each topic of each book, there will be a quiz to test the ability of the students. my book explanation model is as follows: class book_explination(models.Model): title = models.CharField (max_length = 255) slug = models.SlugField(max_length= 250, null = True, blank = True, unique= True) lesson_no = models.CharField (max_length = 255) book_text = models.TextField (blank=False, null=False) book_text_explination = models.TextField (blank=False, null=False) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, null= True, blank=True) timestamp = models.DateField(auto_now=False, auto_now_add=True) def __str__(self): return self.title my view for the course model is as follows: def maths_topics(request): content_list = book_explination.objects.filter(title = "maths") return render(request, 'blog/maths_topics.html', {'content_list': content_list}) my url on url.py file is as under: path('nahwa_meer_topics/', maths_topics, name = 'maths_topics'), my quiz model is as follows: class Quiz(models.Model): title = models.CharField(max_length=255) book_name = models.CharField(max_length=255) slug = models.SlugField(blank = True) topic = models.CharField(max_length=255) number_of_questions = models.IntegerField() class Meta: verbose_name_plural = 'Quizes' def __str__(self): return self.title … -
Django instance in model form
There was a problem, I wanted to make an Django user object creation form, but it doesn't work. Exactly the same view with a different model works fine. I think the problem is how I transmit the data and instance in form. views: @login_required(login_url='login') def CreateRoom(request, pk): topic = Topic.objects.get(id=pk) form = RoomForm(data=request.POST, instance=room) if request.method == 'POST': if form.is_valid(): room = form.save(commit=False) room.host=request.user room.topic=topic room.save() return redirect('home') context = {'form': form, 'topic': topic} return render(request, 'room_form.html', context) forms: class RoomForm(ModelForm): def __init__(self, *args, **kwargs): super(RoomForm, self).__init__(*args, **kwargs) self.fields['themes'].queryset = self.instance.themes.all() class Meta: model = Room fields = '__all__' exclude = ['topic', 'host', 'participants'] -
reverse() doesn't resolve in django-rest-framework
django-rest-framework question: TLDR: reverse() doesn't work when everything I'm being told says it should. OK, Longer version: I have a route that works when I navigate to it. "/api/tag/" I have the route set where all my api routes are set router.register("tag", TagViewSet, basename="tag") TagViewSet is based off a ModelViewSet. If I comment this line out /api/tag/ doesn't work in the browser (so it's the authoritative place). The questions comes when I replace "/api/tag/" in my tests to reverse('tag-list') or reverse('tag:tag-list'). Neither resolves. When I put in (using debug mode) http://localhost:port/api/sldkfjalsdjfalskdjflaksj I get a list of things that resolve which has the line api/ ^tag/$ [name='tag-list'] So I'm wondering what else I can check for to make this reverse() or reverse_lazy() to work. -
How to save uploads models data to the user that is logged in, DjangoRestFramework
I want to post data {photos and caption} and I want it to save to the user that is logged in. I get this error 'Got a TypeError when calling Uploads.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Uploads.objects.create(). You may need to make the field read-only, or override the UploadsSerializer.create() method to handle this correctly.' In serializer.save() I put user = request.user as the argument, but that just gives me the error mentioned above. Putting that argument worked in other projects, but is giving me trouble, and I don't understand why even with the error. Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', ] class ProfileSerializer(serializers.ModelSerializer): user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True) class Meta: model = Profile fields = [ 'first_name', 'last_name', 'phone_number', 'bio', 'profile_picture', 'banner_picture' ] def to_representation(self, instance): my_fields = {'first_name', 'last_name', 'bio'} data = super().to_representation(instance) for field in my_fields: try: if not data[field]: data[field] = "" except KeyError: pass return data class UploadsSerializer(serializers.ModelSerializer): caption = serializers.CharField() file = serializers.URLField() id = serializers.IntegerField(read_only = True) class Meta: model = Uploads fields = ['id', 'file', … -
Switching between django development environment and production environment settings
I have a django project with different environments for production and development. The production environment runs on Postgresql while the development environment runs on sqlite3. I deployed on railway.app with all the necessary variables set. After installing railway cli and connecting my project, it's now running on production settings. Now I want to switch back to use development settings but it continues using production settings. I tried to unlink the project, then logout. Yet it's not working. -
I want to make a python web application live. But it shows
[1]It showed me. What's the solution? Please give me a solution -
How to use Django-simple-captcha on the admin login page?
I would like to add captcha on my django login form using Django Simple Captcha found here: http://code.google.com/p/django-simple-captcha/ This works great if you create a new form but I'm using the django.contrib.auth.forms the one that comes with django. Any idea how I might be able to implement captcha with the existing django auth views? Thank you! Please do not suggest using Google reCaptcha. My urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login') ,... ] My login.html <form class="fadeIn second" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary"> Login </button> </form> My Forms.py from captcha.fields import CaptchaField class MyFormCaptcha(forms.Form): captcha = CaptchaField() -
Why all the tags not displaying in home.html page?
So here's the problem, I'm trying to display all the tags on the homepage in a dropdown menu but the tags are not being called in base.html. But when I open the specific post itself, the Dropdown menu displays the tags used in that post. Why is that? Can't the tags used in each post be passed on to all pages? Btw I'm using Django-taggit for it. My views.py goes like this: def home(request, tag_slug=None): posts = Post.objects.all() # tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) context={ 'posts': posts, #introduces the content added in Post Class 'tag':tag, } return render(request, 'blog/home.html', context) And my urls.py goes like this: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('tag/<slug:tag_slug>/',views.home, name='post_tag'), ] My base.html goes like this: <li class="list-group-item list-group-item-light" style="text-align:center"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}">{{tag.name}}</a> {% endfor %} </div> </div> </li>