Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic Display of Address on Google Map Triggered by Selection
I have a list of products that I display on a web page. Each product has a seller with an address. When I click on a product, I want a Google Map on the same page to show the address of the seller of that product on the map. I'm using Django for my server-side technology but the solution I'm looking for can be pure HTML/CSS/JavaScript which I will then integrate. Any help would be greatly appreciated. Thanks. -
can't find mod_wsgi.so after yum installation
I'm trying to move an old client to a new server and get WSGI working for his django backend. I installed wsgi using yum; the httpd -M command shows that it is installed. However, the file mod_wsgi.so appears to be nowhere on the server. Earlier I had tried to include a WSGIScriptAlias command in the httpd.conf file, and received this error: /etc/apache2/conf.d/includes/pre_main_global.conf.tmp: Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration --- /etc/apache2/conf.d/includes/pre_main_global.conf.tmp --- 1 ===> WSGIScriptAlias /spdre /home/pdr887629/django/sullivan/wsgi.py <=== --- /etc/apache2/conf.d/includes/pre_main_global.conf.tmp --- Another Stack Overflow solution on that error message said I should include this first: LoadModule wsgi_module modules/mod_wsgi.so But the mod_wsgi.so file does not actually exist in that directory, or anywhere else on the server. How can I get mod_wsgi working? Do I need to reinstall via another method, or is there somewhere I can go from here (with the current install)? Thank you for any assistance. -
The proper way to upset field in Mongodb using Djongo?
I have following Person model class Person(models.Model): id = models.ObjectIdField() # ----------------- CharFields ------------------ name = models.CharField(max_length=255) city = models.CharField(max_length=255) status = models.CharField(max_length=20) phone_number = models.CharField(max_length=10) objects = models.DjongoManager() def __str__(self): return self.name and comment model class Comment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) comments = models.JSONField() objects = models.DjongoManager() The add_coment method looks like this @api_view(['POST']) def add_comment(request): comment_data = JSONParser().parse(request) comment_serializer = CommentSerializer(data=comment_data) if comment_serializer.is_valid(): comment_serializer.save() return JsonResponse(comment_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(comment_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then I call add_coment methods twice with the same request instead of update this field it create the other document. What is the proper way to perfume upsert operation? -
Creating Keycloak user from docker container
I am having problems creating users using the Keycloak REST API from my docker container running a Django application. The following works using postman: Fetch admin token Create user: The following does NOT work in python, and returns 401 Unauthorized: Fetch admin toke (This successfully returns a token): Create user (This returns 401): I am using the exact same user credentials in both scenarios,and since I am able to get this to work in postman I don't think there's any problem with access/roles etc. Any help is greatly appreciated. Thanks! -
Django model.save() not updating model instance
I am trying to update a handful of fields if the record has been marked as deleted. When I debug, I can see that the values are being assigned in the view, but not being updated in the DB. I'm not sure what I'm missing. views.py contact_formset = ContactFormSet(request.POST, prefix='contact') for contact in contact_formset.deleted_forms: contact = contact.cleaned_data print(contact) instance = contact['id_cnt'] contact_id = instance.id_cnt contact_object = get_object_or_404(AppContactCnt, id_cnt=contact_id) contact_object.deleted_cnt = True contact_object.date_deleted_cnt = '2020-11-23' contact_object.deleted_by_cnt = 'adeacon' contact_object.save() -
How to combine these 2 fields?
I have total Count of comments for 1 movie comments = Comment.objects.filter(movie_id=object_id).count() How to Count all comments in time period (start_date,end_date) I know About Q filter filter=Q(Comments__pub_date__range=( start_date, end_date)) so, how compine those two Fields and get the answer?? -
DJANGO + windows: .bat file: open a command prompt and run the commands
I have to run the following set of commands after opening a windows cmd prompt D: cd Dev\project\backend .\venv\Scripts\activate python manage.py runserver How to write a script(.bat) file for running these commands and the runserver will stay showing the output I tried to put these commands in django.bat and double click, but a cmd window opens and within a fraction of second it closes. Dont know what happened -
What answer to make on OPTIONS request in CRUD on Django?
I have code that handles django requests. It must respond to user requests. He has registered answers to POST and GET requests. But the frontend sends an options request, and it makes no response. What should I prescribe? @csrf_exempt def user_api(request, email=""): # if request.method == "GET": # users = User.objects.all() # users_serializer = UserSerializer(users, many=True) # return JsonResponse(users_serializer.data, safe=False) # if email is not specified in address line by http://127.0.0.1:8080/user/some-email # then django returns data of ALL objects in json print(email) print(request.method) if request.method=="OPTIONS": return if email == "" and request.method == "GET": users = User.objects.all() users_serializer = UserSerializer(users, many=True) return JsonResponse(users_serializer.data, safe=False) elif email == "" and request.method == "POST": user_data = JSONParser().parse(request) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("New user was created successfully", safe=False) else: return JsonResponse("Failed to create user", safe=False) else: # search the specified email and return data in json if request.method == "POST": try: user = User.objects.get(email=email) user_serializer = UserSerializer(user, many=False) print(user_serializer.data) return JsonResponse(user_serializer.data, safe=False) except ObjectDoesNotExist: return JsonResponse("User does not exists", safe=False) elif request.method == "PUT": user_data = JSONParser().parse(request) user = User.objects.get(email=user_data['email']) # щоб знати конкретного юзера, інфу якого змінюватимемо user_serializer = UserSerializer(user, data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("User information was updated … -
django-cacheops with aws redis Encryption
I have set up redis with Encyption in transit and rest. I have come across https://dev.to/yuki0417/easy-way-to-connect-to-amazon-elasticache-redis-with-password-from-django-app-40il and Connect to AWS ElastiCache with In-Transit Encryption. As I am using https://github.com/Suor/django-cacheops shows nothing regarding ssl how can I implement ssl to use the aws redis with encryption? I have tried CACHEOPS_REDIS = { 'host': "redis://{}".format(os.environ.get("REDIS_LOCATION")), 'socket_timeout': 3, 'ssl': True, } -
Show values of last three months in columns and change column names to current month and of 2 months before
I have a csv file containing column names of the months. I made a dataframe (df24) containing the columns as followed: [['Januari','February', 'March','April','May','June', 'July','August','September','October','November','December']] I used dictionary to push the values to my frontend context['Table']= df24.to_numpy() My frontend html looks like this: <tr> <th>Current Month</th> {%comment%}Display name Current Month{%endcomment%} <th>Current Month-1</th> {%comment%}Display name Current Month-1{%endcomment%} <th>Current Month-2</th> {%comment%}Display name Current Month-2{%endcomment%} </tr> <tbody> {% for y in Table %} <tr> <td>{{ y.0 }}</td> {%comment%}Current Month{%endcomment%} <td>{{ y.1 }}</td> {%comment%}Current Month-1{%endcomment%} <td>{{ y.2 }}</td> {%comment%}Current Month-2{%endcomment%} </tr> {% endfor %} I want to display three columns with their corresponding values in the html above according to the current month, the month before current month and the month before that. It needs to keep 'moving'. Is it also possible to change the column names 'Current Month', 'Current Month-1', 'Current Month-2' to the actual current month name and current month-1 , -2? -
How to add apple-app-site-association file to Django project
I am new to Django. I need to test how Universal Links works with web-site which is on Django. I added my site url to xcode Associated Domains and added apple-app-site-association file to root folder on my server which is used as root foolder by Django. This way doesn't work. My apple-app-site-association file works nice, I have alredy done that with github pages and it works fine. But i think there is another to add apple-app-site-association file in Django. Thank you in advance for help! -
Django Is Inserting instead of Updating the AutoField?
I am trying to perform crud operations but when i try to update then django add's a new row in the db with the new pk 'id'. I am using autofield set to primary_key = True(default). Views.py @login_required def edit(request,id): note = UserCreatedNote.objects.filter(pk=id,user=request.user) if request.method == 'POST': form = AddNoteForm(request.POST,note[0]) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user //cause i have excluded this field in form. form_data.save() form = AddNoteForm(instance=note[0]) context={'note':note[0],'u_form':form} return render(request,'edit_note.html',context) -
Django elasticsearch_dsl only 10 results getting returned
currently my Django elasticsearch view only returns 10 results where I expect at least 15 results to be returned. After some searching on the web I figured out that size = 10 See more here: How to Get All Results from Elasticsearch in Python But I don't understand how my syntax has to look like, this is how i query for post objects: post = PostDocument.search().query("multi_match", query=qs, fields=["title", "content", "tag"]).to_queryset() I also tried: post = PostDocument.search(size=1000).query("multi_match", query=qs, fields=["title", "content", "tag"]).to_queryset() But with no success. Can smb. tell me how to change the default size to a higher value than 10 using elasticsearch_dsl with Django. Thanks in advance -
Unit test django inline formset factory
I'm working on a project using Python(3.8) and Django(3.1) in which I have few models as Course, Module etc and for the forms, I have created an Inline Formset factory (to provide the user a better experience while adding modules to courses). Now I want to unit test that form, what should be the approach and how it can be achieved? Here's my forms.py: MYFormSet = inlineformset_factory(Course, Module, fields=['title', 'short_descp'], extra=1, can_delete=True) and here are my models: class Course(models.Model): instructor = models.ForeignKey(Account, related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) students = models.ManyToManyField(Account, related_name='courses_joined', blank=True) course_image = models.ImageField(upload_to='images') class Meta: ordering = ['-created'] def __str__(self): return self.title class Module(models.Model): course = models.ForeignKey(Course, related_name='modules', on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) def __str__(self): return f'{self.order}. {self.title}' class Meta: ordering = ['order'] -
Django queryset keyword from string
This is my model class Mymodel(models.Model): title = models.CharField(max_length=150) author = models.CharField(max_length=150) I have a json like this stored in db q = {"field_name": "title", "value":"django"} and this is what I am trying to do. Mymodel.objects.filter(q["field_name"]=q["value"]) It is not working. Getting the error SyntaxError: keyword can't be an expression How can i make this working ? I have tried things like Mymodel.objects.filter(getattr(event_model, q["field_name"])=q["value"]) It is possible to make it work like many if elif conditions like below but the code becomes ugly. Is there any cleaner way to do this ? if q["field_name"] == "title": Mymodel.objects.filter(title=q["value"]) elif q["field_name"] == "author": Mymodel.objects.filter(author=q["value"]) -
Django Models: Have Trouble with 2 Subqueries (No Foreign Keys)
I have 2 models: TeamsDatabase and EmployeeDatabase EmployeeDatabase has the following columns: emp_id emp_name emp_status emp_team_id emp_role TeamsDatabase has the following columns: team_id reporting_1 I would like to query EmployeeDatabase and join the column reporting_1 from TeamsDatabase where team_id equals emp_team_id. From the resulting reporting_1 (which is the equivalent of emp_id in EmployeeDatabase) value, I want to display the employee name from EmployeeDatabase. (I am limiting my query set to 1.) My django code is below: subquery1 = Subquery(TeamsDatabase.objects.filter(team_id=OuterRef('emp_team_id')).values('reporting_1')) subquery2 = Subquery(EmployeeDatabase.objects.filter(emp_id=subquery1).values('emp_name')) emp_qs = EmployeeDatabase.objects.values('emp_id', 'emp_status', 'emp_team_id', 'emp_role').annotate(reporting_1=subquery2).filter(Q(emp_status='ACTIVE') | Q(emp_status='SERVING NOTICE')).order_by('emp_team_id')[:1] df = read_frame(emp_qs) The expected result is this: Instead, row 1 has JOHN DOE under reporting_1 column, in place of YULISSA HERNANDEZ. (Of note, the text BRAZIL displayed under the column emp_team_id below is the display choice for team ID 1000). In fact, all my rows have JOHN DOE under reporting_1 column. The employee ID of JOHN DOE is 302052. When queried separately where team_id = 1000: SELECT reporting_1 FROM teamsdatabase WHERE team_id = 1000; the result is 150115016 When queried separately where emp_id = '150115016': SELECT emp_name FROM employeedatabase WHERE emp_id = '150115016'; the result is YULISSA HERNANDEZ In PgAdmin using the raw SQL, I get the same … -
Getting a proper dropdown List in ManyToMany Field in django form
These are the two models i am working on: class Category(models.Model): Name = models.CharField(max_length=20) class Listing(models.Model): Category = models.ManyToManyField(Category, verbose_name="Categories") ...... This is the form class in forms.py: class NewForm(ModelForm): class Meta: model = Listing fields = [....., 'Category'....] Now, when i declare form = NewForm(), the input field shown is something like this: Category object (1) Which is understandable as Category model is a ManyToMany field to the model Listing. But what i want is the options to show the "Name" attribute of class Category. But i don't understand how to get it done. -
how to view and download pdf of my current html page in django
i need to view and download pdf format of my current html page in django.can you please reffer me some code to resolve this issue. views.py def pdf(request): date_from=request.POST.get("date_from") print(date_from,"date frommmmmmmmmm==========") date_to=request.POST.get("date_to") print(date_to,"datetoooooooooooo=================") a=db_orderritem.objects.all().filter(timestamp__lte=date_to,timestamp__gte=date_from) b=db_orderr.objects.all().filter(timestamp__lte=date_to,timestamp__gte=date_from) pdf = render_to_pdf('pdf/report.html', {'odl':a,'od':b}) return HttpResponse(pdf, content_type='application/pdf') -
Django administration for two Django projects
I have two Django projects(not apps). their database will be combined in one db cluster. So half models will be in one project and half in another. My question - how can I create Django administration site for models from two projects? I don't understand^ because I can't register models from second project in adminpy. Any suggestions please? -
Why did the Django database receive duplicate posts using fetch in Javascript?
I have an email form in inbox.http, and wanted to send the form to my Django database - the email model. The email form was submitted to the database using the JavaScript function. When I submitted the email form, sometime two same emails were received or stored in the email model on the Django database, sometime six emails. I do not know why that has happened and how to resolved the issues. Your explanations and resolutions would really be appreciated. The form in inbox.html <div id="compose-view"> <h3>New Email</h3> <form id="compose-form"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" value="Send" class="btn btn-primary"/> </form> </div> The email model: class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%m/%d/%Y, %H:%M:%S"), "read": self.read, "archived": self.archived } The JavaScript functions document.addEventListener('DOMContentLoaded', function() { document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('#compose-form').addEventListener('click', sendEmail); }); function compose_email() { // … -
How to pass additional data to serializer?
I need to add 2 variables in serializer for for calculations in logic serializer serializer = MoviesTopFrameSerializator(topMovie) How can i do this ? and how to handle inside of serializer -
how to access django server only with flutter app?
While I'm using Django as my backend and flutter as my front end. I want only the flutter app to access the data from django server. Is there any way to do this thing? -
Django Error: NoReverseMatch at / Reverse for 'like-post' not found
I'm developing a simple blog with Django. I tried adding ajax functionality to my like button. But got this error: Reverse for 'like-post' with arguments '('',)' not found. 1 pattern(s) tried: ['like/(?P[0-9]+)$'] PS: I followed this video to create a like button and this video add ajax functionality views.py class PostDetailView(FormMixin, DetailView): model = Post form_class = CommentForm def get_success_url(self): return reverse('post-detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) postid = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = postid.total_likes() context['form'] = CommentForm(initial={'post': self.object}) context['total_likes'] = total_likes return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(PostDetailView, self).form_valid(form) def LikeView(request, pk): post = Post.objects.get(id=pk) #post = get_object_or_404(Post, id=request.POST.get('post-id')) post.likes.add(request.user) context = { 'post': post, 'total_likes': post.total_likes, } if request.is_ajax(): html = render_to_string('blogsite/like_section.html', context, request=request) return JsonResponse({'form': html}) return HttpResponseRedirect(reverse('blogsite-home')) urls.py urlpatterns = [ path('', PostListView.as_view(), name='blogsite-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('like/<int:pk>', LikeView, name='like-post'), ] base.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like-post" post.pk %}', data: {'id':pk, 'csrfmiddlewaretoken':'{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('#like-section').html(response['form']) console.log($('#like-section').html(response['form'])); … -
Django form logs out user
Today i have this issue: I wrote a Sign-in Sing-out web application with the Django framework. When a user is logged in, he is redirected to the index page. There he can see "posts" by other users and has the option to like a "post". When the like button is clicked, the user gets logged out and the like view is not accessed at all. Can some one tell me why is that? I will provide some code below. If it's not enough here is my projects github: https://github.com/palm-octo-chainsaw/the-end main url.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls', namespace='core')), path('accounts/', include('accounts.urls', namespace='accounts_app')), path('djrichtextfield/', include('djrichtextfield.urls')), ] core.views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login from core.models import Core from django.contrib.auth.models import User def home(req): ctx = { 'posts': Core.objects.all(), } return render(req, 'pages/index.html', ctx) @login_required(login_url='accounts_app:login') def likes(req): if req.method == 'POST': if req.user: return redirect('core:home') def create(req): pass core.urls.py from django.urls import path, include from core.views import home, likes, create app_name = 'core' urlpatterns = [ path('', home, name='home'), path('like/', likes, name='like'), path('create/', create, name='create') ] accounts.views.py from django.shortcuts import render, redirect from django.contrib.auth.models import … -
How to reinstantiate the ckeditor form with existing data to edit a note in django?
Hi all, i want to edit my note which was written using django ckeditor. I have no idea how we can do it. Please help me.