Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fetch id from url in class in django
I want to fetch id from url so that i can use the queryset in diff. mehtods of class. but it is showing: schedule = get_object_or_404(Schedule, id=kwargs['pk']) NameError: name 'kwargs' is not defined Here's My Code: class SubmitAttendanceView(View): template_name = 'schedule/submit_attendance.html' # this html file will be included in 'schedule/scheduledetail.html' form_class = AttendanceForm schedule = get_object_or_404(Schedule, id=kwargs['pk']) students = Student.objects.filter(course__id__in=schedule.course.all(), sem=schedule.sem, subject__id__contains=schedule.subject.id).order_by('roll_no') def get(self, request, pk): form = self.form_class() return render(request, self.template_name, {'form': form, 'students': self.students}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): date = form.cleaned_data['lecture_date'] lecture = self.schedule.id subject = self.schedule.subject.id x = 1 # a counter to fetch each checkbox from template by their name for student in self.students: course = Course.objects.get(id=student.course.id) mark = self.request.POST[f'mark{x}'] if not mark: mark = 0 attendance = Attendance(lecture=lecture, subject=subject, course=course, student=student, lecture_date=date, mark=mark) attendance.save() x += 1 return redirect('schedule') return render(request, self.template_name, {'form': form, 'students': students}) urls.py: path('<int:pk>/submit/', SubmitAttendanceView.as_view(), name='submit-attendance') in template: <a class="btn btn-md btn-danger add-new my-2" type="button" href="{% url 'submit-attendance' schedule.pk %}">Submit Attendance</a> also tell if there's another way in which i can pass the queryset to variable and use it in my class methods -
Render django html text in email body format
Below is a field on my forms.py: body = forms.CharField(label='Paste Email Thread Here', widget=forms.Textarea(attrs={ "class": "body-QAerror",})) And this is the data that I have entered: enter image description here Which I passed onto my html template; however, it didn't retain the email format (with indentions) See below: From: Firstname, Lastname Sent: Wednesday, February 27, 2019 11:01 AM To: someonelese@example.com Subject: server is unresponsive Importance: High For some unknown reason, the server is not responsive – can’t log in, and affected all end users. I filed a ticket 123456. Please communicate this if some users are asking for the issue. Thanks, Firstname MiddleName 78456431 FM@example.com Is it possible to still retain the email format? -
How to create Bar Chart in django using database value
hello everyone i want to create a bar chart using my database value in django i am create a model that is class statictab(models.Model): def indiantime(): date = now() + timedelta(minutes = 330) return date.date() user = models.ForeignKey(usertab,on_delete = True) date = models.DateField(default=indiantime) click = models.IntegerField(default=0) i have save last 10 days click of every user in my database so i have fillter user last 10 days data like this this is views.py def createchart(request): if request.session.has_key('user_id'): pastdate = timezone.now() - timedelta(days=9) + timedelta(minutes=330) nowdate = timezone.now() + timedelta(minutes=330) staticdata = statictab.objects.filter(date__range=[pastdate.date() , nowdate.date() ],user_id=request.session['user_id']) d={"data" : staticdata} return return render(request,"html/chart.html",d) in my d dictionary last 10 days data are present so i want to create a bar chart using chart.js so how i cant do this in my tamplate my template chart.html <html> <head> #all script and css are linked </head> <body> <div id = "mychart"> </div> <script> window.onload = function () { var chart = new CanvasJS.Chart("mychart", { animationEnabled: true, title:{ text: "Last 10 Days View" }, axisX:{ // valueFormatString: "DD MMM" }, axisY: { title: "Number of Click", }, data: [{ type: "line", xValueFormatString: "DD MMM", color: "#F08080", dataPoints: [ // { x: new Date(2017, 0, 7), … -
Adding Multiple Entries to Django database in Single Go
I am trying to add around 40-50k rows to pgsql Database from Django from a Text File Dump from an Application for Data Processing Following is my Function def populate_backup_db(dumpfile): sensordata=sensorrecords() **** This is the Model start_time = time.time() file= open(dumpfile) filedata = file.readlines() endcount=len(filedata) i=0 imagecount=0 while i<endcount: lineitem = split_entry(filedata[i]) if (lineitem[0]== "HEADER"): imagecount=imagecount+1 sensordata.Sensor = lineitem[1] sensordata.Date1 = lineitem[2] sensordata.Date2 = lineitem[3] sensordata.Version = lineitem[4] sensordata.Proxyclient = lineitem[8] sensordata.Triggerdate = ctodatetime(lineitem[13]) sensordata.Compression = lineitem[16] sensordata.Encryption = lineitem[17] sensordata.Fragments = lineitem[21] sensordata.Pbit = lineitem[37] sensordata.BlockIntFT = lineitem[38] sensordata.OriginServer = lineitem[56] sensordata.save() i=i+1 elapsed_time = time.time() - start_time print(imagecount ,'entries saved to database from ',dumpfile,'. Time Taken is ',elapsed_time,' seconds.') file.close() This is taking around 2-3 minutes to save all data to Database. This Dumpfile is likely to Increase in size, and if this Function is to be used, It can take a couple of minutes to Save All data to Database How can I fetch all Data from Dump File and then save it all to the Database in single go. -
How to filter leads, contacts by null city in address fields in https://developers.getbase.com/ API V2?
I'm trying to filter contacts and leads from the api https://api.getbase.com/v2/ for those records which have the city=null in their address fields. So, far I haven't get any resource where filter by null is mentioned. In the provided documentation it is mentioned how to filter by city as follows: https://api.getbase.com/v2/contacts?address[city]=Stcokholm That is providing response with list of contacts which contains city=Stockholm in their address fields. I'm using python request client. Can anyone suggest how can I filter contacts by city which is null? Thanks in advance -
psycopg2.InterfaceError: connection already closed
I am using psycopg2 to access a postgresql database in a django project. When executing a function that takes around 30 minutes and then saving the results into database the following exception appears self.connection.autocommit = autocommit Internal Server Error: /dashboard/ajax/playbookRunner/39 Traceback (most recent call last): File "env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 238, in _set_autocommit self.connection.autocommit = autocommit psycopg2.InterfaceError: connection already closed any ideas? -
Ubuntu 16.04 virtualenv django import error
I installed django at virtualenv. Django is installed at '/usr/local/lib/python3.7/site-packages', but that's not virtualenv's python path. so that makes django import error in virtualenv. please help -
Django memcached session get deleted
Two Django applications(DRF) are running on two separate ports 8001 and 8000 with same host localhost. I am using memcached to store the sessions. Both the application share the sessions from the memcache. when i try to access pages using second application after logining in using first I am getting error : "The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example." I want to build a distributed apps where one app can be used for auth running on a separate docker, so other apps can share the session using memcached -
Fetch data stored on a port using django
I have published data(ble raw data) on an url e.g:(127.0.0.1:8000) using raspberry pi. Data also published on mqtt. My question is about to get the data from that ip:port using a web application in Django -
Django-Storages S3 with minio as backend
i would like to use django-storages with minio so i tryd to adopt settings, configs etc. I found on the web but for some reason my access key or the way it gets provided fails with the following error: botocore.exceptions.ClientError: An error occurred (InvalidAccessKeyId) when calling the PutObject operation: The AWS Access Key Id you provided does not exist in our records. if i run manage.py collectstatic settings.py #S3 config STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'MyProject/static'), ] AWS_ACCESS_KEY_ID = '9VOWWCTSMX4ZEGVW7N9D' AWS_SECRET_ACCESS_KEY = 'zJFf9BYWk0TM3FVwyY98UFy0o+DQF0oY1vCXgLqV' AWS_STORAGE_BUCKET_NAME = 'static' AWS_S3_CUSTOM_DOMAIN = '127.0.0.1:9000' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_URL = 'http://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Is there maybe someone that has already done this? Thankful for every hint! BR -
How can I track users using a middleware?
I have developed a small web app and I want to make a tracking middleware to track all user clicks and activities into a log file. How can I do it ? Can someone provide me the code for it ? -
How to create customize menu structure in Django
first wrote Custom template context processor method def show_pages_menu(context): pages_menu= suppliers.objects.filter(show_in_menu=True) return {'pages_menu': pages_menu} after i added this method to my settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'Accounts.pages_context.show_pages_menu' ], }, }, ] at the end i had created template menu.html {# First render the pages #} {% for page in pages_menu %} {# Then check if current page is 'published' #} {% if page.status == 'published' %} <li> <a href="{{ page.get_absolute_url }}">{{page.menu_title}}</a> </li> {% endif %} {% endfor %} And added this url in my urls.py url(r'^suppliers/', CreateView.as_view(), name="suppliers") i had follow this tutorial.But i am getting error Cannot resolve keyword 'show_in_menu' into field. -
How to search objects in django using an instance of choicefield?
This is my model: class Profile(models.Model): date = models.DateTimeField(auto_now_add=True) full_name = models.CharField(max_length=32,blank=True) user_types = ( ('Bussiness User','Bussiness User'), ('Professional','Professional'), ) user_type = models.CharField(max_length=32,choices=user_types,default='Bussiness User',blank=False) user= models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) e_mail = models.EmailField(max_length=70,blank=True) As you can see the are two types of user in my Profile model Bussiness User and Professional. So I want to make a query in django which will search only for the Professional users. I have tried this in my views: query = request.GET.get('q') if query: if Profile.objects.filter(user_type__icontains='Professional'): result = Profile.objects.filter(Q(user__username__icontains=query) | Q(e_mail__icontains=query) | Q(full_name__icontains=query)) else: result = Profile.objects.filter(user_type__icontains='Professional').order_by('id') In my template: <form method='GET' class="form-horizontal" id="search-form" action="{% url 'userprofile:search' %}"> <div class="col-lg-8 col-md-8 col-sm-8 col-xs-6"> <input class="form-control" name="q" value="{{request.GET.q}}" placeholder="Search"> </div> <div > <span class="input-group-btn"> <button type="submit" class="btn btn-info pull-right">Go</button> </span> </div> </form> But when I search for a Professional user it gives me list of all the user associated with that name. Can anyone provide me with suitable solution for this. Thank you -
Django: How do I include a search filter in a CRUD table website that uses Function Based Views?
I've been searching so far for a problem similar to mine, but can't seem to find one. I made a listing screen that can add, edit, delete Books. However, I can't get how to work search filter in the website. Most examples I've seen are done using Class Based Views. Any help is appreciated. views.py def books(request): books = BookList.objects.all() return render(request, 'listingscreen/book/books.html', {'title': 'Books', 'books':books}) @login_required def create_book(request): print(request.POST) title = request.GET['title'] author = request.GET['author'] pages = request.GET['pages'] price = request.GET['price'] book_details = BookList(title=title, author=author, pages=pages, price=price) book_details.save() return redirect('/books/') @login_required def add_book(request): return render(request, 'listingscreen/book/add_book.html') @login_required def delete_book(request, id): books = BookList.objects.get(pk=id) books.delete() return redirect('/books/') @login_required def edit_book(request, id): books = BookList.objects.get(pk=id) context = { 'books' : books } return render(request, 'listingscreen/book/edit_book.html', context) @login_required def update_book(request, id): books = BookList.objects.get(pk=id) books.title = request.GET['title'] books.author = request.GET['author'] books.pages = request.GET['pages'] books.price = request.GET['price'] books.save() return redirect('/books/') models.py <pre> class BookList(models.Model): """docstring for BookList.""" title = models.CharField(max_length=200) author = models.CharField(max_length=150) pages = models.IntegerField() price = models.IntegerField() </pre> -
Calculated field for a QuerySet with a large number of items
I want to add an extra (calculated) field on the fly for each item in a QuerySet whith thousand items. For performance reasons, this field must be calculated in for a bunch of entities, and not for each singular item. What is the most elegant form to integrate that in models? -
Data format in Ext JS forms and Django models is equivalent, but not works
When I to do POST in my form, debuger throw it: act_date: ["Date has wrong format. Use one of these formats instead: YYYY-MM-DD."] and for other datefields. So, ok, I changed format in extjs like that: Ext.util.Format.defaultDateFormat= 'Y-m-d' No result again. So next I define date format in django setting: 'DATE_FORMATS': [("%Y-%m-%d"),], I tryed change data formats confing on data input format - hasn't been result again. how to fix it? -
How to display inline formsets for many-to-many relations
I have two models: class Profile(models.Model): profileName = models.CharField(max_length=50) class RelatedProfile(models.Model): relatedProf = models.ManyToManyField(UseCaseProfile, through='UseCaseProfileRelatedUseCase') relationType= models.CharField(max_length=3, choices=RELATION_CHOICE) By following the Django documentation of ManyToMany relationships, I have created this table below: class ProfileRelated(models.Model): prof = models.ForeignKey(Profile, on_delete=models.CASCADE) related = models.ForeignKey(RelatedProfile, on_delete=models.CASCADE) I am aiming to have an inlineformset where the parent model is Profile and the child model is RelatedProfile. Therefore, I did the following: forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields='__all__' class RelatedUCForm(ModelForm): class Meta: model = RelatedUseCase fields = '__all__' RelatedUCFormSet = inlineformset_factory(Profile, RelatedProfile.relatedProf.through) views.py (I left out unnecessary code) class ProfileUpdateView(UpdateView): template_name = "some.html" model = Profile form_class = ProfileForm def get_context_data(self, **kwargs): context = super(ProfileUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['relatedProfile_form'] = RelatedUCFormSet(self.request.POST, self.request.FILES, instance=self.object, prefix='related') else: context['relatedProfile_form'] = RelatedUCFormSet(instance=self.object, prefix='related') return context Based on the models, forms, and view, I want to display a web page like this: <pre> Profile profileName: Textfield Related Profile: Dropdown with related Profile :relationType: choicefield </pre> However, when I display my webpage, I don't get the dropdown to select which Profile I want to relate to the parent Profile. Overall, my issue is about getting the dropdown under the Related to show a list of Profiles that I could … -
Django Rest Documentation - Interact not working for POST
I have setup a simple view with a POST request. I need to generate the documentation for this View. @api_view(['POST']) @permission_classes((AdminPermission,)) def searchMe(request, index, format=None): serializer = SearchSerializer(data=request.data) if serializer.is_valid(): es = searchclient() try: res = es.search(index=index, body=serializer.data['query'], scroll=serializer.data['scroll']) return Response(res, status=status.HTTP_200_OK) except Exception as e: return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to test if this is working, but on clicking the interact button all I see is a blank page. I am accepting a json request in the body field. I can query the API using the requests.post method and it works. Why does it not work in the Try it out or interact? -
Django: model not defined?
I can't use the model I defined in Django. My model is defined inside my_object/models.py: class MyObject(models.Model): name = models.CharField("Name") If I launch shell_plus, I can't use my model: # ./manage.py shell_plus # Shell Plus Model Imports ... from my_object.models import MyObject ... In [1]: MyObject --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-05203d19fbcd> in <module> ----> 1 MyObject NameError: name 'MyObject' is not defined And I cannot launch tests either, I get this error: my_object.models.DoesNotExist: MyObject matching query does not exist. My config: Python 3.6, Django 1.11. -
Open Source Mapping System for Multi Data Sources
We collect data from a range of providers. All of them might have a slightly different identifier for the same product. I would like to be able to compare the products At the moment to do so I have a table in my database “product mapping master” which has foreign keys to my providers product tables. I enter the details in here. Does any body have a good example or a ready to go framework (preferably python) that I could review and possibly implement. Most likely I’ll just spin up a Django App, use Django-admin and filter the query sets to reduced the list once a product has a relationship. However I was just curious if someone had a better solution -
Configuring Nginx and Gunicorn for DRF, Django and React Frontend
I have an application whose frontend is in React and the back-end is in Django with API's developed using DRF for the front-end. Now I am using Nginx as the web server along with Gunicorn. The following is my Nginx conf file in sites-available: server { listen 8000; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/nokia-ui/build/; } location /nokia-sdn/api/v1/ { proxy_pass http://127.0.0.1:8000/nokia-sdn/api/v1/; } location / { proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://unix:/home/nokia-sdn/nokia.sock; } } Now the when I access http://localhost:8000/ I get the login page, but I am not able to make any api requests to the back-end.Do we need to define the path of the API in nginx file, if so what is the format? -
Django User Cascade - Build Tree in Template
I'm creating a Django project and I want to give out all informations the server knows about a user (I live in the EU). I tried to create my own tree without giving out too much information to a user but that didn't work. Now I want to use Django's built-in User-Cascade-Tree (Like this tree if you delete a user). How can I do that without giving the user too much information? (For example: I don't want to give out auto-increment ids or fields the user don't need to know.) -
Django admin uploaded image in production
The images i upload through the admin-interface i production cannot be found, though it exists on the server.It loads fine in development. I use Django Image-kit to resize the uploaded image. The image isn't displayed on the website and if i follow the image url, I get <h1>Not Found</h1> <p>The requested URL /media/CACHE/images/references/<reference-name>/<image-name>/211b0022f8a2baad7cdc527711dcb.jpg was not found on this server.</p> The uploaded image is not added to my static files, which are correctly displayed. My model looks like this: def generate_unique_slug(instance, field): original = slugify(field) unique = original numb = 1 while instance.objects.filter(slug=unique).exists(): unique = f'{original}-{numb}' numb += 1 return unique def reference_main_image_path(instance, filename): sub_folder = instance.slug return f'references/{sub_folder}/{filename}' class Reference(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=2000) slug = models.SlugField(max_length=12, unique=True, blank=True) main_image = models.ImageField( upload_to=reference_main_image_path, default='default.png') main_thumbnail = ImageSpecField(source='main_image', processors=[ResizeToFill(540, 300)], format='JPEG', options={'quality': 80},) tags = TaggableManager() def __str__(self): return self.title def save(self, *args, **kwargs): if self.slug: if slugify(self.title) != self.slug: self.slug = generate_unique_slug(Reference, self.title) else: self.slug = generate_unique_slug(Reference, self.title) super().save(*args, **kwargs) My view.py: def reference(request): context = { 'references': Reference.objects.all(), } return render(request, 'home/references.html', context) In the ´html` code I 'call' the image like this: <img src="{{ reference.main_thumbnail.url }}"> My settings.py static and media variables look like this: STATIC_ROOT … -
How to access context variables with javascript
I am working on a django application. In the views.py file I define a few context_variables that I want to send to javascript. Here is my views.py function: def on_csv_upload(request): path = './csv/' if request.method == 'POST': if 'file' in request.FILES: handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) df = pd.read_csv(os.path.join(path, str(request.FILES['file']))) table_heading = list(df.columns.values) table_content = df.to_html(classes='table table-bordered table-hover thead-dark', index=False) context = {'table_heading': table_heading, 'table_content': table_content} return render(request, 'index.html', context) I want the context with javascript so I followed this link for doing the same but does not seem to work for me. Here is my django template <script type="text/javascript"> var content = "{{table_content}}"; console.log(content); </script> this prints the following in the log What am I doing wrong? Thanks in advance -
How to make Django 2.1 to accept PUT/DELETE requests
I am building an app with Django 2.1 and I want to be able to do PUT/DELETE requests through ajax calls. Through researching about this I found out the solution to be to deceive the browser by using a POST request, but setting the header X_METHODOVERRIDE to the desired method. I would start doing this by creating a middleware that will take care of this. What is the best way of doing? Please note that I don't want to use Django-REST