Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter with 'date' in Django
In model.py, I create class Order has a field 'order_date' with DateTimeField. In views.py, I user query: orders = Order.objects.filter(order_day__date__gte = date_from, order_date__date__lte = date_to). The Query doesn't return any data, although in the database, between date_from and date_to has many records. -
django inplaceedit on newer version of django
I'm currently running Django 1.11 on python 2.7. Is the current version of django-inplaceedit supported? I'm trying to use it for my apps. Thanks in advance. -
How to use IntegerRangeField in Django template
I'm using Django with PostgreSQL. I have a model with a IntegerRangeField. When using {{field}} in template the result is NumericRange(2, 8, '[)') How can I get the range numbers in my template? I tried {{ field.0 }} and {{ field.1 }} but got no output. -
Productionizing Docker On AWS With Django & Postgres:
I have been stumped as of late trying to figure out a cloud environment setup that can support my 'dockerized' Python Django project. The architecture of my application is simple; I have a web service, a redis service and a database service (see my compose yml file below). My confusion is finding the correct path of moving a local setup that is stood up via the docker compose yml file to a production like environment. I absolutely love the docker compose utility and hope to use a similar config file for my production environment; however, I am finding that most container based approaches are far more complex that this... This guide has been my favorite so far, but it doesn't dive into databases and other depended on components (which leaves out the necessary nitty gritty!). Questions: Should I move away from trying to use docker-compose on a production environment? Should I use a database that is not containerized? If I shouldn't, how do I configure the containerized web service to an Amazon RDS instance? Should I break apart my docker-compose.yml into individual docker files? Should I write script to start these containers to stand up the environment? Is there a … -
Not able to link a static web page using reverse_lazy
I have written some code to develop a social media site. In that, I wanted to redirect to homepage look-a-like which i have created. I tried to create a url for this page, but there is no use. I am getting the error like: NoReverseMatch at /accounts/signup/ Reverse for 'start' not found. 'start' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 1.11.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'start' not found. 'start' is not a valid view function or pattern name. In this project, there are three apps. Among them, "accounts" is one app. In accounts, I have created the templates folder with three files.("login.html,signup.html and start.html"). The views.py file for this : from django.contrib.auth import login, logout from django.core.urlresolvers import reverse_lazy from django.views.generic import CreateView from . import forms from django.views.generic import TemplateView class MyView(TemplateView): template_name = 'accounts/start.html' class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("start") template_name = "accounts/signup.html" And the urls.py file is: from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"login/$", auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), url(r"logout/$", auth_views.LogoutView.as_view(), name="logout"), url(r"signup/$", views.SignUp.as_view(), name="signup"), url(r"start/$", views.MyView.as_view(), name="start") ] How to redirect … -
Uploading files to django through ajax
I'm having trouble trying to upload files to django using ajax. The upload process is done in a modal. Form <div class="modal fade bs-example-modal-lg" id="fileUploadModal" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span> </button> <h4 class="modal-title" id="myModalLabel2">Upload File</h4> </div> <div class="modal-body"> <div class="modal-body"> {% crispy fileform %} </div> </div> </div> </div> </div> The modal toggle <a data-toggle="modal" href="#fileUploadModal" data-id="0" role="button" class="btn btn-success btn-sm pull-right"> <i class="fa fa-fw fa-cloud-upload"></i> Upload File </a> This is how my file upload looks like $(document).ready(function(){ var file = 0; $('#fileUploadModal').on('show.bs.modal', function(e) { file = $(e.relatedTarget).data('id'); var form = $(e.currentTarget).find('form'); $.ajax({ url: "{% url 'employee:ajax-file-upload' %}", type: "POST", data: $(form).serialize() + '&action=load&eid=' + employee + '&fid=' + file, success: function(data) { if (data['form_html']) { $(form).html(data['form_html']); $('.datepicker').datetimepicker({ format: 'YYYY-MM-DD' }); } } }); }); $(".container" ).on('click', '#submit-file-upload', function(e) { e.preventDefault(); e.stopImmediatePropagation(); var form = $(this).closest('form'); $.ajax({ url: "{% url 'employee:ajax-file-upload' %}", type: "POST", data: $(form).serialize() + '&eid=' + employee + '&fid=' + file, success: function(data) { if (!(data['success'])) { $(form).replaceWith(data['form_html']); $('.datepicker').datetimepicker({ format: 'YYYY-MM-DD' }); } else { location.reload(); } } }); }); }); And my view looks like this @json_view @login_required def ajax_file_upload(request): if request.method == 'POST': action = request.POST.get('action') … -
How to open and read file from request.FILES without saving it to disk
Is there a way to treat a file in request.FILES same as a disk file? I want to do something like this: with open(file_in_request, 'rb') as file: #read data from that file Only, I don't want to have to save it to disk first. I will be encrypting that file and save the encrypted file to disk instead. -
Java script is not working through Handlebar- Python Django
I am a django and python beginner. Django Application is hosted in apache webserver as daemon. I am facing the issue with rendering the URL in django using java script. In my handlebar(html template), i changed did html changes, but, unfortunately changes have not been reflected. Flow be like, When calling and URL from browser, my urls.py will call views.py, inside the views.py , Node_edit.html will be renderred. Node_edit.html will contains handlebar. Sorry for my poor english. views.py @csrf_protect def hierarchyNode_new(request, parentNode_id=None): parentNodeObject = None if(parentNode_id): context = { "parentNode_id": parentNode_id } return render(request, 'test/Node_edit.html', context) Node_edit.html {% load staticfiles %} var assetList = [ //applying the html template { url: '{% static "test/handlebar/Node.handlebar" %}', loadHandler: templateLoaderFunction, name: 'Node_edit' }, ] $(document).ready( function () { debug.log("load complete") registerHandlebarHelpers() // create templates hash if not already present Handlebars.templates = Handlebars.templates || {}; console.log(assetList); chainLoadAssets(assetList, function() { var hierarchyNodeEditor = new HierarchyNodeEditor( "{% url 'test:index' %}", "{% url 'test:Node_list' %}", {% if Node %} "{% url 'test:Node_jsonbase' %}", {% else %} "{% url 'test:Node_new' %}", {% endif %} "{{ Node.id }}", "{{ parentNode_id }}", "{{ csrf_token }}" ) NodeEditor.start() }) }) </script> Node.handlebar <div class="col-sm-7"> <input type="checkbox" id="Node_edit_display" checked="checked" (Trying to make … -
Python manage.py runserver fails. ImportError: module not found
Unhandled exception in thread started by <function wrapper at 0x1046deb18> Traceback (most recent call last): File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named profiles I keep getting this error No module named profiles and I'm not sure why. Profiles is defined in app.py: from __future__ import unicode_literals from django.apps import AppConfig class ProfilesConfig(AppConfig): name = 'profiles' and is called in urls.py from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.contrib import admin from profiles import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^one/', views.one, name='one'), url(r'^two/', views.two, name='two'), url(r'^three/', views.three, name='three'), url(r'^four/', views.four, name='four'), url(r'^five/', views.five, name='five'), ] Profiles is also added in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn and `./manage.py runserver`. See: # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development 'whitenoise.runserver_nostatic', … -
Swagger in Django rest function based api does not show properly on ubuntu server
Checkout my website swagger: http://railer.com/swagger/ (screnshot https://imgur.com/TnTNExa) I cannot get my swagger to display properly on ubuntu django setup. And I am using function based API just like here https://github.com/m-haziq/django-rest-swagger-docs This is the outcome which doesnt display swagger properly - ubuntu 16.04 (in AWS) https://imgur.com/TnTNExa <-- this is the problem, how to fix this ? But on my development environment mac pc https://imgur.com/E1Zst0E <--- its good on PC (Mac) Here is my swagger schema. As you can see I have some logging: https://gitlab.com/firdausmah/railerdotcom/blob/master/railercomapp/swagger_schema.py Here are some logging: 2017-11-30 06:06:57,367 DEBUG xxxx home hello 2017-11-30 06:07:25,131 DEBUG get(self, request) 2017-11-30 06:07:25,132 DEBUG Check and load if the function has __doc__ 2017-11-30 06:07:25,132 DEBUG swagger try yaml_doc 2017-11-30 06:07:25,134 DEBUG if yaml_doc My Django/NGINX/Ubuntu setup is based on this: https://jee-appy.blogspot.my/2017/01/deply-django-with-nginx.html Feel free to look through my code, https://gitlab.com/firdausmah/railerdotcom/tree/master what could be the problem with swagger? On development its working. There is nothing different how I setup development & production. On production its using nginx, gunicorn, supervisor. on PC its running on python manage.py runserver. -
ajax call in django with fild detect with js
i have a model class name(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) I have a view: def get(request): val=request.GET.get("username") print val response=name.objects.filter(story='{}'.format(val)) print response[0].rfc return HttpResponse(response) I have model form: class nameForm(ModelForm): class Meta: model = Manifest fields = "__all__" In template user have to drop down some choices in the first three fields name, project,story . Now i want to detect what user has droped down for the third field 'story'. So that i can make a ajax call with that value just user drop down on third field , to the function 'get' . How can i do it with ajax and js . Kindly help -
serving Django app by NGINX and uWSGI
My project "mysite" is all about creating a pdf file from a HTML document. Now i am facing problem while creating pdf file. Nginx working properly. Project is also loading properly in webbrowsers. My assumption is either uwsgi or nginx conf file is not proper. If its so please help me with some detailed answer. My project is working fine with django server. My uWSGI file and NGINX conf as shown below: server { listen 80; server_name mysite-uat.skysoft.com; charset utf-8; #forward all the request to HTTPS proxy_set_header X-Forwarded-Proto $scheme; if ( $http_x_forwarded_proto != 'https' ) { return 301 https://$host$request_uri; } location / { include uwsgi_params; uwsgi_read_timeout 300; include /var/www/html/mysite/uwsgi_params; uwsgi_pass unix:///tmp/mysite.sock; } access_log /var/log/nginx/mysite-access.log ; error_log /var/log/nginx/mysite-error.log; # Django media location /media { # your Django project's media files - amend as required alias /var/www/html/mysite/media; } location /static { # your Django project's static files - amend as required alias /var/www/html/mysite/static; } # static code has to reside in /home/project/project/static error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } My UWSGI file : [uwsgi] # path to where you put your … -
Django Pagination object is not persistent(Error: object of type 'NoneType' has no len())
# Views from gitdiff import operations from django.shortcuts import render, HttpResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger class Dashboard(operations.Operations): def render_dashboard(self, request): l_filters = [] # Adds configured filters from the config to a sorted list. for k in self.filters: l_filters.extend(k) l_filters.sort() repos = None # Condition to check if the filter is selected in GUI if "selected-filter" in request.POST: selected_filter = request.POST["selected-filter"] repos = selected_filter.split(" to ") # Removes the selected filter and adds in the end of list. l_filters.remove(selected_filter) # if selected, execute filterTool(.pl) self.get_filter_result(selected_filter=selected_filter, dev_repo = repos[0]) else: selected_filter = None # Paginator try: page = request.GET.get('page', 1) except ValueError: page = 1 print("Page is : {}".format(page)) # Retrieving end result from the DB db_res = self.get_dashboard_data(selected_filter) paginator = Paginator(db_res, 10) res = None try: res = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. res = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. res = paginator.page(paginator.num_pages) return render(request, 'dashboard.html', {'end_res': res, 'filters': l_filters, 'selected_value': selected_filter, 'repos': repos}) # In Template: <div class="pagination"> <span class="step-links"> {% if end_res.has_previous %} <a href="?page={{ end_res.previous_page_number }}" class="btn btn-xs btn-default">Previous </a> {% endif %} <span class="current">Page … -
How to link to other websites in my django?
I want to link my buttons to diffrent websites in my django website. <div class="container-fluid" style='margin-left:15px'> <p><a href="#" target="blank">Contact</a> | <a href="#" target="blank">LinkedIn</a> | <a href="#" target="blank">Twitter</a> | <a href="#" target="blank">Google+</a></p> </div> The above href only holds for the urls.py or only to the local pages of the project. -
Get User who owner a Content Object in Django
Helllo everyone, I have no solution to Get User who owner a Content Object in Django. So I post for your guys help! I'm building 2 models: Reaction and Notification. If user React, Notification will auto be created a object. This is my code: Model Reaction: class Reaction(models.Model): user = models.ForeignKey(User) react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='NO') timestamp = models.DateTimeField(auto_now_add=True, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') def save(self, force_insert=False, force_update=False, *args, **kwargs): Notification(from_user = self.user, to_user = ???, notification_type = Notification.LIKED, target_content_type = self.content_type, target_object_id = self.object_id).save() super(Reaction, self).save(*args, **kwargs) Models Notification class Notification(models.Model): from_user = models.ForeignKey(User, related_name='+') to_user = models.ForeignKey(User, related_name='+') date = models.DateTimeField(auto_now_add=True, null=True) is_read = models.BooleanField(default=False) target_content_type = models.ForeignKey(ContentType, related_name='notify_target', blank=True, null=True) target_object_id = models.PositiveIntegerField(null=True) target = GenericForeignKey('target_content_type', 'target_object_id') As you saw, I have problem with get to_user fields. This field I want to get User who owner a Content Object in Django Example: Post, Comment, ... Please help me with this case! -
Why is my Django template not loading?
I have the following code which seeks to pull a number "counter" out of a DB, add a value ("+1") to it, save the new "counter" value, wait for a specified amount of time, and then start again from the beginning. This same function would be called via a view on Django, so it is also responsible for generating the template as well. According to the development server, the function IS performing the simple arithmetic and saving the new value to the DB. As I can see the value being updated every time I refresh the Django-Admin. However, it fails to load the template. Specifically, the page stays loading indefinitely, while the calculations happen. Sorry if the code isn't perfect, I'm new to everything ever. Also, please note that I have previously tested the entire ecosystem with a much simpler index function (generates simple HTML) and the template indeed generates. So I'm assuming that the problem must come from this code specifically. Views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import Context, loader from home.models import DeathNum import datetime import time def index(request): while True: counter = DeathNum.objects.get(pk=1) counter.deaths += 1 counter.save() print('Added @ %s ' … -
Celery Beat unable to find database models (django.db.utils.OperationalError)
I have to add few periodic tasks. I'm using Celery - Redis in Django platform. When I execute the method from shell_plus all is well . However Celery Beat is unable to find the database instance properly. Celery version = 4.1.0. I had previously installed django-celery-beats etc Database = MySQL Where am i wrong. Thanks in advance. Celery Command (venv)$:/data/project/(sesh/dev)$ celery -A freightquotes worker -B -E -l INFO --autoscale=2,1 settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_BROKER_TRANSPORT = 'redis' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 604800} CELERY_RESULT_BACKEND = BROKER_URL CELERY_TASK_RESULT_EXPIRES = datetime.timedelta(days=1) # Take note of the CleanUp task in middleware/tasks.py CELERY_MAX_CACHED_RESULTS = 1000 CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERY_TRACK_STARTED = True CELERY_SEND_EVENTS = True CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] REDIS_CONNECT_RETRY = True REDIS_DB = 0 BROKER_POOL_LIMIT = 2 CELERYD_CONCURRENCY = 1 CELERYD_TASK_TIME_LIMIT = 600 CELERY_BEAT_SCHEDULE = { 'test': { 'task': 'loads.tasks.test', 'schedule': crontab(minute='*/1'), }, init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.base') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) loads/tasks.py @task() def test(): x = [i.id for i in Load.objects.all()] print (x) Error [2017-11-30 03:52:00,032: ERROR/ForkPoolWorker-2] Task loads.tasks.test[0020e4ae-5e52-49d8-863f-e51c2acfd7a7] raised unexpected: OperationalError('no such table: loads_load',) Traceback (most recent call last): File "/data/project/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line … -
`send_mail` method send email, the receive address did not received
I use the send_mail to send email to a list of email addresses, but it seems did not send to the addresses. My key code are bellow: from django.core.mail import send_mail result = send_mail(subject, message, from_email, to_email_list, fail_silently=False) print(result) # there prints `1` My email settings in settings.py is bellow: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.qq.com' # QQ:smtp.qq.com 163:smtp.163.com EMAIL_PORT = 465 EMAIL_HOST_USER = 'qiyunserveremail@qq.com' EMAIL_HOST_PASSWORD = 'qiyunserver_password' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and the traceback is bellow: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Subject: =?utf-8?b?5Li76aKY?= From: qiyunserveremail@qq.com To: lxt123@126.com Date: Thu, 30 Nov 2017 03:02:26 -0000 Message-ID: <20171130030226.15096.58930@aircraftdemacbook-pro.local> 内容 ------------------------------------------------------------------------------- 1 # this is the print(result) EDIT And I login my EMAIL_HOST_USER email, in the sent email section, there is no email there. -
Double underscore method for ordering the list returned by the view based on a field in another model not working
I'm trying to order the list the view returns based on a field in another model. I read the documentation over here and it says I could do that by using the model's name followed by double underscore followed by the field in the model. But that for some reason is not working. I tried another method, as mentioned below. View class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' ordering = ['choice'] Model class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Meta: ordering = ['-votes'] The above method works but the below one does not, can someone kindly point me why. View class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def get_queryset(self): """Return the choices in the order of votes""" return Question.objects.order_by('-choice__votes') Model class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Even tried replacing def get_queryset() with ordering = ['-choice__votes'] didn't work either. -
Not able to get url parameter while unit testing Django's rest api using APIRequestFactory
I have created a rest api using Django's rest_framework. It's created using class based view. views.py import logging from rest_framework.views import APIView from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication from rest_framework.response import Response from handlers.product import get_data log = logging.getLogger(__name__) class ProductView(APIView): authentication_classes = (TokenAuthentication, BasicAuthentication, SessionAuthentication) def get(self, request, **kwargs): try: product_id = kwargs['product_id'] response = get_data(product_id) return Response(response) except KeyError as key: log.exception(key) return Response({'error_msg': '{} is required'.format(key)}, status=400) urls.py url(r'^product/(?P<product_id>[0-9]+)/data/$', ProductView.as_view(), name='product'), And this is what I have tried, import pytest from django.contrib.auth.models import User from mixer.backend.django import mixer from rest_framework.authtoken.models import Token from rest_framework.test import APIRequestFactory from views import * pytestmark = pytest.mark.django_db @pytest.fixture() def token(): user = mixer.blend(User) return Token.objects.create(user=user) class TestProductView: def test_get_data(self, token): factory = APIRequestFactory() request = factory.get('/product/100230/data/', HTTP_AUTHORIZATION='Token {}'.format(token)) response = ProductView.as_view()(request) assert response.status_code == 200 My test fails because I get an exception, KeyError: 'product_id' But when I run my app and request the api from browser it takes the product_id from the url. Please note that I really have to use kwargs in get api method because later I want to make get_data generic and pass all the url params and query params to it. -
odd Django behavior with multiple forms
I have a Django app with 1 views.py and 1 forms.py file, however within these they had distinct forms. The forms sometime call functions of other scripts which log data using logging module. Recently I've noticed that script 1 is writing data to script 2's log instead of its own. The code is solid and this wasn't an issue before. My only theory is the same person is submitting 2 different forms using multiple tabs/same session in the same browser. How can I prevent this? or at least prevent the data cross over -
Multiple validators for Django 1.11 Model CharField
Does anyone know if it is possible to apply multiple validators to a Django 1.11 Model CharField? I am trying to enforce formatting of the field as either: "Use format XX XXXX XXXX" or "Use format XXXX XXX XXX" prefphone = models.CharField(max_length=255,null=True,blank=True,validators=[RegexValidator(r'^[0-9]{2} [0-9]{4} [0-9]{4}$', "Use format XX XXXX XXXX"),RegexValidator(r'^[0-9]{4} [0-9]{3} [0-9]{3}$', "Use format XXXX XXX XXX")]) The first validation is failing and the second validation is not tested. If there are alternative methods to achieve my outcome I would be grateful to hear them. Thanks! -
handle two difference action, add and save
I have a form where user can add multiple items which will be shown in table and then if user hits the save button, all those items will be saved to database but I have no idea on how should i do this. Can anyone give me an idea, please? This is the form I have to process In screenshot, there is one add button which will add in the below table and then there is save button which will post to the database. I have only created a model and forms for now class OpeningStock(models.Model): office = models.ForeignKey(OfficeSetup, blank=True, null=True, on_delete=models.CASCADE) miti = models.DateTimeField(null=True) item_group = models.ForeignKey(ItemGroup, blank=True, null=True) item = models.ForeignKey(Item, blank=True, null=True) department = models.ForeignKey(DepartmentSetup, blank=True, null=True) employee = models.ForeignKey(Employee, blank=True, null=True) quantity = models.PositiveIntegerField(default=0) value = models.DecimalField(default=0.0, max_digits=100, decimal_places=2) specification = models.CharField(blank=True, null=True, max_length=600) remarks = models.TextField(blank=True, null=True) def stock(request): form = StockForm(request.POST or None) if request.method == "POST" and form.is_valid(): office_instance = OfficeSetup.objects.get(user=request.user) new_form = form.save(commit=False) new_form.office = office_instance new_form.save() messages.success(request, 'Thank you') return redirect('stock') messages.warning(request, "Correct the errors below") stocks = OpeningStock.objects.all() context = { "form": form, "stocks": stocks } return render(request, 'dashboard/stocks/stock.html', context) {% block content %} <div class="right_col" role="main"> <h1 class="text-center">Stock</h1> <div … -
Deleting 'models.py' from Django app
Inside a project I'm implementing using Django framework, I have two applications: Application responsible for REST API, containing production models.py file. Application responsible for Web client, that uses REST API's models. Both of them contain vast static files and hierarchy of additional source code, that is why it came to my mind to split this responsibilities into two apps, rather than different views.py and urls.py files inside one application. Because application responsible for Web relies entirely on REST API's models is it a good practice to delete models.py file from this application entirely? -
django 1.11 app can't find style.css in static/app/style.css dir
my app dir: my base.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'sns/style.css' %}" /> style.css content: li a { color: green; } for some reason, I get a 404 when it tries to load style.css page source: Not sure what im missing?