Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: oldest entry for distinct fields
I have the following models (simplified for sample purposes): class Execution(models.Model): name = models.CharField(null=False, max_length=30) creation_date = models.DateTimeField(auto_now_add=True, null=False) class Post(models.Model): class Meta: unique_together = ('code', 'secondary_code', 'execution') code = models.CharField(null=False, max_length=30) secondary_code = models.CharField(null=False, max_length=3) execution = models.ForeignKey(Execution, null=False, on_delete=models.CASCADE) text = models.TextField() On the database I have the following instances: execution_1 = Execution('Execution 1', '2019-01-01') execution_2 = Execution('Execution 2', '2019-01-02') post_1 = Post('123', '456', execution_1, 'lorem') post_2 = Post('789', '999', execution_1, 'ipsum') post_3 = Post('789', '999', execution_2, 'dolor') I want to retrieve all the posts, unique for code and secondary_code (so, only one between post_2 and post_3 since they have the same code and secondary_code) and chose the one to get based on the oldest execution (so, in this case, I want post_1 and post_2 since the execution of post_2 is older that the execution of post_3). I need to support both Postgres and sqlite3 3.18.0, so, because of sqlite, I cannot use window functions. How to do this? -
How to get the filepath while uploading a file to azure-storage in django
i have a form in which files can be uploaded.the uploaded file has to be stored in azure-storage. i am using create_blob_from_path to upload a file file to azure-storage.create_blob_from_path expects filepath as one of the parameter. but how can i get file path in this case as the operation has to be in on the fly mode(The uploaded file can not be stored in any local storage).it should get stored directly in azure. if request.method=="POST": pic=request.FILES['pic'] block_blob_service = BlockBlobService(account_name='samplestorage', account_key='5G+riEzTzLmm3MR832NEVjgYxaBKA4yur6Ob+A6s5Qrw==') container_name ='quickstart' block_blob_service.create_container(container_name) block_blob_service.set_container_acl(container_name, public_access=PublicAccess.Container) block_blob_service.create_blob_from_path(container_name, pic, full_path_to_file)//full_path_to_file=? the file uploaded dynamically has to be stored in azure -
Look up by primary key in graphene-django (with relay)
I'd like to be able to write a query that looks like this, using a human primary key rather than the opaque relay IDs: query { issue(pk: 10) { pk state } } I've been able to add the int pk field from the model; however, I haven't been able to figure out how to query it (and I'm a little confused about how I'd switch to a custom filterset for this). from django.db import models import graphene from graphene import relay class Issues(models.Model): state = models.CharField(default='') text = models.TextField(default='') class IssueNode(DjangoObjectType): pk = graphene.Int(source='pk') class Meta: model = Issue interfaces = (relay.Node,) filter_fields = ['pk', 'state'] class Query(graphene.ObjectType): issue = relay.Node.Field(IssueNode) issues = DjangoFilterConnectionField(IssueNode) This will raise an error about pk: TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: pk With this set up, I can write a query that looks like: query { issue(id: 'ascadf2e31af=') { state } } but since the application previously used human readable IDs, I'd like to support that as well. Any ideas on how to set up a custom filterset or if there's a native way to do this with graphene-django? -
Upgrade to Django 2.2: AttributeError: module 'statistics' has no attribute 'pstdev'
Upgraded Django from 1.11 to 2.2. After cleaning up some obvious stuff as described in various upgrade checklists, got stuck on this one which does not seem to be answered anywhere. Migration chokes on some "statistics" module. Probably some dependent module is not compatible anymore: Trying: > python manage.py runserver Getting: File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 230, in get_new_connection conn.create_aggregate('STDDEV_POP', 1, list_aggregate(statistics.pstdev)) AttributeError: module 'statistics' has no attribute 'pstdev' The full traceback: Exception in thread Thread-1: Traceback (most recent call last): File "/Users/myuser/miniconda3/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/Users/myuser/miniconda3/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/Users/myuser/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/myuser/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/Users/myuser/.local/lib/python3.5/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/Users/myuser/.local/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 230, in get_new_connection conn.create_aggregate('STDDEV_POP', 1, … -
How can I insert rows to DB in django from the code without forms
I opened a project in Jungo I worked closely with their training and when I got to the stage of posting rows to DB (after I created the modules that suited me) ,the way the guide suggested to me was to insert from the UI through the site itself - Or through PYTHON SHELL, The problem is that the data I need to enter into the site are not data that I am supposed to enter manually, I scraped it from another source, I have a Python file with a function that returns a list of objects that I need to insert into the DB When I tried various ways to combine the call to the above function in the ADMIN.PY file I encountered many errors and would be happy if you could direct how to do so -
Django-allauth initially creates a user- why?
I have just added django-allauth to our project. On launching the app I run no seeding, yet when i check the users there is a single user created: "AnonymousUser". from django.contrib.auth import get_user_model User = get_user_model() User.objects.all()[0].__dict__ { '_state': <django.db.models.base.ModelState object at 0x7fc0cb644c50>, 'id': 1, 'password': '!ckXY3T...wUhuko52q', 'last_login': None, 'is_superuser': False, 'username': 'AnonymousUser', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 5, 2, 8, 22, 32, 317584, tzinfo=<UTC>) } When using the django standard auth model no user was created by default. My settings and custom user model are below: # settings.py # Authentication AUTH_USER_MODEL = 'accounts.CustomUser' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True # accounts.models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): def __str__(self): return self.email I can't find any documentation about this in the allauth docs, or by googling variations of "allauth AnonymousUser created". Why was a user created using allauth, and how can i disable this? -
JWT authentication in django 1.6
I am a newbie to django and I'm trying to implement JWT authentication. I have multiple micro-services, and I have a few questions. Right now what I am doing is- While logging into the first micro-service, adding the JWT token using request.session["Authorization"] = "Token " + my_token Is this the correct way of storing the JWT? I wrote a custom authentication class JWTBackend which implements authenticate method with signature that looks like: def authenticate(self, request): .... Then I added the path of this class to AUTHENTICATION_BACKENDS in settings.py. But django is not even entering my authenticate method. I know that usually authenticate methods have username and password as parameters, but mine has request. What should I change for my method to work? -
Displaying Wrong data in web Page by interacting with MySQL database
while opening the web page of dashboard , overall volume showing =0 (Correct) but we go for numpy chart of same data , its shows the data. how its this possible if there is no data in database between 28th April to 5th May . then how data showing in numpy chart column... -
Checking the return value of a custom templatetag in a template
I have created a custom template tag which does some processing and returns 1, if all goes well,0 if not. In my template I want to check the returned value, and if it is 1, display an image. How should I go about doing this? The name of my function is fname which takes an argument n, and return a value of 1 or 0. So, I want to check {% if fname n %} <img src=""> {% endif %} my custom templatetag called testing.py def fname(name): path = 'media/' path += name if path != "media/": x_test = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB) x_test = np.array(x_test)/127.5 - 1. x_test = x_test.reshape((1, 256, 256, 3)) #1 since keras expects first element of shape to be reserved for batch size gen = generator.predict(x_test) scipy.misc.imsave("main/static/main/modimages/"+name, gen[0]) return 1 else: return 0 in my template {% load testing %} {% if fname n %} <img src="abc.jpg"> {% endif %} -
Authenticate through OTP sent to email of user
I want to send an OTP to the user's email Id. I checked I can send the eamil through the Django's send_eamil() method with random no. I am using the following to generate the random no. from django.utils.crypto import get_random_string otp = get_random_string(6, allowed_chars='0123456789') Now my question is how I can make it valid for a specific time in backend. Should I use session or cache or something else to store the otp. I have hardtime to figure out this. -
Django: User special permission is not working
I am new to Django. I am working on a project in which i have made special permission to manager if a user have that permission then it will render 'manager' page. But user.has_perm is returning false. here is my views.py def login(request): if request.method =='POST': # print(request.POST) username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) print (user.has_perm('app.edit_task')) # return redirect('index') if user.is_superuser: return redirect('master') elif user.has_perm('app.edit_task'): return redirect ('manager') else: return redirect('index') else: messages.error(request, 'Invalid Credentials') return redirect('login') else: return render(request, 'vadash/sign-in.html') here is my models.py class manager(models.Model): name = models.CharField(max_length= 500) designation = models.CharField(max_length= 500) class Meta: permissions = [ ("edit_task", "can edit the task"), ] if the user has that permission then it will render managers page. But user.has_perm is returning false. -
how to solve encoding error on django when taking input from forms
i get an error when i try to get data from a post request i'm trying to make a user model (apart from the built in one could be any model with 3 inputs ) File "C:\Users\o00489658\AppData\Local\Continuum\anaconda3\lib\site-packages\django\contrib\staticf return self.application(environ, start_response) File "C:\Users\o00489658\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\w response = self.get_response(request) File "C:\Users\o00489658\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\b response = self._middleware_chain(request) File "C:\Users\o00489658\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\e response = response_for_exception(request, exc) File "C:\Users\o00489658\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\e response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "C:\Users\o00489658\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\e return debug.technical_500_response(request, *exc_info) File "C:\Users\o00489658\AppData\Local\Continuum\anaconda3\lib\site-packages\django\views\debug.py" html = reporter.get_traceback_html() File "C:\Users\o00489658\AppData\Local\Continuum\anaconda3\lib\site-packages\django\views\debug.py" t = DEBUG_ENGINE.from_string(fh.read()) UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence my models.py from django.db import models class kullanici(models.Model): id=models.IntegerField(unique=True,primary_key=True) Name=models.CharField(max_length=128) LastName=models.CharField(max_length=128) def __str__(self): return self.id+' '+(self.Name)+' '+(self.LastName) view from django.shortcuts import render from django.http import HttpResponse from myapp import forms from myapp.forms import UsernameForm def homepage(request): mydict ={'inserted':'inserted via django '} return render(request,"Linked_page.html",context=mydict) def secondpage(request): form = forms.UsernameForm() form2 =UsernameForm(data=request.POST) if request.method=='POST': form=forms.UsernameForm(request.POST) print('valid as in entry standard') print(form) form2.save() return render(request,'onyuz.html',{'form':form}) def Users(request): userlist=kullanici.objects.order_by('id') mydict ={'access_records':userlist} return render(request,"onyuzmodetrator.html",context=mydict) form from django import forms from myapp.models import kullanici class UsernameForm(forms.Form): Name=forms.CharField() LastName=forms.CharField() id=forms.IntegerField() class Meta(): model=kullanici fields='__all__' html İt has {% load static %} on the top <form class="" method="POST"> {{form}} {% csrf_token %} <input type="submit" name="" placeholder="Submit"> </form> -
How to fix "Error Cannot read property 'hidden' of undefined" when trying to plot Chart.js from views.py
I'm trying to plot a graph from the database by using axios endpoint to get the data. I suspect it has something to do with the format. As I can see still see the correct data when navigating to api/chart/data/. I have two variables, one is working fine but another is undefined: total_km and sorted_vehicle_list so when I console.log(labels), it said "Error Cannot read property 'hidden' of undefined" P.S. sorted_vehicle_list has one only instance and returns as a list [] (which I'm sure if it's the problem) I have tried to print the output of the query in views.py and the output is correct. It returns the data that I want but somehow Chart.js can't see it. class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): all_vehicles = LoggerRecord.objects.values('imei').distinct() vehicle_list = [] for vehicle in all_vehicles: vehicle_list.append(vehicle['imei']) sorted_vehicle_list = sorted(vehicle_list) #create sum km total_km = LoggerRecord.objects.aggregate(Sum('distance')) print(total_km) print(all_vehicles) data = { 'all_vehicles': all_vehicles, 'total_km': total_km } return Response(data) axios.get(endpoint) .then(function (response) { labels = response.data.sorted_vehicle_list total_km = response.data.total_km console.log(labels) console.log(total_km) var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx2, { // The type of chart we want to create type: 'bar', // The data for our dataset … -
Merged 2 model objects in python and provided datas not showing in one row (used data tables to list datas from db)
I have created two models and using formset combined both models in one page. but when am trying to list out the datas in list page(using data tables, this will list created datas from db), it is showing one models in one row and another models in 2nd row. I want to display it on same row using one id. models.py class Sensiple(models.Model): EmployeeName = models.CharField(max_length=20) Employeemail = models.EmailField(max_length=50, blank=False, unique=True, validators=[validate_email]) EmployeeLocation = models.CharField(max_length=10, choices=LOCATION_CHOICES, default='') EmployeeQualification = models.CharField(max_length=10, choices=Qualif_CHOICES, default='') EmployeePhoneNumber = models.IntegerField() class Meta: db_table = "generic" class Adding(models.Model): Experience = models.CharField(max_length=10, choices=YEARS_CHOICES, default='') Address = models.CharField("Address Line 1", max_length=100, default='') zip_code = models.CharField("ZIP/Postal code", max_length=12, default='') LastWorked = models.CharField(max_length=30, default='') class Meta: db_table = "Test" views.py def show(request): generics = Sensiple.objects.all().order_by('-id') extras = Adding.objects.all() employee_list = list(chain(generics, extras)) for item in employee_list: print("ssss", item.id) return render(request,'show.html',{'employee_list':employee_list}) -
Django: CSS is not getting applied
I have placed all my CSS files in static/css folder. My settings are: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') While the media files are working properly, and the images kept in static/images folder are also appearing, the CSS styling are not appearing. For each page, I am creating a CSS file, placing that in static/css folder, and calling it like this: {% load static %} <head> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/getting-started.css' %}"> <--this </head> Though the bootstrap.min.css is working, the CSS are not working. -
How to change incorrect Django Path (django.__path__)?
I have pip installed django into my project and now it seems that my Django Project is confused about what Django installation should it be running. When I run python manage.py shell and import django django.__path__ Shell returns incorrect path: ['D:\\project_2\\venv\\lib\\site-packages\\django'] Since I am working on project_1, I expect the following path: ['D:\\project_1\\venv\\lib\\site-packages\\django'] Is there a quick fix? -
How to fix {% extends %} in django
i'm building a social blog and when i remove {% extends %} in html file my code works and display the code when i put it agin doesn't display the code only the nav barenter image description here enter image description here enter image description hereenter image description here -
HSTS headers for Django + Nginx projects - should the headers be set by Django SecurityMiddleware or Nginx?
HSTS = HTTP Strict Transport Security From the Django Docs on HSTS For sites that should only be accessed over HTTPS, you can instruct modern browsers to refuse to connect to your domain name via an insecure connection (for a given period of time) by setting the “Strict-Transport-Security” header. This reduces your exposure to some SSL-stripping man-in-the-middle (MITM) attacks. SecurityMiddleware will set this header for you on all HTTPS responses if you set the SECURE_HSTS_SECONDS setting to a non-zero integer value. However this header can also be set by Nginx in the conf file, by adding a line: add_header Strict-Transport-Security "max-age=63072000; includeSubdomains;"; So the question is, should we configure Nginx to set this header or Django SecurityMiddleware, by adding the HSTS settings in the project settings file? -
How to create or update value to relationship model
I want to save the Portfolio products details in PortfolioProducts model in django I have models like below: class Product(models.Model): name = models.CharField(max_length=255,null=True, verbose_name ='Name') class Portfolio(models.Model): name = models.CharField(max_length=100, blank=True, null=True, verbose_name ='Name') class PortfolioProducts(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, verbose_name ='Portfolio') product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name ='Product') Portfolio form: class PortfolioForm(forms.ModelForm): class Meta: model = Portfolio fields = ['name'] My view file: def edit(request): portfolio_form = PortfolioForm if request.method=="POST": portfolio_id=request.POST.get('portfolio_id') portfolio_detail = Portfolio.objects.get(pk=portfolio_id) pform = portfolio_form(request.POST, instance=portfolio_detail) if pform.is_valid(): portfolio = pform.save(commit = False) portfolio.save() products=request.POST.getlist('product_id[]') for product in products: ppform = PortfolioProducts(product_id=product, portfolio_id=portfolio_id) port_product = ppform.save() I am trying to save and update the Portfolio products like this, but is adding products to portfolio multiple time. -
How to return empty response from root URL in Django
I have a Django app using djangorestframework. I want to return an empty response or nothing if the root URL is called. Below is my code. url(r'^$', HttpResponse(''), name="redirect_to_somepage") Expected output: [] or {} -
how to use front-end filter system in django template/
I have only one page for all the action.and only one url in urls.py. and In the menu section there are several food category .how can i show foods only belonging to the specific category.and there is a front-end filter system in design for this .how can i use frontend filter system in django. i want to keep my design like this.HOw can i use front end filter system in django models.py class MenuCategory(models.Model): title = models.CharField(max_length=250) slug = AutoSlugField(populate_from='title') active = models.BooleanField(default=True) featured = models.BooleanField(default=False) def __str__(self): return self.title class Meta: verbose_name_plural = 'Menu Category' class Food(models.Model): name = models.CharField(max_length=250) price = models.CharField(max_length=100) detail = models.TextField(blank=True) category = models.ForeignKey(MenuCategory,on_delete=models.DO_NOTHING) image = models.ImageField(upload_to='Foods',blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'Foods' views.py def homepage(request): featured_dishes = Food.objects.filter(featured=True) menu_categories = MenuCategory.objects.filter(active=True) foods = Food.objects.filter(active=True) return render(request,'cafe/base.html',{ 'menu_categories':menu_categories, 'featured_dishes':featured_dishes, 'foods':foods, }) base.html I have a single homepage. <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#about">About</a> </li> <!-- <li class="nav-item"> <a class="nav-link" href="#">Special</a> </li> --> <li class="nav-item"> <a class="nav-link" href="#menu">Menu</a> </li> <li class="nav-item"> <a class="nav-link" href="#gallery">Gallery</a> </li> <li class="nav-item"> <a … -
Django NoReverseMatch exception
I have got a function refresh in my views.py file and I want to redirect it to another function jenkinsreport in the same file but I am getting NoReverseMatch error.Can someone please point what am I doing wrong.I am new to Django so any help would be appreciated.I have looked for solution but I cant seem to fix it. #views.py def refresh(request): server = jenkins.Jenkins('link',username=username,password='password') jobs = server.get_jobs() job_name_list=[] build_number_list=[] build_info_list=[] status_list_dict={} tme=time.time() print tme time_now=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tme)) print time_now tmelastmonth=tme-2592000 time_from=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tmelastmonth)) tmemiliseconds=tmelastmonth*1000 #print dir(server) for i in range(len(jobs)): job_name=jobs[i]['name'] job_name_list.append(job_name) for i in range(len(job_name_list)): job_info=server.get_job_info(job_name_list[i]) lastbuilt=job_info['lastSuccessfulBuild'] if lastbuilt: b_number=job_info['lastSuccessfulBuild']['number'] build_number_list.append(b_number) build_zipped=zip(job_name_list,build_number_list) print build_zipped for i ,j in build_zipped: success=0 failure=0 unstable=0 aborted=0 try: for k in range(j,1,-1): build_info=server.get_build_info(i,k) if build_info['timestamp']<tmemiliseconds: break build_info_list.append(build_info) status=build_info['result'] if status=="SUCCESS": success+=1 elif status=="FAILURE": failure+=1 elif status=="UNSTABLE": unstable+=1 else: aborted+=1 statuscount=[success,failure,unstable,aborted] status_list_dict[i]=statuscount except: pass for job in status_list_dict: build_status_object = Build_status_count.objects.filter(Job_name=job) if not build_status_object: build_status_count = Build_status_count() build_status_count.Job_name =job build_status_count.Time_from = time_from build_status_count.Time_to= time_now build_status_count.Successful=status_list_dict[job][0] build_status_count.Failure=status_list_dict[job][1] build_status_count.Unstable=status_list_dict[job][2] build_status_count.Aborted=status_list_dict[job][3] build_status_count.save() else: for obj in build_status_object: obj.Time_from = time_from obj.Time_to=time_now obj.Successful=status_list_dict[job][0] obj.Failure=status_list_dict[job][1] obj.Unstable=status_list_dict[job][2] obj.Aborted=status_list_dict[job][3] obj.save() return redirect('jenkinsreport') def jenkinsreport(request): Build=Build_status_count.objects.all() status_list_dict={} testdict={} for build in Build: job_name=build.Job_name jb=job_name.encode("utf-8") success=build.Successful sc=success.encode("utf-8") scint=int(sc) failure=build.Failure Unstable=build.Unstable Aborted=build.Aborted status_list=[int(success),int(failure),int(Unstable),int(Aborted)] … -
In Django models need validation help on two fields with one dropdown field option making another field mandatory
I Have two fields one is a dropdown called payment method and other is a field called cheques, if the payment method in dropdown is chosen as cheques then the cheques field should be mandatory, i need to validate this in model level, if payment method is cheques and cheques field is empty then raise error, i need help on this please. i havent tried any method yet PAYMENT_METHOD = ( ('cash', 'Cash'), ('credit card', 'Credit Card'),('debit card', 'Debit Card'), ('cheques', 'Cheques') ) payment_method = models.CharField(max_length=255, choices = PAYMENT_METHOD, verbose_name= "Payment Method") cheques = models.IntegerField(blank=True, null=True) i want this in such a way that in the front end form when we chose payment method cheques, the cheques field should be mandatory and when the chosen payment method is cheques and cheques field is left blank it should raise an error. -
Thumbnail generation failed
I'm currently using versatile image to generate thumbnails, but it throws many of the same errors relating to the fact that a thumbnail couldn't be generated even when the model instance that is being created doesn't require one. Also, django does have permission to write images to C:\Users\jason\Desktop\staticfiles\media_root'. When I actually upload an image, versatileimage does successfully write the image and thumbnail into media_root. Here is an example of the error: Thumbnail generation failed Traceback (most recent call last): File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\image_warmer.py", line 117, in _prewarm_versatileimagefield url = get_url_from_image_key(versatileimagefieldfile, size_key) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\utils.py", line 216, in get_url_from_image_key img_url = img_url[size_key].url File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\datastructures\sizedimage.py", line 149, in __getitem__ height=height File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\datastructures\sizedimage.py", line 201, in create_resized_image path_to_image File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\datastructures\base.py", line 140, in retrieve_image image = self.storage.open(path_to_image, 'rb') File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\files\storage.py", line 33, in open return self._open(name, mode) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\files\storage.py", line 218, in _open return File(open(self.path(name), mode)) PermissionError: [Errno 13] Permission denied: 'C:\\Users\\jason\\Desktop\\staticfiles\\media_root' -
How to give value in variable while edit form in python
I am working on edit form, when i go for edit i want to show pre loaded values for that form, but when i set value in the variable it doesn't working for me,can anyone please help me to resolve this issue ? here i have added my whole code views.py def add(request,id=None): pass if request.POST: title = request.POST.get("title") permialink = request.POST.get("permialink") updated_date = request.POST.get("updated_date") bodytext = request.POST.get("bodytext") page_data = Pages(title=title,permialink=permialink,updated_date=updated_date,bodytext=bodytext) page_data.save() return HttpResponseRedirect(reverse('crud:index', args=(''))) else: if id is not None: page_data = Pages.objects.all().filter(id=id) context = {"page_data":page_data} return render(request,'polls/add.html',context) else: return render(request,'polls/add.html') add.html {% load static %} {% if page_data %} title = page_data.title permialink = page_data.permialink {% else %} title = '' permialink = '' {% endif %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> <form method="post" action="{% url 'crud:add' %}" name="page_form" id="page_form"> <input type="text" name="title" value="{{ title }}"> <input type="text" name="permialink" value="{{ permialink }}"> <input type="text" name="updated_date" value=""> <input type="text" name="bodytext" value=""> {% csrf_token %} <input type="submit" name="submit" value="Submit"> </form>