Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IP address for django-axes logins does not show
I have django-axes running with my Django app and so far everything works fine, however, in the django-axes admin section, the IP addresses do not seem to work. It just shows a "-". Is there perhaps a setting I should configure for django-axes to enable this or is it one of my Django project settings that prevent this? Maybe one of these: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 2592000 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_REFERRER_POLICY = 'same-origin' SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True X_FRAME_OPTIONS = 'DENY' -
How can I run create-react-app project made react with django template at the same route?
I trying to split react web project with django template. But, this project is so big, and I want to divide it gradually. So my question is, is it possible to run react web made with django template and project newly created with create-react-app in the same route? If possible, how can I separate and running? In my common sense, I can't think of a solution. Sorry for the insufficient question. -
Django adding hour and minute from form
It is possible to add hour, minute and second from admin dashboard, but now I want to add it to my template. models.py: class Document(models.Model): date = models.DateTimeField() forms.py: class CreateDocumentForm(ModelForm): ... class Meta: model = ComplaintDocument fields = '__all__' widgets = { 'date': DateTimeInput(attrs={'type': 'date'}), } -
Django. how to assign the right variable to pre populating the form
I am trying to pre populate the form to the edit entry, but I am having a problem to assign the right variable. I did a test using just a text to populate it, and it works. But could somebody give a hint in how to do it retrieving the content and title from util.save_entry(title,content). My test: def edit_entry(request): title = 'title' content = 'content' if request.method == "GET": form = EditEntryForm(initial={'title': title, 'content': content}) return render(request, "encyclopedia/edit.html", { "form": form }) -
How can I query embedded records in a Djongo ArrayField?
I'm using Django 3.0.6 with Django Rest Framework 3.11.1. I'm connecting to a MongoDB database using the djongo connector. One of my models has an ArrayField that contains embedded records. I would like to know how I can retrieve these embedded fields using a django query. Each Person can have many different sub records. Here is a sample model to illustrate what I'm working on Models: from djongo import models class SubRecords(models.Model): status = models.CharField(max_length=20) startTime = models.CharField(max_length=20) identifier = models.CharField(max_length=20) job_title = models.CharField(max_length=20) class Meta: abstract = True class Person(models.Model): _id = ObjectIdField() workplace = models.CharField(max_length=120) subject = models.CharField(max_length=120) records = models.ArrayField(model_container=SubRecords) I would like to query the Person model and get all Person.records objects and Person.records objects that match some criteria I have tried to do this >>> Person.objects.filter(records__exact={'job_title': 'HR'}) Now the problem I'm facing is that the result isn't limited to subrecords where the job title is HR, instead if a Person object contains a sub record that matches the criteria, the whole Person object and associated sub records are returned. I want to be able to get a list of all the subrecords and only the subrecords that match the criteria I specify. How can I … -
How do I combine two arrays in for loop fashion so the 3 items of one list appear then 1 item of the other list appears, in python (django)
I'm building a social media site with events and posts and I want the user feed to have new events advertised every 4 posts. So basically the feed would look like: Post 1, Post 2, Post 3, Event 1, Post 4, Post 5, Post 6, Event 2, ... Do I do this in the template or view? And how do I do it? -
MultiValueDictKeyError at /new_search/realme-xt-pearl-blue-64-gb/p/i/realme-xt
I want to capture the url parameters to views.How can I do it? views.py def new_search(request,linkadd,text): serch = request.GET['linkadd'] link = request.GET['text'] html {% for post in product_names %} <a id="link" href="{% url 'new_search' linkadd=post.1 text=post.0 %}" value="{{ post.0 }}">{{ post.0 }}</p> {% endfor %} urls.py urlpatterns = [ url(r'^new_search(?P<linkadd>)/(?P<text>)',views.new_search,name='new_search'), ] I want to get link and text from the url "120.0.0.0:8000/1232-23232-32-2323sdsjdhjas/redmi" assume :1232-23232-32-2323sdsjdhjas as link and redmi as text but I get the error like this please suggest me how to do it MultiValueDictKeyError at /new_search/realme-xt-pearl-blue-64-gb/p/itm731360fdbd273?pid=MOBFJYBE9FHXFEFJ&lid=LSTMOBFJYBE9FHXFEFJNVQVIV&marketplace=FLIPKART&srno=s_1_1&otracker=search&fm=organic&iid=a64429b9-99a5-405b-8edb-9d94934fb991.MOBFJYBE9FHXFEFJ.SEARCH&ssid=iprr3ut7io0000001598430215812&qH=23f6a0071022557e/Realme XT (Pearl Blue, 64 GB) Please help me..Thanks in advance!! -
Redirect using next in django even after taking multiple attempts to login
I am having this login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) next_page = request.POST['next'] if next_page != '': return redirect(next_page) else: return redirect('/') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") In this if a user comes to a page where login is required then he is redirected to login page and when he logs in successfully he is redirected to the page where he came from. But the problem arises when the user does not login in first attempt(enters wrong email or password) then the login page reloads and then if he logs in successfully he isnt redirected to the page where he came from. How can I work this out so that no matter the number of attempts the user takes to login he is redirected to the same page from where he came from. -
Dont work command 'django-admin.py startproject blog .'. IDE just show script and nothing happens
I try to create new django project in Pycharm IDE. After correct installing Django i try to do this command in terminal "django-admin.py startproject blog .", but IDE show me this script in new window and nothing happening. How can i fix this? enter image description here -
Is foreign key reference is necessary when using schemas for data isolation?
I am doing some research on data isolation strategies for a SaaS project. I am using Django with PostgreSQL. I have three options, separate database for each tenant, the separate schema for each tenant, foreign key reference of each tenant in every table. 2nd approach suits best for my requirements. My question is that, if I create a separate schema for every tenant, how secure is that? Should I still add a foreign key reference in every major entity and add filtration logic to the application layer? Any suggestions on improving the overall design are also welcome. -
NoReverseMatch Reverse for 'teacher_edit' with no arguments not found. 1 pattern(s) tried
my part of code of html link is: <button type="submit" name="btnedit" id="rpt_teacher_btnedit_0" class="btn btn-secondary btn-sm" onclick="window.location.href='{% url 'institute_module:teacher_edit' teacher.id %}'" /><i class="fa fa-edit"> Edit</i></button> view.py def teacher_edit(request, tch_id): teacher_details = TEACHER.objects.get(id=tch_id) return render(request, 'institute/teacher_edit.html') urls.py path('Institute/Teacher_Reg/edit/<int:tch_id>', views.teacher_edit, name='teacher_edit'), -
How to debug django in spyder
I have a django project which I would like to start in debug mode so I can use breakpoints in spyder to see what is happening. However I do not know how to start the manage.py runserver in debug mode in spyder. Unfortunately I am stuck with spyder for this (unfortunate because I know how to do it in vs code). Can anybody help me? -
Django Annotation with Sum(Case(When))) returning wrong values
In a Django 1.9 app, I need to annotate a queryset in order to get a number of related entities without querying the DB multiple times. The problem is that with such an old version of Django, the filtering function on Count with related entities is not available and I need to use Sum(Case(When))) to be able to filter. I have a job model that can have multiple matches and multiple fits. Here is the code about the annotation part. unchecked_fits = Count('fits', distinct=True) nb_matches_proposition = Sum(Case(When(matches__current_status=MATCH_PP_STATUS, then=1), default=0, output_field=IntegerField()), distinct=True) nb_matches_preselection = Sum(Case(When(matches__current_status=MATCH_PRESELECTION_STATUS, then=1), default=0, output_field=IntegerField()), distinct=True) nb_matches_valides = Sum(Case(When(matches__current_status=MATCH_VALIDES_STATUS, then=1), default=0, output_field=IntegerField()), distinct=True) nb_matches_entretiens = Sum(Case(When(matches__current_status=MATCH_ENTRETIENS_STATUS, then=1), default=0, output_field=IntegerField()), distinct=True) jobs = Job.objects.filter( job_team_owner=user, current_status__in=active_statuses, open_to_suggestion=False ).annotate( # unchecked_fits = unchecked_fits, nb_matches_proposition = nb_matches_proposition, nb_matches_preselection = nb_matches_preselection, nb_matches_valides = nb_matches_valides, nb_matches_entretiens = nb_matches_entretiens, ).order_by('-date_created').select_related('company') The numbers returned by the annotated fields are correct when I comment the unchecked_fits annotated field but they give me much too high values when I uncomment it. Strangely enough, I noticed that all the nb_matches_xxx fields get multiplied by the value of unchecked_fits when I uncomment. I guess there's just something wrong with my syntax but I do no get it... Any help … -
django many-to-many filter and count
I'm using Django 2.2 I have a model structure class Product(models.Model): data = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class ProductRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) tags = TaggableManager() class TrackingData(models.Model): d = models.CharField(max_length=200) product = models.ForeignKey(Product, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) Where TaggableManager() is a many-to-many field by django-taggit library. I have the following tags tags = ['tag1', 'tag2'] I want to filter the TrackingData by the tags from the ProductRelation and get the count of tracking data for each tag. Each ProductRelation object can contain many tags. The example table would be like # ProductRelation user | product | tags --------+----------+--------- user1 | product1 | tag1, tag2 user2 | product2 | tag2, tag3 I'm able to filter the tracking data like from functools import reduce from django.db.models import Q import operator t = TrackingData.objects.filter( product__productrelation__user=u ).filter( reduce( operator.or_, ( Q(product__productrelation__tag__name__icontains=x) for x in tags ) ) ) But how will I get the count by tags? -
Django ModuleNotFoundError can't import model file
I am new to Django and want to create dummy data so using faker library with sqlite db. Created models.py and DummyData.py . models.py from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=200) surname = models.CharField(max_length=200) email = models.EmailField(max_length=200, unique= True) def __str__(self): return "Object created " + "Name :-" + self.name + " Surname :-" + self.surname + " Email :-" + self.email for creating fake data made DummyData.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'Course.settings') # 1. method from .models import User # 2. method from appTwo.models import User Both ways I am not able to import Users class from models getting error like Method 1 output ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package Method 2 output ModuleNotFoundError: No module named 'appTwo created empty init.py in appTwo folder. File structure is as above But I can able to import models.py using method 2 in Terminal, So I am little bit confuse. -
How can i use for loop in Django to have different titles and texts?
here is my html code. I wanna use for loop to have different texts in different titles. I wanna put each minor sentence in each title! not all 5 sentences in one title! {% for num in list %} <h3>COVID 19 is coming down. {{ num }} </h3> {% for sen in text %} <div><p>{{ sen }}</p></div> {% endfor %} {% endfor %} and here are my views. def index(request): date = dt.datetime.today().date _list = [1, 2, 3, 4, 5] text = ['This minor text', 'This is major text', 'This is fifth text', 'This is my text', 'This is the last text'] return render(request, 'index.html', {'date': date, 'list': _list, 'text': text, }) -
Django tags with html tab element
i'm trying to use tabs with django. the blocks work when I call them up using a button, for example. the base html excerpt therefore looks like this: <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-A-tab" data-toggle="tab" href="#nav-A" role="tab" aria-controls="nav-A" aria-selected="true">A</a> <a class="nav-item nav-link" id="nav-B-tab" data-toggle="tab" href="#nav-B" role="tab" aria-controls="nav-B" aria-selected="false">B</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-A" role="tabpanel" aria-labelledby="nav-A-tab">{% block A%}{% endblock %}</div> <div class="tab-pane fade" id="nav-B" role="tabpanel" aria-labelledby="nav-B-tab">{% block B%}{% endblock %}</div> </div> I now understand why that doesn't work. Since django does not render the part {% block A%} {% endblock%} as long as it is not called ... hence my consideration I use the href property so that the code looks like this. <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-A-tab" type="submit" data-toggle="tab" href="{% url 'a:A' %}" role="tab" aria-controls="nav-A" aria-selected="true">A</a> <a class="nav-item nav-link" id="nav-B-tab" data-toggle="tab" type="submit" href="{% url 'a:B' %}" role="tab" aria-controls="nav-B" aria-selected="false">B</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-A" role="tabpanel" aria-labelledby="nav-A-tab">{% block A%}{% endblock %}</div> <div class="tab-pane fade" id="nav-B" role="tabpanel" aria-labelledby="nav-B-tab">{% block B%}{% endblock %}</div> </div> unfortunately that doesn't help. Does somebody has any idea? many thanks -
Creating Dynamic Tuple for Sending Mass Email Django using send_mass_mail
I see a lot of documentation and example to create mass email like below message1 = ('That’s your subject #1', 'That’s your message body #1', 'from@yourdjangoapp.com', ['to@yourbestuser1.com', 'to@yourbestuser2.com']) message2 = ('That’s your subject #2', 'That’s your message body #2', 'from@yourdjangoapp.com', ['to@yourbestuser2.com']) message3 = ('That’s your subject #3', 'That’s your message body #3', 'from@yourdjangoapp.com', ['to@yourbestuser3.com']) send_mass_mail((message1, message2, message3), fail_silently=False) I want to send mass email to N number of users returned from my queryset with the same message. I am using the code below to send mass email. However , it is very slow and would want to know if any efficient methods exists or since am using gmail for testing, its going to be slow. def sendMassPasswordResetEmail(request): schoolval = user_school.objects.filter(username=request.user.id).values_list('schoolCode',flat=True)[0] clsval = student_group.objects.filter(schoolCode=schoolval).values_list('classVal_id').distinct() student = studentclass.objects.all().prefetch_related('student_group_set__username').filter(student_group__classVal__in=clsval).distinct() addStudentlink = True #groups = student.values('student_group') userinschool = User.objects.filter(user_school__schoolCode=schoolval,user_type=1).values('username') html_content = render_to_string('dashboard/registration_email.html') # render with dynamic value text_content = strip_tags(html_content) # Strip the html tag. So people ca for recipient in userinschool: subject, from_email, to = 'Account Activation xxxxx', 'xxxxxgmail.com.com',recipient.get('username') print(recipient.get('username')) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return render(request,'dashboard/add-student.html',{'students':student, 'addStudentlink':addStudentlink}) -
Heroku CLI not working within pycharm terminal
I am new to django and working on a django project, using pycharm as the editor. I am trying to deploy it on heroku. I installed heroku cli on my windows os, and tested it using command prompt, and it is working. But within pycharm's terminal, when I type "heroku", it does not recognize it. What am I missing? -
Handling Authentication in Django + GraphQL + Vuejs
I'm currently developping an application (SPA) with this stack : Django - GraphQL (graphene-django) - Apollo - VueJS I ended up at a point where I want to set up the authentication and I feel completely lost. I think there are 2 ways : Using the builtin Session system from Django but I don't know how to get the state of it (Am I logged in or not) in the frontend (VueJS where I could have a state variable in Vuex) and even if it's possible. Using JWT I'm currently trying JWT but once again, I feel completely lost since I've read many articles that say it is not a good idea to store the tokens in localStorage or in the sessionStorage. I began that way following several tutorials and I faced one problem, how do I get a token when the first one expires ? In terms of state, I could handle a state variable in Vuex that looked into localStorage,... But since I've read it's not good that way (XSS attacks,...), I decided to do it with cookies. Again, I'm lost ! While I managed to get the cookie once, with the jwt_cookie() : It expires quite fast … -
Python Pandas number column range 1-999999 messes up formats above 1000 like 1 000,000 and it cannot be converted to num from string
My problem is, I've got an excel file containing a huge amount of data, and some columns are supposed to be number fields. These columns contain numbers ranging from 1-99999. Handling these numbers is a real pain, in fact I have no solution how to, as I cannot convert them from string to number at all. My end goal would be to be able to do arithmetic operations with these columns, mainly multiplication and division. Right now I get a typeerror saying "str" or "float" cannot be matched with "/", so when I'm trying to divide these columns' values, it wont let me. First off, numbers above 1000 are totally messed up in the original report file. There is a whitespace in front of them, so for instance it is not like '1000', but ' 1000,000' (disregard the '' in this cases, just trying to help spot the leading whitespace). Also, there's this ,000 part that I cant understand. For numbers below 1000 there's nothing like that, however, for numbers above 1000, without exception it trails them with this decimal separator and 3 decimal places all filled with 0. Picture: I've been trying to sort this for 2 days now, … -
How to delete objects and their historical records at once in django?
I have an object called PTORequest which have a history field for storing HistoricalRecords of it. history = HistoricalRecords() I have not mentioned cascade_delete_history=True while creating history column which would automatically cascade history records. How do I delete all the objects and their historical records from PTORequest table without doing model changes and migrations? One thing I can think of is this: for i in PTORequest.objects.all(): print i.history.all().delete() print i.delete() Is there any other efficient way to do this? I'm using Django 1.11 -
aioredis.errors.ReplyError: ERR unknown command 'BZPOPMIN' When trying to use redis
I have redis 5.4. and I am gettign this error: aioredis.errors.ReplyError: ERR unknown command 'BZPOPMIN' I am following the tutorial on the django-channels website. This is the consumer code: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) I run my server using python manage.py runserver 0.0.0.0:8080 -- noreload maybe it has to do something with that, I open the page on the 5656 port and it is hosted on 8080 as I am using vagrant and those are the set ports in the VagrantFile. -
Continue Execution After HttpResponse Django
I want am working with a webhook that times out . To acknowledge receipt I have to send a 200 ok response . Then continue my execution. Code looks something like this def webhook(request): return HttpResponse(status=200) print(“ok”) -
Problem with rendering datepicker in django bootstrap template
In my Django bootstrap template, I am rendering a text field like below to insert the record --- Employee Contact: {{ form.econtact }} --- Like code below --- Employee Date of Birth: {{ form.edob }} </div --- I want to do the same for the date but I am unable to do please help with a date picker to choose date only I am trying this code from this answer How to use the bootstrap-datepicker in Django app? but it is not working template.html --- {{ form.date }} --- JavaScript --- $(function () { $('#datetimepicker1').datetimepicker({ format: 'YYYY-MM-DD' //This is the default date format Django will accept, it also disables the time in the datepicker. }) }); --- Please help.