Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not recognize UUID Foreign Key
I had this current model: class Apps(models.Model): """ Apps são os aplicativos que terão financeiro gerido, uma empresa/usuario pode ter multiplos apps conectados """ app_code = models.UUIDField(auto_created=True, default=uuid.uuid4, unique=True, primary_key=True) chave_app = models.UUIDField(auto_created=True, default=uuid.uuid4, unique=True) usuario = models.ForeignKey(Usuario, on_delete=models.CASCADE) descricao = models.CharField(max_length=100) The usuario field is an ForeignKey... The usuario model is this: class Usuario(AbstractBaseUser): """ Classe que ira gerir o cliente final, cadastrado via APP ou Webapp """ user_id = models.UUIDField(auto_created=True, default=uuid.uuid4, unique=True, primary_key=True) nome = models.CharField(max_length=120) celular = models.CharField(max_length=20, unique=False) email = models.EmailField(max_length=100, unique=True) ativo = models.BooleanField(default=True) chave_api = models.UUIDField(auto_created=True, default=uuid.uuid4, unique=True) created_at = models.DateTimeField(auto_now_add=True) objects = AccountManager() USERNAME_FIELD = 'chave_api' REQUIRED_FIELDS = ['email', 'nome', 'celular'] class Meta: ordering = ('-created_at',) All works nice, but when i try to list apps on django-rest-framework as list. I did same way on anothers models, with no foreign key, and listing is all ok. The error is giving only on this view with Foreign Key. TypeError at /apps/ str returned non-string (type UUID) At database, my fields was inserted with this values: [ { "app_code": "423676e9968d41beaeeeb2da43fc56d8", "chave_app": "86c18ae7809e4bda88830090f309a00c", "descricao": "Matrix Cashback 2.0", "usuario_id": "998339b46bde40bca053978670626a6f" } ] I'm using Django-rest-framework and Django in an personal project. Don't know what to do now, … -
How to order related field by its foreign key fields?
Let's assume I have three model like below; class Stats(models.Model): gp = models.IntegerField(default=0) won = models.IntegerField(default=0) drawn = models.IntegerField(default=0) lose = models.IntegerField(default=0) gf = models.IntegerField(default=0) ga = models.IntegerField(default=0) gd = models.IntegerField(default=0) pts = models.IntegerField(default=0) class Team(models.Model): team_name = models.CharField(max_length=50) stats = models.ForeignKey(Stats) class Group(models.Model): group_name = models.CharField(max_length=1) teams = models.ManyToManyField(Team) And, this is my serializer for Group Model class GroupSerializer(serializers.ModelSerializer): teams = TeamSerializer(read_only=True, many=True) class Meta: model = Group fields = '__all__' However, I want to order the teams according to pts and gd fields of their stats. I tried to add order_with_respect_to='stats' to the Team model and ordering = ['pts', 'gd'] to the Stats Model but it did not work. -
Page not found (404) Password reset link (local test)
I have set up the build in password reset in django. It's working until I am going to paste the reset link that I got in the email. When I paste it i get this 404 error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/registration/reset/Nw/4o1-b6d03123dbdd2fb0eab5/ Raised by: taskoftheday.views.taskoftheday I have the password reset code in an app called registration. But I get the error raised by an app I also have called taskoftheday. What is wrong? -
error: Requested setting INSTALL ED_APPS, but settings are not configured.
I installed Django and made a project called joseph. This is all I've done thus far. I can't access it at all, however, because I can only access the core commands. I get this message when I put it django-admin help: Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALL ED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). I have looked for an answer but all of the other ones seem to be about scenarios not like mine because they already have been able to do things. I haven't been at all. What am I supposed to do here? Thanks. -
Why doesn't psql like loading into django's ArrayField?
my models.py contains class CardioPattern(models.Model): schedule = ArrayField(ArrayField(models.IntegerField()),null=True,blank=True) i then have a command that initializes some tables, including these lines: cp = CardioPattern(name=cp) ... import pdb; pdb.set_trace() cp.schedule = csched cp.save() when the command is run via python manage.py initCmd: it throws the following exception, arising from the cp.save() attempt: Traceback (most recent call last): File "/home/rik/lib/python3.5/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: ARRAY could not convert type text[] to integer[] LINE 1: ...265, 265, 265, NULL], ARRAY[264, 264, 264, NULL], ARRAY[NULL... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/rik/lib/python3.5/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/rik/lib/python3.5/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rik/lib/python3.5/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/rik/lib/python3.5/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/rik/webapps/django10/fitAlchem/moveGen/management/commands/initMove.py", line 207, in handle cp.save() File "/home/rik/lib/python3.5/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/home/rik/lib/python3.5/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/rik/lib/python3.5/django/db/models/base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/rik/lib/python3.5/django/db/models/base.py", line 947, in _do_insert using=using, raw=raw) File "/home/rik/lib/python3.5/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File … -
Django `loaddata` pretty way to load same objects with different pk (id)
I use loaddata to load my fixtures (Django doc.) For example i have this example.json: [ { "model": "foo.bar", "pk": 1, "fields": { "name": "dmytryi" } }, { "model": "foo.bar", "pk": 2, "fields": { "name": "dmytryi" } }, ... (repeat it until pk is not 10 with increasing pk by one) { "model": "foo.bar", "pk": 10, "fields": { "name": "dmytryi" } }, ] How you see, I have 10 same objects (same name for same model), but with different pk value. After loaddata I will see in my database 10 objects. It is OK. Give a hint how to reduce the code, but leave the same result, if it exists. Thanks you! -
how to show all post with relatedid in django?
hey guys i have trouble in display all post with same relatedid and related id comes from qna and i want to show all relatedid post to qna_post.html please help to fix it in django 1.11 python3 urls.py from django.conf.urls import url, include from django.views.generic import ListView, DetailView from qna.models import Post urlpatterns = [ url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="qna.html")), url(r'^(?P<pk>\d+)$', DetailView.as_view(model = Post, template_name= 'qna_post.html')) ] qna_post.html {% extends "header.html" %} {% block content %} {% for post in object_list %} {% url page_item item.id %} {% if post.relatedid == post.id %} {% if post.PostType == 'q' %} <h3>{{ post.Title }}</h3> <h6>on {{ post.date }}</h6> {{post.Body|safe|linebreaks}} {% endif %} {% if post.PostType == 'a' %} <h3>{{ post.Title }}</h3> <h6>on {{ post.date }}</h6> {{post.Body|safe|linebreaks}} {% endif %} {% endif %} {% endfor %} {% endblock %} qna.html {% extends "header.html" %} {% block content %} {% for post in object_list %} {% if post.PostType == 'q' %} <h5>{{ post.date|date:"Y-m-d" }}<a href="/questions/{{ post.id }}"> {{ post.Title }}</a> -<label> {{ post.Body|slice:":8" }}...</label></h5> {% endif %} {% endfor %} {% endblock %} -
DATA_UPLOAD_MAX_MEMORY_SIZE not working?
For testing purpose, I set the DATA_UPLOAD_MAX_MEMORY_SIZE = 2 #bytes and then try to upload an image (18mb) and it fails with below message: Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. which is good. But then I change the value to 10mb DATA_UPLOAD_MAX_MEMORY_SIZE = 10485760 #bytes and that same image successfully gets uploaded. Am I missing something here? Django version is 1.10. I'm uploading images thru Jquery Ajax (XMLHttpRequest) and on the upload view I have @csrf_exempt decorator. -
django fbv ajax with pagination
I'm trying create a CRUD using Ajax with pagination, but when I try add a new book, i get the exception empty in foreach of books, but when I refresh the page it works and show the new register. views.py: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def livro(request): livros = Livro.objects.all().order_by('-id') paginator = Paginator(livros, 5) page = request.GET.get('page', 1) try: registers = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. registers = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. registers = paginator.page(paginator.num_pages) return render(request, 'livros.html', {'registers': registers}) def salvar_form_livro(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True #import pdb; pdb.set_trace() livros = Livro.objects.all().order_by('-id') data['html_book_list'] = render_to_string('listaLivros.html', { 'livros': livros }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def criarLivro(request): if request.method == 'POST': form = LivroForm(request.POST) else: form = LivroForm() return salvar_form_livro(request, form, 'cadastraLivro.html') template.html {% for livro in registers %} <tr> <td>{{ livro.id }}</td> <td>{{ livro.titulo }}</td> <td>{{ livro.autor }}</td> <td>{{ livro.get_tipoLivro_display }}</td> <td>{{ livro.dataPublicacao }}</td> <td>{{ livro.paginas }}</td> <td>{{ livro.preco }}</td> <td> <button type="button" class="btn btn-warning btn-sm js-update-book" … -
Is it possible to delegate celery tasks and block until all is processed?
I have this task: @app.task(name='somesmalltask') def some_small_task(some_input): some_list = [] #do something to some_list return some_list Is it possible to do something like: all_results = map(lambda x: some_small_task.delay(x), inputs) #do stuff later to all_results but instead of returning the celery task, I would like to actually get the result. Would I have to do something like this for every task id? result = some_small_task.AsyncResult(task_id) result.get() -
Send PIL Image from Django View to Browser for Download via HttpResponse
I'm trying to send a PIL image from a Django view to the browser for automatic download. The code below seems to work for many: response = HttpResponse(content_type='image/jpg') PIL_imageToSend.save(response, "JPEG") response['Content-Disposition'] = 'attachment; filename="name.jpg"' return response I call the Django view through Ajax, and when I print the callback I get what looks to be the JPEG image, but no download is triggered. Am I missing something to get the download to automatically trigger? -
Class has no atribute 'urls' - Django models.ImageField() can't migrate
I try to add ImageField but I get error. Code I am working with: #models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.core.exceptions import ValidationError import datetime class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) verified = models.BooleanField(default=False) status = models.CharField(max_length=200, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) province = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) class ProfileImages(models.Model): profile = models.ForeignKey(Profile, related_name='images') image = models.ImageField() #admin.py from django.contrib import admin from .models import * class ProfileImagesInline(admin.TabularInline): model = ProfileImages extra = 3 class ProfileAdmin(admin.ModelAdmin): inlines = [ ProfileImagesInline, ] admin.site.register(Profile, ProfileImages) This throws: 'Attribute Error' ProfileImages has no attrbute 'urls'. I don't know why. Any ideas? -
Django form not updating existing record even when instance is passed
I have a form that is used to create and edit a model instance. But when editing the model instance, the form still tries to create a new record and fails because the unique together fields already exist. I am already passing the instance when initializing the form. views.py def organization_course_detail(request, org_id): ''' Get all courses that are associated with an organization ''' template_name = 'users/organization-course-list.html' organization = models.Organization.objects.get(id=org_id) if request.method == 'POST': print organization.id form = forms.CreateOrganizationForm(request.POST, instance=organization) if form.is_valid(): print 'form is valid' org = form.save(commit=False) org.save() return HttpResponseRedirect( reverse('users:org-course-list', kwargs={'org_id': org_id})) else: form = forms.CreateOrganizationForm(instance=organization) forms.py class CreateOrganizationForm(forms.ModelForm): ''' A form used to create a new organization. At the same time, we create a new course that is a clone of "Chalk Talk SAT" and associate the course with the organization and any student that signs up from that organization ''' class Meta: model = models.Organization fields = ['name', 'country', 'acronym',] models.py class Organization(models.Model): ''' This is a model where we will have every institution (test prep centers, governments, schools) that we do workshops at or create school accounts for ''' name = models.CharField(max_length=2000) country = CountryField(null=True, blank='(Select Country)') date = models.DateTimeField(default=timezone.now) acronym = models.CharField(max_length=7, help_text="(Up to … -
Link Facebook messenger sender id with Facebooks fbid
I have a django app that allows users to login using facebook and it also allows used to communicate with the app using facebook messenger. Now the users id for logging in and messenger are different. I want to be able to link the two together. I've found this doc which should connect the two accounts but I keep getting errors https://developers.facebook.com/docs/messenger-platform/connecting-accounts I'm using GET /{user-id} ?fields=name,is_payment_enabled,ids_for_apps,ids_for_pages &access_token=[page_access_token] &appsecret_proof=[appsecrete_proof] but keep getting the error {u'error': {u'message': u"Unsupported get request. Object with ID '1569748269763653' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api", u'code': 100, u'type': u'GraphMethodException', u'fbtrace_id': u'BEurWnDCwuu'}} Any idea what I am doing wrong? Thanks -
How to use jQuery datetimepicker plugin with Django
I'm a beginner with Django, working on my first project. For the main functionallity of the site I need to use a datetimepicker. Since it's impossible to use Bootstrap (incompatible with Django 1.11) it looks that the only(?) option which I could handle is this one: jquery datetimepicker plugin. I tried to configure it, but unfortunately I see no result at my site. My code: Forms.py time_from = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class': 'datetimepicker'})) Template - base.html I put jQuery and jQueryUI into static directory, add path to them into head section and {% load static %} between html tag and head. At the and of the file I have links to the datetimepicker. <html> {% load static %} <head> <meta charset="utf-8"> <title>placyk</title> <meta name="viewport" content="width-device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script type="text/javascript" src="{{ STATIC_URL }} /static/js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="{{ STATIC_URL }} /static/js/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script> </head> <body> {% block content %} <p>Nothing</p> {% endblock %} </body> <link rel="stylesheet" type="text/css" href="/static/datetimepicker-master/jquery.datetimepicker.css"/> <script src="/static/datetimepicker-master/jquery.js"></script> <script src="/static/datetimepicker-master/build/jquery.datetimepicker.full.min.js"></script> </html> Template - specific for the view, extends base.html <html> {% extends 'base.html' %} <script> $(document).ready(function() { $('.datetimepicker').datetimepicker(); }); </script> {% block title %}<title>Dodaj wizytę</title>{% endblock %} {% block content %} <form … -
Django filter all that has certain names
I have a problem very similar to Django filter queryset __in for *every* item in list I need to select all prospects that have certain certifications as defined by class Prospect(models.Model): certification = models.ManyToManyField(Certification, blank=True, related_name="certification_prospects") class Certification(models.Model): name = models.CharField(max_length=200, null=True, blank=True) For example, if I have certifications ['CPA', 'PhD'] I want all prospects that have exactly CPA & PhD, if they have more or less than those two, I want to exclude them. I'm using this solution, as give by the link earlier def searchForProspectByCertifications(prospects, certifications): prospects = prospects.filter(certification__in=certifications).annotate(num_certifications=Count('certification')).filter(num_certifications=len(certifications)) return prospects But I'm receiving an error of ValueError: invalid literal for int() with base 10: 'CPA' -
Django variable not visible in header section
I have a basic start to a blog, it lists out blog articles from the database in post_list.html that extends from header.html. I am trying also to get a variable in the header as a slogan but this is not working. header.html - this renders without the "propaganda.slogan" which is entered from the admin pages and has content: <!DOCTYPE html> <html lang="en"> <head> <title>hey!</title> <meta charset="utf-8" /> {% load staticfiles %} <link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/> </head> <body> <section class="hero is-success is-bold"> <div class="hero-body"> <div class="container"> {% block slogan %} <ul> {% for propaganda in propagandas %} <li>{{ propaganda.slogan }}</li> {% endfor %} </ul> {% endblock %} <h1 class="title"> My weblog </h1> </div> </div> </section> {% block content %} {% endblock %} </body> </html> post_list.html extends header.html and displays a list of posts from models.py: {% extends "blog/header.html" %} {% block content %} {% for post in posts %} <section class="section"> <div class="container"> <h1 class="title"><a href="#">{{ post.title }}</a></h1> <p>{{ post.summary|linebreaksbr }}</p> <p>published: {{ post.last_edited }}</p> </div> </section> {% endfor %} {% endblock %} models.py looks like this: from django.db import models from django.utils import timezone # Create your models here. class Propaganda(models.Model): slogan = models.CharField(max_length=140, blank=True, null=True) def … -
Django template label_suffix
I am trying to extract the suffix in Django template. I have tried: {{ field.label_suffix }} {{ field.label_tag.label_suffix }} Nothing seems to work. Is there a way to extract the suffix in the template? -
Post query to API in Django REST
I have code in Angular 2: sendPost(){ let headers = new Headers(); headers.append('Content-Type', 'application/json'); let requestOptions = new RequestOptions({headers: headers}); requestOptions.headers = headers; let data = { "name": "XX", "email": "xxx@op.com", "phone_number": "+99999995555", "address": "YYY", "code": "80-885", "city": "YHYY", "voivodeship": "ZZZZ", "description": "VVVVV" }; this.http.post(`http://127.0.0.1:8000/companies/create`, data, requestOptions).subscribe(res => { console.log(res.json()); }, (err) => { console.log(err); }); } Error API: <WSGIRequest: OPTIONS '/companies/create'> Internal Server Error: /companies/create Traceback (most recent call last): File "C:XX\CRM\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:XX\CRM\env\lib\site-packages\django\core\handlers\base.py", line 198, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view my_crm.views.companies_create didn't return an HttpResponse object. It returned None instead. [25/Jul/2017 21:32:35] "OPTIONS /companies/create HTTP/1.1" 500 59515 The API shows that there is an error somewhere in the function but when I use POSTMAN this is identical JSON goes through with no problem. Where can be the error? I think the API is well handled when testing using POSTMAN. -
Django REST Angular $http 403 Status
So I have a very simple API endpoint that is supposed to determine if a user is logged in. I did decide to make it a POST request for the sake of hiding the response from being accessed in the browser class Check(APIView): def post(self, request): print request.user if request.user.is_authenticated(): # a successful response for logged in return Response(status = HTTP_200_OK) # return an error status code for not logged in return Response(status = HTTP_401_UNAUTHORIZED) When logged out, I get AnonymousUser in the console and a 401 status code as expected. However when logged in as a superuser or any other user, I get no print output and a 403 status code. This indicates that for some reason the entire callback is never entered. I've been told that it is an issue of permissions but I have AllowAny enabled. Do you guys have any ideas? REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer' ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } -
What is a good way to push notifications from the server in django?
I was wondering what could be a good way to push notifications of changes from the server in a django app. For example, let's say I have a model called "Transaction". I have several tabs (or even browsers) open, showing a list of "Transactions" objects, and I add a new transaction to the database. I'd like all the tabs to update their content to reflect the change. I can keep an history and poll regularly, but this doesn't scale well for sure. I've read some answer to similar questions on stackoverflow, but they are 6-7 years old, so I was wondering if there were developments on this side. Specifically, I'd like to know: What is the state of the art method to deal with server notifications Is it a good or a bad idea to use a client-side solution like intercom.js and why? I've (quickly) read about websockets, long polling, html5 server-sent events, but I find a little confusing understanding pros/cons and in general understand the related challenges and solutions. Any tips or source where to start? Any suggestions about modules/libraries for a quick implementation? Thanks in advance -
How to save checked checkboxes in a CheckboxSelectMultiple field in an edit form in Django
I made a form for a model, and now I want to create an update form for that model, but I'm having trouble with the CheckboxSelectMultiple field. Here is my code: choices.py FREQUENCY_CHOICES = (('sunday', 'Sunday'), ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday'), ('thursday', 'Thursday'), ('friday', 'Friday'), ('saturday', 'Saturday')) models.py class Schedules(models.Model): course_name = models.ForeignKey(Course) location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield') room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A') start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today) start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am') end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am') instructor = models.ForeignKey(Instructor) total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six') # Relevant code here frequency = models.CharField(max_length=128) status = models.CharField(max_length=128, choices=STATUS_CHOICES) interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day') initiated_by = models.CharField(max_length=128, null=True) schedule_id = models.IntegerField(default=0) forms.py class ScheduleForm(forms.ModelForm): course_name = CourseChoiceField(queryset=Course.objects.filter(status=True), label="Course Name", widget=forms.Select(attrs={'class': 'form-control'})) location = forms.ChoiceField(choices=LOCATION_CHOICES, initial='south_plainfield', label="Location", widget=forms.Select(attrs={'class': 'form-control'})) room = forms.ChoiceField(choices=ROOM_CHOICES, initial='A', label="Room", widget=forms.Select(attrs={'class': 'form-control'})) start_date = forms.DateField(input_formats=['%m/%d/%Y'], label="Start Date", widget=DateInput(format='%m/%d/%Y'), help_text="MM/DD/YYYY") start_time = forms.ChoiceField(choices=START_TIME_CHOICES, initial='eight-thirty am', label="Start Time", widget=forms.Select(attrs={'class': 'form-control'})) interval = forms.ChoiceField(choices=INTERVAL_CHOICES, initial='1 day', label="Interval", widget=forms.Select(attrs={'class': 'form-control'})) # hours_per_class = forms.ChoiceField(choices=HOURS_PER_CLASS_CHOICES, initial='four_and_half', label="Hours Per Class", widget=forms.Select(attrs={'class': 'form-control'})) total_hours = forms.ChoiceField(choices=TOTAL_HOURS_CHOICES, initial='six', label="Total Hours", widget=forms.Select(attrs={'class': 'form-control'})) instructor = InstructorChoiceField(queryset=Instructor.objects.all(), label="Instructor", widget=forms.Select(attrs={'class': 'form-control'})) end_time = forms.ChoiceField(choices=END_TIME_CHOICES, initial='eight-thirty am', label="End Time", widget=forms.Select(attrs={'class': 'form-control'})) # Relevant code here frequency = … -
how to run .py script with user input as parameters
I have a .py file, say 'car.py'. It takes 3 inputs (color, make, year). It takes the user input and reads a file, then it returns all matching instances of the color, make, and year given in the input. This script runs fine. Now, I would like to create a web page that works like a search page. It asks for 3 inputs, searches the file (locally) and returns the results. I am using Django for the first time and I am having difficulty figuring out how to call the car.py file and have it run on the background before it returns the result. I have an html interface made but I know I cant ref a python script in it. Is there anything similar in Django? Where I can reference a script and when a button is pressed, it'd run that script given the user input? I don't expect a full coded response, I just want a clarification or reference to an answer. I haven't been able to find anything similar online. -
VS2017 Django Web Project build fails without bin folder
I have created a Django Web Project in Visual Studio 2017 and i have tried serving static files from a directory defined in STATICFILES_DIRS in settings.py. settings.py: STATICFILES_DIRS = ( os.path.join( BASE_DIR, 'static', ), ) Once i had this in settings.py my project didn't build anymore. After quite some time battling with the IDE (i had no errors, it just failed to build and it gave no reason why) i figured out that if i copy the bin folder from a hobby project i made some time ago with PTVS and VS 2015, my project builds fine. And I have absolutely no idea why. The contents of the bin folder are two files: Microsoft.PythonTools.WebRole.dll and wfastcgi.py. I don't have the PC with VS 2015 anymore so i can't check my IDE settings there and i am pretty sure i didn't make any changes nor have i had trouble with settings.py or serving static files in that project. Can anyone explain why this could be happening? Why is VS 2017 not creating a bin folder but VS 2015 did. Is there something i am missing? Using: VS2017 Professional with Python development installed with VS installer - pretty much default settings -
Django 'next' redirect for log in and new user
I have an e-commerce website where users can view ads without logging in. However when they want to post an ad they are re-directed to the login page, where after successful login they are directed to the 'create ad' page. This functionality is working fine. The problem is when user is re-directed to log in page, and she clicks on 'new user' and creates an account, she is not redirected to the 'create ad' page after successful account creation. My code looks like this so far: login.html: #login form <form method="post" action="{% url 'login' %}"> {% csrf_token %} {% if request.GET.next %} <input type="hidden" name="next" value={{ request.GET.next }} /> {% endif %} <b>Name:</b> {{ form.username }} <b>Password:</b> {{ form.password }} <input type="submit" value="OK"> </form> # button to redirect to new account creation page <a href="{% url 'unauth_home_new' %}#section0"><button>New Account</button></a> </div> views.py: def login(request, lang=None, *args,**kwargs): if request.user.is_authenticated(): if 'next' in request.POST: return redirect(request.POST['next']) return redirect("home") else: if request.method == 'POST': if lang == 'ur': return log_me_in(request=request,template_name='login_ur.html') else: return log_me_in(request=request,template_name='login.html') else: if lang == 'ur': return log_me_in(request=request,template_name='login_ur.html') else: return log_me_in(request=request,template_name='login.html')