Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query that filters on calculated fields, searching for character within string
I have a django model that describes a cyclical status between two dates. It looks something like: class OnCallCycle(models.Model): crew = models.ForeignKey(Crew, on_delete=models.CASCADE) start = models.DateField() end = models.DateField() cycle = models.CharField(max_length=255) where start and end are the inclusive start and end date of the cycle, and cycle is a string representing the on call status cycle using one character per day. E.g.- if you had a 12 day cycle where the first 6 days were on (represented by a P), and the last 6 days were off (represented by an N, cycle would look like: PPPPPPNNNNNN. If the number of days between start and end are greater than the length of the cycle, it repeats. Thus, given an OnCallCycle instance, occ, one can calculate the on call status for a given date, d (known to be between start and end) by: delta = (d-occ.start).days status = occ.cycle[delta % len(occ.cycle)] Is there any way to do this within a query for a given date, d? I would like to do something like this: active_cycles = OnCallCycle.objects.filter( start__lte=d, end__gte=d ).filter( # Find all OnCallCycles where the cycle status for date d is not 'N' ) I am using Postgres for my … -
function inside class is not defined?
I'm trying to check if the unique id generated is unique in the database because it's only 6 characters. class Images(models.Model): uid = models.CharField(max_length=10, default=genid(), editable=False) def genid(): uid = uuid.uuid4().hex[:6] if Images.objects.get(uid=uid).exists(): uid = uuid.uuid4().hex[:6] return uid but it's not working. it tells me genid is not defined, Images is not defined. how can I fix this? thanks -
'[Errno 13] Permission denied: '/static'' even when I have permissions? Django Admin
I recently finished deploying my website using apache2 and django. I was testing everything, including the uploading process. But, when I select a file to upload and hit 'Save', it gives me an error: PermissionError at /admin/path/path2/add/ [Errno 13] Permission denied: '/static' I have all the right permissions, since I wrote these commands to allow permissions: sudo chown -R :www-data project/static sudo chmod -R 775 project/static sudo chown :www-data project/db.sqlite3 sudo chmod 664 project/db.sqlite3 sudo chown :www-data project/ This works, since when I do ls -l, the permissions are correct. This is my apache2 config file (just the static folder part): Alias /static /home/alexholst/excelsite/static <Directory /home/alexholst/excelsite/static> Require all granted </Directory> My settings.py file has this as STATIC_ROOT and STATIC_URL: STATIC_URL = '/static/' STATIC_ROOT = '/home/user/project/static' I dont know if this has to do with anything, but my css does load so i dont think it should have to do with the settings.py. Any suggestions are very much appreciated! -
django-dynamic-formset: copy values on adding form
I am using django-dynamic-formset to add forms of 2 inputs. I would like to to copy the values entered to the fields when the user clicks 'add another'. As far as I understand the description, this can be done with the option keepFieldValues. The script portion is this one <script type="text/javascript"> $('.formset_row-{{ formset.prefix }}').formset({ prefix: '{{ formset.prefix }}', keepFieldValues: '#id_set_set-0-id', }); </script> The part of the template renders as <tr class="row1 formset_row-set_set"> <td> <input type="hidden" name="set_set-0-id" id="id_set_set-0-id"> <input type="hidden" name="set_set-0-workout" id="id_set_set-0-workout"> <div id="div_id_set_set-0-reps" class="control-group"> <div class="controls"> <input type="number" name="set_set-0-reps" placeholder="reps" min="0" class="numberinput" id="id_set_set-0-reps"> </div> </div> </td> Am I misunderstanding the option or how should I apply it? I tried a couple of different options but without any success. TIA! -
Django URL as a variable not working for external site
I have a link being rendered to a template in Django, which changes from record to record. the HTML comes up blank, even though I verified the link works when hard coding it in the site. HTML source rendered: <div id="container2"> <img id="image2" src="" style="width:75%;height:40%;"> </div> source HTML template: <div id="container2"> <img id="image2" src="{{trip.pcs_mca_image.url}}" style="width:75%;height:40%;"> </div> the variable itself is a fully qualified URL such as https://googalopolis.photos.category.jdslkjf.blah.blah when I copy/paste the URL and not use jinja variable it works, but this is issue as each refresh is a new link. -
DjangoCMS - multisite with shared pages
I'm trying to build several websites with DjangoCMS with some shared pages. Is it possible to create a page which is shared across all django Sites? When looking at the code I've seen that the TreeNode is linked to a specific Site (https://github.com/divio/django-cms/blob/develop/cms/models/pagemodel.py#L52), so I guess that if it's possible it won't be really simple (even if I hope so :p). I'd be fine with an external module if DjangoCMS does not handle this, or even some ideas or lead of how to code this, I really don't have a clue. Thanks! -
Use foreign key in django_tables2
I am using django_tables2 to display some data, however one of the columns uses a foreign key and I can't figure out why this data isn't being displayed. I know the foreign key is working, since I can access it in the shell using: In [25]: b = Forms.objects.get(id = "v_akkadianakka1240-mM-1") In [26]: b.source.display Out[26]: 'Black 2000' But it is not clear to me how this translates to the table.py class. model.py class Sources(models.Model): category = models.TextField(db_column='CATEGORY', blank=True) bibtexkey = models.TextField(db_column='BIBTEXKEY', blank=True, primary_key = True) display = models.TextField(db_column='DISPLAY', blank=True, null=True) class Meta: managed = False db_table = 'sources' def __unicode__(self): return self.display class Forms(models.Model): id = models.TextField(db_column='ID', blank=True, primary_key = True) # Field name made lowercase. local_id = models.IntegerField(db_column='Local_ID', blank=True, null=True) # Field name made lowercase. language_id = models.TextField(db_column='Language_ID', blank=True, null=True) # Field name made lowercase. parameter_id = models.TextField(db_column='Parameter_ID', blank=True, null=True) # Field name made lowercase. value = models.TextField(db_column='Value', blank=True, null=True) # Field name made lowercase. form = models.TextField(db_column='Form', blank=True, null=True) # Field name made lowercase. segments = models.IntegerField(db_column='Segments', blank=True, null=True) # Field name made lowercase. comment = models.TextField(db_column='Comment', blank=True, null=True) # Field name made lowercase. source = models.ForeignKey(Sources, on_delete=models.CASCADE, db_column='source') cognacy = models.IntegerField(db_column='Cognacy', blank=True, null=True) # Field name made … -
Subquery for returning the most recent foreign key less than equal to a date
I have two models, Rank and Product. Rank has a foreign key Product. Every day a new Rank is created for each product. However, occasionally an error happens and some date may not have a Rank object for a Product. Therefore, I am trying to return a QuerySet that grabs the most recent Rank object less than or equal to date_str for every Product object. date_str can be any arbitrary date. If several Products do not have Rank objects with a pub_date equal to date_str this queryset should return the most recent Rank in the database before date_str. I thought this function would work, but it fails to return anything at all when an exact match for date_str is not found. date_str = '2020-04-27' def get_queryset(self): r = super().get_queryset().filter(pub_date__lte=self.date_str) return r.filter( pub_date=Subquery( (Rank.objects .filter(product=OuterRef('product')) .values('product') .annotate(last_updated=Max('pub_date')) .values('last_updated')[:1] ) ) ).order_by('-day_rank') -
Is there any way to set up a password for my sqlite3 database in Django?
I have made a ToDoList app using Django. It's a rather simple app as I made it while I was just learning Django. I am still a novice programmer. Anyways, for the database I went with Django's default offering SQLite 3. Now my app won't be used by millions of users around the world so a lightweight database works fine but my main concern is that the database is not protected via a password. For production, the app is hosted on PythonAnywhere via their free tier service and they support SQLite3 for free. I know using something like Postgres is preferred for production scale use. But the app is only made as a personal project and no one is likely to use it for commercial use so SQLite3 seems fine. Moreover, using Postgres would require a paid account on PythonAnywhere. So, I was wondering if I could do something to set up a password for my db file. My settings.py file is this: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
Confusion creating modal form with Django ModelForm
I'm trying to create a pop-up form for a web app where doctors select a journal (research/scientific journal name) and input some information and it gets added to a list of components showing that information. I'm trying to abstract the form used for them to input journal information into a pop-up form, and am really surprised by how much work it is to add this functionality. I am a beginner with Bootstrap, and am using https://pypi.org/project/django-bootstrap-modal-forms/ because apparently it's almost impossible to get Bootstrap modals to work with Django otherwise. Here are the code changes to the relevant files specified by the library--I have replaced their "create-book" with "create-journalentry" etc. There is a lot of code but it's really a very simple app, and this inability to get modals to work with the ModelForm has been stunningly frustrating me for over a week. models.py from django.db import models from datetime import date from django import forms from bootstrap_modal_forms.forms import BSModalForm JOURNAL_NAME_CHOICES = [ ('NEJM', 'New England Journal of Medicine'), ('JVS', 'Journal of Vascular Surgery'), ] # Create your models here. class JournalEntry(models.Model): name = models.CharField( null=False, choices=JOURNAL_NAME_CHOICES, max_length=256) renewal_date = models.DateField( verbose_name="Date of Renewal", auto_now=False, auto_now_add=False, blank=True, null=True, ) sub_cost … -
RuntimeError: Model class myapp.models.class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
This error has been addressed a lot of times but none of the answers seems to applied to me. I am fairly experienced with Python 2 and 3. I used django for the first time.I started making a project. As i was working with a basic DB and after i called the class.objects for the first time the title error occurred. After some time trying to fix it i moved to the django tutorial and i decided to do everything step by step. The error occured again specifically at "Writing your first Django app, part 3" right befor using render. Directories: \home_dir \lib \Scripts \src \.idea \pages \polls \migrations __init__.py admin.py apps.py models.py test.py views.py \templates \django_proj __init__.py asgi.py manage.py settings.py urls.py wsgi.py __init__.py db.sqlite3 manage.py Do not bother with pages it's a test app. django_proj\settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My App 'polls' 'pages' ] TEMPLATES and DATABASES are well configured polls\apps.py: from django.apps import AppConfig class PollsConfig(AppConfig): name = 'polls' polls\manage.py from django.db import models from django.utils import timezone import datetime # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) published_date = models.DateTimeField('date published') objects = models.Manager() def __str__(self): return self.question_text … -
AttributeError Django
Getting "Generic detail view ItemDetailView must be called with either an object pk or a slug in the URLconf". #models.py class Pic(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=100) caption = models.CharField(max_length=100) is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('picture:item-detail', kwargs={ 'pk2': self.pk}) def __str__(self): return self.caption #views.py class ItemDetailView(generic.DetailView): model = Pic template_name = 'picture/pic.html' #urls.py urlpatterns = { url(r'item/(?P<pk2>[0-9]+)/$', views.ItemDetailView.as_view(), name='item-detail'), } -
Can different Django apps serve the same URL for different MIME types?
I want a URL, say /users/fred, to serve different content based on the Accept header. If the requested MIME type is application/activity+json, I want to serve an ActivityPub representation of Fred's account; otherwise, I want to serve an HTML page. The twist is that I want to implement the ActivityPub view and the HTML view in different Django apps. If they were at different URLs, this would be easily done with urls.py, but that doesn't seem to allow filtering by Accept. Is there a standard way to do this? Do I need to implement something new in middleware? -
CSS Styling not being applied to parts of my html file
I'm using flask's {%extends%} tag to create an index HTML page, and extend styling from the base.html; however, the styling does not seem to be applying to certain parts of the page. I've used HTML and CSS before but this is the first time I am using it with flask as I am creating a python application. I am trying to style the bottom section of the page, but the styling does not apply. Here is my base.html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Taster Day Booking System</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet"> <link rel="shortcut icon" href="{{ url_for('static', filename='images/favicon.ico') }}"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default navbar-fixed-top topnav" role="navigation"> <div class="container topnav"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs- example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand topnav" href="{{ url_for('home.homepage') }}">Home</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> {% if current_user.is_authenticated %} {% if current_user.is_admin %} <li><a href="{{ url_for('home.admin_dashboard') }}">Dashboard</a></li> <li><a href="{{ url_for('admin.list_tasterdays') }}">Taster Days</a></li> <li><a href="{{ url_for('admin.list_courses') }}">Courses</a></li> <li><a href="{{ url_for('admin.list_students') }}">Students</a></li> {% else %} <li><a href="{{ url_for('home.dashboard') }}">Dashboard</a></li> {% endif %} <li><a href="{{ url_for('auth.logout') }}">Logout</a></li> <li><a><i class="fa fa-user"></i> Hi, {{ current_user.username }}!</a></li> {% … -
Docker Django NGINX Postgres build with scaling
I have worked mostly with monolithic web applications over the years and have not spent very much time looking at Django high-availability scaling solutions. There are plenty of NGINX/Postgres/Django/Docker builds on hub.docker.com but not one that I could find that would be a good starting point for a scalable Django web application. Ideally the Docker project would include: A web container configuration that easily allows adding new web containers to web app A database container configuration that easily allows adding new database shards Django microservice examples would also be a plus Unfortunately, I do not have very much experience with Kubernetes and Docker swarms. If there are none, I may make this my next github.com project. Thank you in advance. -
Model.clean() vs Model.clean_fields()
What is the difference between the Model.clean() method and the Model.clean_fields() method?. When should I use one or the other?. According to the Model.clean_fields() method documentation: This method will validate all fields on your model. The optional exclude argument lets you provide a list of field names to exclude from validation. It will raise a ValidationError if any fields fail validation. . . . So the Model.clean_fields() method is used to validate the fields of my model. According to the Model.clean() method documentation: This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field . . . But, this method should be used to make other validations, but among those, you can perform validations to different fields. And in the Django examples of the Model.clean() method, validations are made to fields: class Article(models.Model): ... def clean(self): # Don't allow draft entries to have a pub_date. if self.status == 'draft' and self.pub_date is not None: raise ValidationError(_('Draft entries may not have a publication date.')) # Set … -
Django - URL configuration
Here is something i wanna ask if i try this code i can go to login page but my url look like this http://127.0.0.1:8000/%2Flogin/. What is this %2F? urlpatterns = [ path("", views.index, name="index"), path("<str:slug>", views.redirect, name='redirect'), path('/login/', views.logIn, name='login')] And i remove slash from login url i get an error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000//login/ after removing slashes here is the code urlpatterns = [ path("", views.index, name="index"), path("<str:slug>", views.redirect, name='redirect'), path('login', views.logIn, name='login')] So, i wanna know is that why are the slashes affecting the url for login but not <str:slug> -
I am not getting any error but also not getting any blog, Problem with pagination
I am not getting any error with this code, but also not getting any result it is not showing any of my blog on-page. I think HTML code is misplaced. my pagination is not working properly before it throws an error of order then I ordered it by date and now it is not displaying anything and not throw any error which makes it's difficult to fix main.html <!DOCTYPE html> {% load static %} <link rel="shortcut icon" href="{% static 'img/favicon.png' %} "> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Advice Lancing</title> <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> --> <!-- Bootstrap Core CSS --> <link type="text/css" href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Theme CSS --> <link href="{% static 'css/clean-blog.min.css' %}" rel="stylesheet"> <!-- Custom Fonts --> <link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <style> img { border: 1px solid #ddd; /* Gray border */ border-radius: 10px; /* … -
How to query postgres RangeField using Hasura GraphQL
Python3 django==3.0.5 Hasura v1.1.1 postgres==11.3 I am trying to use Hasura filter on the IntegerRangeField() and DecimalRangeField(), but stuck at first one from django.contrib.postgres.fields import DecimalRangeField, IntegerRangeField from django.db import models class MyModel(modles.Model): age = IntegerRangeField() ... In browser I query with this payload query MyQuery { insurance_life_premium(where: {age: {_eq: "47"}}) { percentage_rate plan_id policy_term premium sum_insured } } It raises error { "errors": [ { "extensions": { "path": "$", "code": "data-exception" }, "message": "malformed range literal: \"47\"" } ] } I confirm that my database has valid data In [1]: Premium.objects.filter(age__contains=47) Out[1]: <QuerySet [<Premium: Premium object (1)>, <Premium: Premium object (60)>, <Premium: , <Premium: Premium object (878)>, '...(remaining elements truncated)...']> In terminal it mentions about parentheses hasura_1 | {"type":"http-log","timestamp":"2020-04-29T17:19:08.094+0000","level":"error","detail":{"operation":{"user_vars":{"x-hasura-role":"admin"},"error":{"path":"$","error":"malformed range literal: \"47\"","code":"data-exception"},"request_id":"aab2de87-1095-423e-9eb1-dae34926b226","response_size":78,"query":{"operationName":"MyQuery","query":"query MyQuery {\n insurance_life_premium(where: {age: {_eq: \"47\"}}) {\n percentage_rate\n plan_id\n policy_term\n premium\n sum_insured\n }\n}\n"}},"http_info":{"status":200,"http_version":"HTTP/1.1","url":"/v1/graphql","ip":"172.22.0.1","method":"POST","content_encoding":null}}} postgres_1 | 2020-04-29 17:19:08.095 UTC [34] ERROR: malformed range literal: "47" postgres_1 | 2020-04-29 17:19:08.095 UTC [34] DETAIL: Missing left parenthesis or bracket. postgres_1 | 2020-04-29 17:19:08.095 UTC [34] STATEMENT: SELECT coalesce(json_agg("root" ), '[]' ) AS "root" FROM (SELECT row_to_json((SELECT "_1_e" FROM (SELECT "_0_root.base"."percentage_rate" AS "percentage_rate", "_0_root.base"."plan_id" AS "plan_id", "_0_root.base"."policy_term" AS "policy_term", "_0_root.base"."premium" AS "premium", "_0_root.base"."sum_insured" AS "sum_insured" ) AS "_1_e" ) ) AS … -
how to filter list in Mysql in Django
class Student(): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) class group2020(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) biology=models.DecimalField(decimal_places=2,max_digits=1000) chemistry=models.DecimalField(decimal_places=2,max_digits=1000) class group2019(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) biology=models.DecimalField(decimal_places=2,max_digits=1000) chemistry=models.DecimalField(decimal_places=2,max_digits=1000) class group2018(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) biology=models.DecimalField(decimal_places=2,max_digits=1000) chemistry=models.DecimalField(decimal_places=2,max_digits=1000) If i added other classes that represents years 2020,2019,2018 of a group grades, i combined them in list and made calculations. math=[group2020.math,group2019.math,group2018.math] english=[group2020.english,group2019.english,group2018.english] chemistry=[group2020.chemistry,group2019.chemistry,group2018.chemistry] type_1=list(map(lambda n,m:n/m,math,english )) type_2=list(map(lambda n,a:n/a,chemistry,math )) How to filter the ready list based on type_1 > 2 and type_2 < 1 ? -
Pandas to_csv method's option quoting=csv.QUOTE_MINIMAL is NOT working
Pandas to_csv method's option quoting=csv.QUOTE_MINIMAL is NOT working. I have following input tab delimited data, In the following example -> denotes tab and . denotes space chars. Jhon->35->123.Vroom.St->01120 After using to_csv method and option quoting=csv.QUOTE_MINIMAL I am expecting following output. Jhon 35 "123 Vroom St" 01120 Which means quote only address values where there is space in the delimited data and do not quote if no space. df.to_csv(file, sep='\t', header=False, index=False, quoting=csv.QUOTE_MINIMAL) However, I am getting following output. There is no quote on the address. Jhon 35 123 Vroom St 01120 Using option quoting=csv.QUOTE_ALL getting me below which I don't want. "Jhon" "35" "123 Vroom St" "01120" Could someone please help me what's wrong here or this is a panda bug? Thanks. -
Why is not rendering the template
This is my create view I want to call each form one at a time. on getting to the second step organizer form after submitting the form, it does nothing instead of rendering the next form and html what I wanted to do is create venue_form, create organizer_form save it and populate them to event before saving event_form but event_form template is not rendering. What am I doing wrong. def create_event(request, step=None): venue_form = VenueForm() organizer_form = OrganizerForm() event_form = EventForm() ctx = { 'venue_form': venue_form, 'organizer_form': organizer_form, 'event_form': event_form, } if request.method == "POST": venue_form = VenueForm(request.POST) return render(request, 'event/organizer_form.html', ctx) if request.method == "POST": organizer_form = OrganizerForm(request.POST) return render(request, 'event/event_form.html', ctx) else: return render(request, 'event/venue_form.html', ctx) -
MultiSelectField On Django Admin Not Showing Values
I am seeing my list's key (permit_num and passport_num) instead of my values (Work Permit and Passport) on my Django admin. How do I fix this? For docs_good, it is showing "Yes" or "No". So it is good to me. Everything else is doing fine but only for this one. Perhaps because I use an external package? Here is my view.py: from django.db import models from multiselectfield import MultiSelectField class Case(models.Model): doc_choices = ( ('permit_num', 'Work Permit'), ('passport_num', 'Passport'), ) doc_listed = MultiSelectField("Documents Received?", choices=doc_choices, default=False) doc_good_choices = ( ('y', 'Yes'), ('n', 'No'), ) docs_good = models.CharField("Documents Good To Go?", max_length=264, choices=doc_good_choices,default=False) My admin.py script: class CaseAdmin(admin.ModelAdmin): model = Case list_display = ('doc_listed', 'docs_good') admin.site.register(Case, CaseAdmin) -
Accessing Moodle web service via django
Im trying to access moodle via moodle-ws-client package but im getting this error -
Django return redirect and Pop Up
under my views.py i have a def that will actually do some config into a device, i`m saving the output under a variable for the results and i would like to redirect to "home" when the request is done and at the same time create an html pop-up that will display the results. Expl: under views.py i have the follow code: def pstn_nanp_pri_ca(request): if request.method == "POST": result = [] selected_device_id = request.POST['device'] circuit_id = request.POST['circuit_id'] pri_channel = request.POST['pri_channel'] dev = get_object_or_404(Device, pk=selected_device_id) PSTN_slot = dev.PSTN_Slot # dev.ip_address dev.username, dev.password, dev.site_code try: ` ip_address = dev.ip_address # STATIC Username and Password username = dev.username password = dev.password # # Initiate SSH Connection to the router # ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ip_address, username=username, password=password) print("Successful connection", ip_address) remote_connection = ssh_client.invoke_shell() time.sleep(2) remote_connection.send("configure terminal\n") time.sleep(2) # # # PRI Config # # remote_connection.send("card type t1 0 " +str(PSTN_slot[2])+ "\n") remote_connection.send("isdn switch-type primary-ni\n") remote_connection.send("controller T1 " +str(PSTN_slot)+ "\n") remote_connection.send("Description ## PRI Circuit ID : " +str(circuit_id)+ " ###\n") remote_connection.send("framing esf\n") remote_connection.send("clock source line primary\n") remote_connection.send("linecode b8zs\n") remote_connection.send("cablelength long 0db\n") remote_connection.send("pri-group timeslots 1-" +str(pri_channel)+ "\n") time.sleep(2) remote_connection.send("voice-card 0/1\n") remote_connection.send("dsp services dspfarm\n") remote_connection.send("voice-card 0/4\n") remote_connection.send("dsp services dspfarm\n") remote_connection.send("interface Serial" +str(PSTN_slot)+":23\n") remote_connection.send("description ## PRI Circuit ID …