Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReactJS with Python as Backend
What is the best approach to use ReactJS as front end and Python as a backend? I already built a tool using Tkinter which have simple UI. I want to use ReactJS and rebuild this application that anyone can install on their desktops. Is it possible? If so can anyone briefly explain the workflow or any online resources would be appreciated. Thank you! (I have a basic knowledge using Djnago) -
Is Nginx needed using an openshift router in django app?
I have a question. Is it necessary to use nginx when using an openshift router. I will add that the application is written in Django and uses gunicorn. If Nginx is needed please explain why. greetings -
CREATING DOWNLOAD LINK WITH EXPIRATION THROUGH EMAIL DJANGO/PYTHON
I'm building a function that sends an email with pdf download link that expires in a day.The download link is unique and looks like this: http://127.0.0.1:8000/download?e=eJzTyCkw4AozNDMwsriXoAIqENGQ==&h=aa23401994b8 And I added this on my views.py if expiring_date > day_opened: with open('example.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="example.pdf"' return response else: with open('yourLinkHasExpiredPage.html', 'rb') as html: response = HttpResponse(html.read(), content_type='text/html') return response I don't have a problem returning the pdf file, the problem starts when I try to open the link again after a day and it returns to server 500 error instead of the page that says the link has expired. -
How to build one to one chat system with django
Is there any django expert who has experience to build chat system quite similar to Facebook. I want to ask that how can I build chat with django, do I have to use django restframe also? And what is the easiest and robust way to create chats. I have search about it and it feels like more harder than I imagined. I am actually feeling discouraged after searching about implementing chats in website. So if you guys have experience with chat system already than tell me something really helpful or give me complete guideline to build chat system. Many many thanks in advance to all my seniors. I am new with django so please briefly explain your answers. -
How to negate a queryset function in django?
I have this queryset in django 3.1 class AuthenticationQuerySet(InheritanceQuerySet): def expired(self): return self.filter(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD) def active(self): return self.filter(status__in=["PENDING"]).filter( date_created__gt=timezone.localtime() - self.model.ACTIVE_THRESHOLD ) Notice that in active function there is just negation from expired function in the second filter. I did it like this, because I could not figure out a more simple solution. But it feels like there should be a way to negate what a queryset function filters? What I imagine and what feels much more natural is something like class AuthenticationQuerySet(InheritanceQuerySet): def expired(self): return self.filter(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD) def active(self): return self.filter(status__in=["PENDING"]).not(self.excluded) Is something like this possible? or should I just go for something like: class AuthenticationQuerySet(InheritanceQuerySet): def expired(self): return self.filter(self._expired_condition) def active(self): return self.filter(date_resolved__isnull=True, status__in=["PENDING"]).exclude(self._expired_condition) @property def _expired_condition(self): return Q(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD) ? but this seems just really ugly and hacky... Thanks for suggestions! -
Broken Comment section after implementing like button AJAX in Django Blog
For some reason nobody is able to make comments after I implemented the like button, which requires the user to be logged. @login_required def like(request): if request.POST.get('action') == 'post': result='' id = request.POST.get('postid') post= get_object_or_404(Post, id=id) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 result= post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result, }) The error says: ValueError: invalid literal for int() with base 10: 'xxx-xxx-xxx (slug parameter) ValueError: Field 'id' expected a number but got 'xxx-xxx-xxx' (slug parameter). I'm really lost with this, I think that the Ajax code may not be working well or not well coded: $('#myForm').trigger("reset"); $(document).on('click', '#like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: "{% url 'like' %}", data: { postid: $('#like-button').val(), csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] console.log(json) }, error: function (xhr, errmsg, err) { } }); }) </script> The button works perfectly well. The web only get broken when u try to add a comment. path('article/<slug:slug>/comment/', AddCommentView.as_view(), name='add_comment'), class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'add_comment.html' def form_valid(self,form): form.instance.post_id = self.kwargs['slug'] return super().form_valid(form) Any suggestion will be appreciated. Thanks in advance. -
Keep getting random No reverse match error in django blog page while trying to make a comment section appear under each post?
User posts is a page where the logged in user can view their own posts and it functions fine. I don't know why django says the error is in my base template near the html navbar of the page. Here is my comment model class comment(models.Model): linkedpost = models.ForeignKey(Post, related_name="postcomments", on_delete=models.CASCADE) commentauthor = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.linkedpost.title My home page template where the blog posts are looped through and the comments are also looped through under each post. {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> <div> <h2>Comments</h2> {% for cmnts in post.postcomments.all %} #<a class="mr-2" href="{% url 'user-posts' cmnts.author.username %}">{{ cmnts.commentauthor }}</a> <small class="text-muted">{{ cmnts.date_posted|date:"F d, Y" }}</small> <p class="article-content">{{ cmnts.body }}</p> {% endfor %} </div> </div> </article> {% endfor %} Project Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/loginpage.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('passwordreset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='passwordreset'), path('passwordreset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='passwordresetdone'), … -
Passing data between veiws.py and template.html in django
I am new in Django. I want to write a very simple code to create a string in views.py and shows in an html file in templates.: views.py from django.shortcuts import render from django.http import JsonResponse def index(request): F = 100 response = str(F + 10) response1 = {"Main": response} template_name = "homepage.html" return render(request, template_name, response1) urls.py urlpatterns = [ path('', views.index, name='homepage.html'), path('admin/', admin.site.urls)] homepage.html <html> <head> <h1>User Information</h1> </head> <h2>Answer: {{response1}}</h2> </html> What I get on webpage is the headers without {{response1}} -
ModuleNotFoundError: No module named 'mysite.polls' in django tutorial while testing
I am coding along tutorial from django documentation site: https://docs.djangoproject.com/en/3.1/intro/tutorial05/ I got a following problem: While trying to run test on my app (with: py manage.py test polls in Pycharm commndline) i get following error: > ImportError: Failed to import test module: mysite.polls Traceback > (most recent call last): File > "C:\Users\micha\Anaconda3\envs\DjangoTutorial\lib\unittest\loader.py", > line 470, in _find_test_path > package = self._get_module_from_name(name) File "C:\Users\micha\Anaconda3\envs\DjangoTutorial\lib\unittest\loader.py", > line 377, in _get_module_from_name > __import__(name) ModuleNotFoundError: No module named 'mysite.polls' The file structre of my project is as follwoing: link to the directory tree img It looks like testing unit automaticcaly adds 'mysite' in front of 'polls' What i tried: I have tried to lookup for an answer in django test documentation. Only solution that i was able to find was to change command to like like this: py manage.py test polls.tests Then it runs my test properely. As far as I understand django documentation, django should automatically find every 'test*' file in polls yet in case of mine it cannot find 'polls' module. Can you tell me why it happens? -
uWSGI + Django - Confused between no of process and threads while deploying
I think i am stuck in some basics. My system has 8 cores (4 physical and 4 logical cores) I developed a basic django application. I want to deploy it with uWSGI. To achieve concurrency I have to specify number of processes and threads in uWSGI config. Here come's the confusion. To start with, I have 2 options Option 1: No of process = 8 Option 2: No of process = 4 No of threads per process = 2 https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#adding-concurrency-and-monitoring If I get 8 simultaneous request, what is the impact in both the options? What does the no of thread per process exactly means here? If my app does not use multithreading, will option 2 will be useful to me? Python GIL will be disabled in option 2, so there must be some disadvantages to it. I appreciate, if someone can guide me. Thank You! -
Reorder Django ModelForm Fields After Adding Additional Field
I have this model: class StudentResult(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) test = models.FloatField(default=0) exam = models.FloatField(default=0) I created a ModelForm from it and added session_year (which is not in the model) as shown below: class EditResultForm(FormSettings): session_list = Session.objects.all() session_year = forms.ModelChoiceField( label="Session Year", queryset=session_list, required=True) def __init__(self, *args, **kwargs): super(EditResultForm, self).__init__(*args, **kwargs) class Meta: model = StudentResult fields = ['subject', 'student', 'test', 'exam'] session_year displays as the last form element. How can I display it as the first form element. I tried: fields = ['session_year', 'subject', 'student', 'test', 'exam'] But since session_year is not in the model, it raised an error. How can I achieve this? -
Django not rendering template from class based view
I only need to display a column from my table as dropdown on the template. I'm using class based view and not sure what am I doing wrong since i just need to diplay the data as it is. <app/models.py> class DBModel(models.Model): id = models.BigAutoField(primary_key=True) url = models.TextField(blank=True, null=True) user_name = models.TextField(blank=True, null=True) class Meta: db_table = 'demotable' def __str__(self): return str(self.url) <app/forms.py> class ChooseForm(forms.ModelForm): list = forms.ModelChoiceField(queryset=DBModel.objects.all().distinct(), empty_label="(Nothing)") <app/views.py> class ChooseView(CreateView): template_name = 'form_list.html' form_class = ChooseForm def get(self, request, *args, **kwargs): form = self.form_class(request.GET) return render(request, self.template_name, {'form' : form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) return render(request, self.template_name, {'form': form}) <templates/form_list.html> <form method="post"> {% csrf_token %} {{ form.list }} <button type="submit" class="btn btn-primary btn-border" name="show-list">Continue..</button </form> <app/urls.py> urlpatterns = [ url('main_page/', views.ChooseView.as_view(), name='main_page') ] -
Django: Haystack with ajax
Let me cut to the chase. All i want is to render a SearchQuerySet as a list/dictionary or anything that can be serialized by JsonReponse. Is there a method or special technique that achieved this? -
Django: How to filter objects on values coming from functions?
I have two models: Company and Service. In order to filter on Service objects based on the company website, I do the following: company = Company.objects.get(id=some_id) service = Service.objects.filter(website=company.website) Now, suppose I have a function f(website) that only returns the hostname of the website, and I want to filter for instances where f(website of the service) would be equal to f(website of the company). Now, company = Company.objects.get(id=some_id) service = Service.objects.filter(f(website)=f(company.website)) gives syntax errors (obviously). What is the proper way to do this simple filtering? -
creating queues dynamically with realtime data, and assigning task to those quese in celery in python
i am getting realtime data of live football matches and i want to create a multiple queues for every matches in celery. For example whenever i will get data for match_id = 203, than i will create one queue named 203 and i will submit my task of processing this match data in 203 queue, like this for each match there should be a queue, where i will process all incoming data for that match only. mode of incoming data will be like this, sometime i can get data for match_id 203 than after i can get data for match_id = 204 or match_id=3,and agaiin new data for match id=203 means there will not be any sequence or pettern. and there will be multiple incoming updates for each match and in no particular order. All creation of queues for each match and assigning task to their queues respectively, should happen dynamically I wont know in advance how many matches will be there, there can be maximam 200 live matches at any time How i can achieve this in python using celery, i am using redis with celery -
What makes the developer efficiency low?
I am conducting a survey to understand what blocks a software developer in their day to day work life to focus primarily on coding. Please help out with filling a 2 minute survey -> https://forms.gle/XsdPevQMQGMfYYkR8 This is a part of a study and I plan to seek feedback from people who have had a first hand experience developing software. -
Fatal error and unable to create django process
So I am trying to create a new project with Django. However, when I tried to create a new project, I got an error message. Here's what my command prompt looks like so far Microsoft Windows [Version 10.0.19041.572] (c) 2020 Microsoft Corporation. All rights reserved. C:\Users\Ben>cd Documents C:\Users\Ben\Documents>django-admin startproject photoshare Fatal error in launcher: Unable to create process using '"c:\users\ben\appdata\local\programs\python\python38-32\python.exe" "C:\Users\Ben\AppData\Local\Programs\Python\Python38-32\Scripts\django-admin.exe" startproject photoshare': The system cannot find the file specified. C:\Users\Ben\Documents> I've never had this issue before, so....hoping someone can help me figure it out?! I've been tying my head around it all afternoon. -
Can't get Django to render template
I am trying to get my view to render my HTML through a POST request from javascript but I can't make it work using the onclick="" function of an tag? I'm struggling to find an answer as I'm not sure how to pose the question so I will just try to show.... My view looks like: def photos(request): BASE_DIR = Path(__file__).resolve().parent.parent workingDir = os.path.join(BASE_DIR, 'main', 'static', 'gallery', 'img') vehicle = request.POST.get('car') # Assigns the 'pass_vehicle' JS function returned value to 'vehicle' variable print(request) # Debug number_of_images = len(os.listdir(f'{workingDir}/{vehicle}/')) - 1 # Retrieve number of images within folder for <p> tag cols = [(3, 6, 3), (8, 4), (6, 6), (4, 8)] # CSS columns used below for displaying images in specific layout on HTML page htmlText = [] imgNum = 0 while imgNum <= 25: # During development limit number of pictures to display (will have specific amount in deployment) for colNum in cols: for x in range(len(colNum)): # Generate HTML to display each image within folder within the CSS column layout above imgNum += 1 inputText = f'<div class="col-6 col-md-6 col-lg-{colNum[x]}" data-aos="fade-up">\n <a href="/main/static/gallery/img/{vehicle}/img_{imgNum}.jpg" class="d-block photo-item" data-fancybox="gallery">\n <img src="/main/static/gallery/img/{vehicle}/img_{imgNum}.jpg" alt="Image" class="img-fluid">\n <div class="photo-text-more">\n <span class="icon icon-search"></span>\n</div>\n</a>\n</div>' htmlText.append(inputText) context = … -
Uploading images to an SQLite Database
I am looking for some advice please. As a beginner learning Python, what would be the most straight forward way to allow a user to upload images and .pdf documents to a SQLite database through a GUI. OR, perhaps I am looking at webpage solution here - Django has come up in some initial research that I did. Does anyone have experience of this? Any advice is much appreciated. -
How to create multiple collapse when i use for loop in Django template
How to create multiple collapse when i use for loop in Django template I have created a django template which show lists of subjects and i want to create collapse for each subject such that on click of it , it shows the video . For now i have used django template html code : <div id="accordion"> {% for lesson in course_posts.lesson_set.all %} <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0 text-center"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{lesson.name}} </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <iframe width="100%" height="400px" src="{{lesson.youtube_url}}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> </div> {% endfor %} </div> -
Django Admin - list of all instances for Tabular.Inline
Sorry I am beginner in Django.I have model with foreign key and TabularInline view. How I can visualize list of all instances instead of selection from list of instances. enter image description here -
Django: filtering on ManyToMany only return exact matches
let's say I have a model like class Group: users = ManyToMany(User, related_name='groups') and I have groups with a different mixture of users group1 = Group(users=[user1]) group2 = Group(users=[user1, user2]) group3 = Group(users=[user1, user2, user3]) How would I go about querying for groups only with user1 and user2? I'd like to do something that's like Group.objects.filter(users=[user1, user2]) -> [group1, group2] but I'm getting TypeError: Field 'id' expected a number but got [<User: user1>, <User: user2>]. if I do Group.objects.filter(user__in=[user1, user2].distinct('id') it returns back all the groups [group1, group2, group3] I know how to go through the User instance to get all of the user's groups but I specifically want to go through the Group model. I imagine I may have to do some type of matching with the ORM... maybe a subquery? -
Why is django telling me im missing the 'request' positional argument even though im calling it?
Ok, a little bit of context first. My view ProjectView has a link which takes you to another view called memorandum_download, which has the only function of downloading the memorandum assigned to the Project model shown in project view. The memorandum is stored as a FileField in the project model. I take the slug of the project as an argument via url, which is created by slugify(project.name). Then in the second view (memorandum_download), I try to request the project based on the slug, and download the memorandum assigned to it with a FileResponse. The problem is, that django keeps telling me that im missing the request argument even tough im using, it. Sending source code of urls.py and views.py. def download_memorandum(request, slug): project:Project = get_object_or_404(Project, slug=slug) response = FileResponse(open(project.memorandum, 'rb')) return response urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('<str:slug>/', views.ProjectView.as_view(), name='project'), path('<str:slug>/memorandum', views.download_memorandum(), name='download'), ] Apart from that, im just starting to learn how to manage FileFields with django, so any feedback or improvements on my actual download system are welcomed -
how to send mails to the users who are inactive for 2 weeks
I am building a subscription type Django model in which i have to identify the users who are inactive for certain duration, say 2 weeks an send mail, does any one have an idea how it could be done -
can anyone help me regarding change of quiz app to annual exam in django app
I am newbie to django app , can anyone help me out regarding the heading in the django model on admin panel of my app Here is a sample for idea which is marked with black