Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Display model values in table
I am a newbie to django and need some help. I have a created a vaguely functioning website. I have a model which looks as follows; from django.db import models class InductiveSensors(models.Model): Part_No = models.CharField(max_length=250) Manufacturer = models.CharField(max_length=250) Sn = models.CharField(max_length=250) AssuredSn = models.CharField(max_length=250) def __str__(self): return InductiveSensors.Manufacturer There are a couple of pages. one which gives me a list of all items in the database {% extends "ESensFind/header.html" %} {% block content %} {% for InductiveSensors in object_list %} <h5>{{ InductiveSensors.Manufacturer}}<a href="/Inductive_Search/{{InductiveSensors.id}}"> {{InductiveSensors.Part_No}}</a></h5> {% endfor %} {% endblock %} When the {{InductiveSensors.Part_No}} link is clicked it opens up another page. On which I would like to display this database entry in a table with the information of Part_No = models.CharField(max_length=250) Manufacturer = models.CharField(max_length=250) Sn = models.CharField(max_length=250) AssuredSn = models.CharField(max_length=250) my urls look like: from django.conf.urls import url, include from django.views.generic import ListView, DetailView from Inductive_Search.models import InductiveSensors urlpatterns = [ url(r'^$',ListView.as_view(queryset=InductiveSensors.objects.all().order_by ("Manufacturer") #THIS PAGE IS THE LIST OF ALL DATABASE ENTRIES# [:25],template_name="Inductive_Search/Inductive_Search.html")), url(r'^(?P<pk>\d+)$', ListView.as_view(model= InductiveSensors, template_name = 'Inductive_Search/SensorInfo.html')) #THIS OPENS UP A NEW INDEX PAGE AFTER A PARTICULAR DATABASE ENTRY LINK IS CLICKED# is the 2nd url code correct to work in conjunction with "SensorInfo.html"? In "SensorInfo.html" i have … -
django cron job cannot get model query
I am using django-crontab and the following cron job is working well: the following cron job is added by python manage.py crontab add settings.py CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'my_app.cron.test','>> ~/cron_job.log'), ] my_app/cron.py from datetime import datetime def test(): print('HELLO : {}'.format(datetime.now())) and once the server runs, it prints out to the log file: ~/cron_job.log >... >HELLO : 2018-01-04 23:52:02.983604 >... same thing if I want to add a query for all my models : my_app/cron.py from datetime import datetime from django.apps import apps def test(): print('HELLO : {}'.format(datetime.now())) print(apps.get_models()) ~/cron_job.log >... >HELLO : 2018-01-05 10:00:02.283938 [<class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.auth.models.Group'>, <class 'django.contrib.auth.models.User'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'django.contrib.sessions.models.Session'>, <class 'my_app.models.UserProfile'>, <class 'my_app.models.Post'>, <class 'my_app.models.Comment'>, ...] >... But when I start to query my model entries: my_app/cron.py from datetime import datetime import blog_app.models def test(): print('HELLO : {}'.format(datetime.now())) for post in my_app.models.Post.objects.all(): print(post.title) nothing is printed out. The model entries exist though.Any idea? >... >django.db.utils.OperationalError: no such table: blog_app_post -
1025 MySql rename error in django
from django.db import models class InvoiceBill(models.Model): invoice_num=models.DecimalField(unique=True,max_digits=5,decimal_places=0) invoice_date=models.DateField(auto_now=True) cust_name=models.CharField(max_length=150) billed_by=models.CharField(max_length=150) def __str__(self): return self.cust_name+" Billed by: "+self.billed_by class ProductDetails(models.Model): invoice_id=models.ForeignKey(InvoiceBill,on_delete=models.CASCADE) product_name=models.CharField(max_length=250) quantity=models.DecimalField(max_digits=3,decimal_places=2,default=1.0) mrp=models.DecimalField(max_digits=5,decimal_places=2) selling_price=models.DecimalField(max_digits=5,decimal_places=2) discount=models.DecimalField(max_digits=2,decimal_places=2,default=0.0) class Meta: verbose_name_plural = "Product details" def __str__(self): return self.product_name this is manage.py and am using pip install mysqlclient DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangofirstinvoice', 'USER': 'root', 'PASSWORD': '12345', 'HOST': 'localhost', 'PORT': '3306' } } this one is the settings.py file this one works fine when i run command python manage.py migrate whit the mysql lite that comes with django but doesn't with mysql though tables are created, i made a new project and no error occurred is this because i changed mind to change my database?as am beginner just started learning django, please help -
lookup first_name having username in django
I am trying to get a first_name and last_name for logged in user. I could get them but they are displayed as : <QuerySet [{'first_name': 'steven'}]> I want to display only steven here is the view function: def user_profile(request): username = None if request.user.is_authenticated(): username = request.user.username pk = request.user.id first_name = MyUser.objects.filter(pk=pk).values('first_name') context = { 'username': username, 'pk' :pk, 'first_name': first_name, } return render(request, 'path/to/user_profile.html', context) in the template file: {{first_name}} -
Reading fingerprint input in python
I have a java application for fingerprint enrollment which works well using digitalPersona SDK. I however need to authenticate using the enrolled images in a web app I'm developing with django. I believe this should mean that the django app is able to read the fingerprint image from the scanner to compare with existing data. Is there a python library I can use to read the input? I have checked discussions on OpenCV forum but they seem to be focused on the comparison/verification of the image and not reading the image from the scanner. -
How to do a CBV CreateView with Extended user model django
I am currently learning about CBVs and what they provide in django. I am wondering how does one approach CBV CreateView for both the User model and Extended User Model so the page can display the accumulative fields for both? For example if I had this Extended model (example from django): https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#extending-the-existing-user-model And have this basic CBV setup: # views.py from django.views.generic import CreateView from .models import Employee class UserCreateView(CreateView): model = Employeee fields = ['department'] # employee_form.html <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="" value="Save"> </form> What ways does django provide that can allow this CBV to also display user fields to also be created in conjunction with employee? -
JWT Token expiration time increase
I have integrated JWT token with django-restframwork, here I have setted expiration time 15mints JWT_EXPIRATION_DELTA but it is getting expire before mentioned time(1mints) and I need to refresh the token for proceeding... PFB me configuration Python 3.5 Django==2.0.5 djangorestframework==3.8.2 djangorestframework-simplejwt==3.2.3 Setting.py REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=900), 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), } Please help, am I doing any mistake here. -
webpack style-loader displays css as a base64 encoded string inside the style tag
I am using the style-loader to load css. But the css displays as a base64 encoded string as follows: <style type="text/css"> data:text/css;base64,dmFyIgvZ...... many lines </style> The same bundle.js seems to work correctly inside an almost empty index.html. In this case it displays the CSS as a proper string. What am I doing wrong? -
What is the best way to learn a Web Framework when you have no experience with one before?
I am currently learning Django and it is the first ever Web Framework I've worked with. What is the learning curve for Django or Any Web Framework when you have no prior experience with them before? -
Django and Heroku, URL Not Found but Postman show me the response
i have this problem, for some reason Heroku send two respond from me call, one is correct but the other show this: Jun 09 12:38:54 app-url app/web.1: Not Found: url-to-api For this reason in a IONIC APP show me error 404, URL NOT FOUND. And POSTMAN show me the correct response. What need to do to fix this? I change the method, the url, but nothing, any answer for this? -
Ajax and Django
I have a jquery ajax code that looks like below,Its working on a delete button and a checkbox. $(".delete-row").click(function(){ $("table tbody").find('input[name="record"]').each(function(){ if($(this).is(":checked")){ var value = $('chk').val(); $(this).parents("tr").remove(); $.ajax({ url: "/delete/", // type: "post", // or "get" data: value }); }); }); }); This jquery call should delete the checked row in a table and the added ajax call will call a django view. My doubt is I am passing the checkbox value to django view in the above AJAX call. In this case how do django view come to know what table row to delete based on the checkbox value? this is how I have defined checkbox and delete button whose id's are used in the ajax call. <input type="checkbox" id="chk" name="record"></td> <button type="submit" name="erase" class="delete-row">Delete Row</button> -
Process Several Pcap Files Simultaneously - Django
In essence, the following function, called by the user of the django application that I am developing, uses the Scapy library to process 80-odd fairly large pcaps in order to initially parse their destination IP addresses. I was wondering whether it would be possible to process several pcaps simultaneously, as the CPU is not being utilised to it's full capacity, ideally using multi-threading def analyseall(request): allpcaps = Pcaps.objects.all() for individualpcap in allpcaps: strfilename = str(individualpcap.filename) print(strfilename) pcapuuid = individualpcap.uuid print(pcapuuid) packets = rdpcap(strfilename) print("hokay") for packet in packets: if packet.haslayer(IP): # print(packet[IP].src) # print(packet[IP].dst) dstofpacket = packet[IP].dst PcapsIps.objects.update_or_create(ip=dstofpacket, uuid=individualpcap) return render(request, 'about.html', {"list": list}) -
Running Django Management command in crontab
I am trying to run the management command python manage.py process_tasks provided by Django background tasks to run my background tasks. I want to run them as a cronjob. To do this I am creating a entry in cron tab using the command sudo crontab -e My crontab entry looks something like this - */1 * * * * . /var/www/cronjob.sh >> /var/www/crontab.log 2>&1 and the contents of the shell script which I am running here are - #!/bin/bash while true do echo 'starting' sudo su ubuntu . /var/www/myproject/env/bin/activate . /var/www/myproject/.shahrukh_aliases python /var/www/myproject/src/manage.py process_tasks echo 'finished' sleep 2 done But the problem is that my EC2 instance crashes after some time and runs only after I restart it. I get the following error -bash: fork: Cannot allocate memory I think it's consuming all the memory and hence my instance crashes. I don't know how to run the task in cron job and why it is consuming my memory. I want to know how can I run this job as a cronjob. Thanks for the help in advance -
DJANGO 2.0.5 'User' object has no attribute 'META'
I am trying to display the result of my sql aggregate query with Django(2.0.5) in my html view but i got this error message : 'User' object has no attribute 'META' However, I can see the result of my query in terminal because i print it in my view.py. So the connection with sqlite is working. I have written something like that in my view : class MyClass(UserPassesTestMixin, DetailView): def test_func(self, request): cursor = connection.cursor() cursor.execute('''select a, count(b), c, d from table1 inner join table2 ON table2.id = table1.b_id where c < 2 group by a, d order by d ’’’) results = cursor.fetchone() print(results) context = {“results”:results} return render(request, “path/file.html", context) In my urls.py file i have something like this : path(‘/path/’, MyClass.as_view(), name = ‘my-class’), And inside my template “file.html” I am trying to access my results when a button is clicked : {% trans ‘Show results’ %} I am still new with Django and Python. Thank you very much. -
User-Profile-Based-Webpage Tipps and Help for Beginning
I'm pretty new into learning programming. I do learn for myself and also in my IT school. I like to programmin a lot and so I'd like to start a Project but because I'm pretty a noob I'd like to ask for the advices of you skillful people :) I wanna build a homepage for a project, this homepage should have a small blog and also user profiles, where people can create an account and change thing like profile picture a small about me text and add friends, so pretty basic a small facebook. I were able to build a small blog watching a online tutorial and using Django and MySQL but now I'm stuck. The languages I'm able to use is HTML, CSS, some JS, Java and Python. But I'm always open to learn more!! I do also know the basics of PostgreSQL and MySQL. So I would like to ask the pros what would you suggest me? If you could answer me those following questions I'd be pretty happy and proud!! Which DB should I use? Which languages would you suggest me? If Python which one? (Flask, Django etc...) Do you know any good tutorials? I'm sorry for … -
need help for reservation system in python django
I'm trying to create a reservation system for a property. I have created the database models, my database structure is quite similar to this picture that i found http://www.access-diva.com/dm13/imag005.jpg as you can see in the date table there is rFromDate and rTodate. I want to implement that and I want to use dateField in django. but i'm not sure how i'm supposed to query this. I've never worked with dates before. also i thought i might be able to do this instead of the above example: a table with one dateField for each day of the year and one integerField for number of available rooms in that date. but then i thought how i'm supposed to query that and how the hell am i supposed to create the whole year. So at this point I'm completely stuck and i have no idea what should i do. I'm sure this task for some of you out there is quite simple but since I've never worked with dates and querying them i'm kinda stuck. I'd be really grateful if you could help me. thanks. -
Django parse template templatetags arguments
I am trying to parse a template and extract the first argument passed to a custom template tag. My first approach was to use regular expressions. So for example a template in a given template: {% mytag "name-1" %} <div></div> {%mytag 'name2'%} {% mytag 'name-3' 'arg1' %} I could use a regex similar to: tag_parser = re.compile(r'{%\s+mytag\s+\'([^\']+)') But as you can see a template tag can have single or double quotes and different syntax allowances that make it seem a bit difficult to parse with a regular expression given the fact that there should exist something like it already in Django. Given the template above as an example, is there a Django way of parsing a template and get the arguments for a given template tag ? -
Django TemplateDoesNotExist error keeps showing and files are not in the `django/contrib/admin/templates/` directory
I created a templates directory in my django project and then created fun directory inside of which i have fun.html file.In order to access this file i have the following code in my views.py: from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render_to_response def index(request): template_name = 1 return render(request,'fun/fun.html') and here is the directory of my project:enter image description here I checked /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/templates/ and unfortunately nor my directory nor my files were there. I tried Changing template 'DIRS', in settings.py to os.path.join(BASE_DIR, 'templates'), and rerunning the server,neither worked. -
Django 1 to Django 2 on_delete error
I believe this workflow was created for a previous Django version. Now when I am trying to upgrade it I get an error to add on_delete. Here is what I have done but it is still not working and I'm wondering what I am doing wrong. ORIGINAL class Task(AbstractEntity): request = ForeignKey(Request, related_name='tasks') assignee = ForeignKey(Group) updated_by = ForeignKey(User) activity_ref = CharField(max_length=100) status = CharField( verbose_name="Status", max_length=30, choices=TASK_STATUS) MY VERSION class Task(models.AbstractEntity): request = models.ForeignKey(Request, related_name='tasks', on_delete=models.CASCADE) assignee = ForeignKey(Group) updated_by = ForeignKey(User) activity_ref = CharField(max_length=100) status = CharField( verbose_name="Status", max_length=30, choices=TASK_STATUS) Then I get another error saying the model is not defined. -
Automatically connect one models' object to other in django rest framework
I have two models (non-user type) with relation ForeignKey. I need to connect or give the value of one models object to other without choosing but automatically. How can I do that? -
Having unexpected Error in Django EditView
When i hit the url i find all my fields are empty instead of having populated values, but when i try to edit them from django admin they work fine.I can see all my values there and when i can change their values also. models.py from django.db import models class Post(models.Model): name = models.CharField(max_length=10) choice = (('pending','pending'),('approve','approve'),('reject','reject')) test = models.CharField(choices=choice,max_length=10,default=choice[0][0],blank=True) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['name','test'] urls.py urlpatterns = [ path('<int:pk>/edit/',views.index), ] models.py def index(request,pk): if request.user.is_superuser: try: query = Post.objects.get(id=pk) print(query) except: raise Http404('0') form = PostForm(request.POST or None, instance=query) print(form) if request.method == 'POST': print(form) if form.is_valid(): form.save() return redirect('all') else: form = PostForm(request.POST, instance=query) return render(request, 'index.html',{'form':form}) index.html <form method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="submit"> </form> when i try to print each and every step, this step if form.is_valid shows no output. There is no error though in console it works fine,doenst work the way i want it to be. -
Create exel file and download it
I have class Line in models.py. Also I have hlml file which consist from elements of this class. I want to add the button in html file which allows create exel file and download it by user. How I can to realize this idea.? PS. This is may be a stupid question, but I' begginer in django and don't know how to make it. -
`This field required error` though it's not defined in Model data table
I try to create a new article with model data: class Article(models.Model): STATUS = ( (0, 'normal'), (-1, 'deleted'), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) block = models.ForeignKey(Block, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() # set the widget status = models.IntegerField(choices=STATUS) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title However, when I submitted data from browser, it prompted that comment field is required thought it's not one of Article's fields. I add a test command print(form.errors.as_data()) in CBV class ArticleCreateView(View): Starting development server at http://127.0.0.1:8001/ Quit the server with CONTROL-C. {'comment': [ValidationError(['This field is required.'])]} [09/Jun/2018 22:50:16] "POST /article/create/1 HTTP/1.1" 200 3694 I have other table Comment whose ForeignKey is article class Comment(models.Model): STATUS = ( (0, 'normal'), (-1, 'deleted'), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) comment = models.TextField() # set the widget status = models.IntegerField(choices=STATUS) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.comment I had no idea why it throw such an error? -
Mix two models to the same endPoint in DRF
I am learning DRF right now, and I would like to know can I mix two models link by foreign key to one specific endpoint. For example let say that I have two models: Model1: class Car(models.Model): Name = models.CharField(max_length=500, null=True, blank=True) Year = models.CharField(max_length=500, null=True, blank=True) Model2: Class Revision(models.Model): revision1 = models.CharField(max_length=500, null=True, blank=True) revision2 = models.CharField(max_length=500, null=True, blank=True) car_is = models.ForeignKey( Car, on_delete=models.CASCADE, null=True, blank=True) What I would like to achieve would be to get at url: "/car/1" (car datails) the data of the specific car with the Revisions. I am using Class Based view with DRF -
checkbox and submit button without any form element
I am trying to create a checkbox html element and a submit button. But my requirement is they should not be a part of a html form element. Now I need to use these 2 elements inside a Django view. Is there anyway I could achieve this . I am not sure how to access the not form elements inside django view.