Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do I need to install the PostgresSql in Project directory for it to work with psycopg2?
I am trying to make migrations to my newly created PostgresSql database when I run python manage.py makemigrations it gives me the following error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: role "<MYNAME>" does not exist the here is my windows username I think it is maybe because I have installed PostgresSQl in the C: directory. I had to use psql --username=postgres in CMD to get into the database and make new user with a superuser role. Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_DB_NAME'), 'USER': os.environ.get('POSTGRES_DB_ADMIN'), 'PASSWORD': os.environ.get('POSTGRES_DB_PASS'), 'HOST': 'localhost', 'PORT': '5432' } } Any help with this would be appreciated. -
I need to join two lists that have similar values in another third list with the different fields
I have in my Models the following codes: class Meta(models.Model): conta = models.ForeignKey(Conta, on_delete=models.CASCADE) ccusto = models.ForeignKey(Ccusto, on_delete=models.CASCADE) data = models.DateField() valor_meta = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self): return '%s %s %s %s %s' % (self.conta, ':',self.data.strftime("%d %m %Y"),':',self.ccusto) class Despesa(models.Model): conta = models.ForeignKey(Conta, on_delete=models.CASCADE) ccusto = models.ForeignKey(Ccusto, on_delete=models.CASCADE) data = models.DateField() valor_despesa = models.DecimalField(max_digits=8, decimal_places=2) chave = models.CharField(max_length=100) def __str__(self): return str(self.id) And in my Views, the following codes: mes = request.POST['selectmes'] lista = Despesa.objects.filter(data__month=mes).values('conta__conta_nome','ccusto__ccusto_nome').order_by('conta__conta_nome').annotate(sum_despesa=Sum('valor_despesa')) lista2 = Meta.objects.filter(data__month=mes).values('conta__conta_nome','ccusto__ccusto_nome').order_by('conta__conta_nome').annotate(sum_meta=Sum('valor_meta')) That generate two lists like this: conta_nome|ccusto|valor_despesa and conta_nome|ccusto|valor_meta But I need this: conta_nome|ccusto|valor_despesa|valor_meta How I do this? -
How do I write a Django query with a subquery as part fo the WHERE clause?
I'm using Django and Python 3.7. I'm having trouble figuring out how to write a Django query where there's a subquery as part of a where clause. Here's the models ... class Article(models.Model): objects = ArticleManager() title = models.TextField(default='', null=False) class ArticleStat(models.Model): objects = ArticleStatManager() article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats') elapsed_time_in_seconds = models.IntegerField(default=0, null=False) votes = models.FloatField(default=0, null=False) class StatByHour(models.Model): index = models.FloatField(default=0) # this tracks the hour when the article came out hour_of_day = IntegerField( null=False, validators=[ MaxValueValidator(23), MinValueValidator(0) ] ) In PostGres, the query would look similar to select * FROM article a, articlestat ast where a.id = ast.article_id and ast.votes > 100 * (select index from statbyhour where hour_of_day = extract(hour from a.created_on)) Notice the subquery as part of the WHERE clause ast.votes > 100 * (select index from statbyhour where hour_of_day = extract(hour from a.created_on)) So I thought I could do something like this ... hour_filter = Func( Func( (F("article__created_on") + avg_fp_time_in_seconds * "interval '1 second'"), function='HOUR FROM'), function='EXTRACT') ... votes_criterion2 = Q(votes__gte=F("article__website__stats__total_score") / F( "article__website__stats__num_articles") * settings.TRENDING_PCT_FLOOR * StatByHour.objects.get(hour_of_day=hour_filter) * day_of_week_index) qset = ArticleStat.objects.filter(votes_criterion1 & votes_criterion2, comments__lte=25) but this results in a "Cannot resolve keyword 'article' into field. Choices are: hour_of_day, id, index, num_articles, total_score" … -
Jquery no Django
Ao editar um campo gerado por um Jquery em um formulário Django ele duplica em vez de deletar e inserir o que eu editei. Tentei ler o campo e ver se ele já estava preenchido e se sim que deletasse. try: funcao_banco = Funcao.objects.filter(matricula=funcao.matricula) if len(funcao_banco) > 0: deletou = funcao_banco.delete() except Funcao.DoesNotExist: pass funcoes.append(funcao) Queria alguma solução de como faço para quando eu for salvar ele em vez de duplica,apague o campo e insira os novos dados. -
Having been run as an .exe, the django admin panel hides models except users and user groups
I created the most simple Python/Django project following to the standard procedure: virtual environment => startproject, startapp, simple model with one Char field. Also I add my model to the admin.py file. Then I ran makemigrations, migrate, createsuperuser. If I run like python manage.py runserver then everything is perfect: I can view and edit my model. But I need to run my program as a single exe-file. For that purpose I use PyInstaller with default settings. The exe file is generated with no errors. And here is the problem: there is no my model at the Admin Panel except User and User Groups. My environment is Python 3.7, Django 2.2, Pyinstaller 3.4, Windows 7. Everything is under a virtual environment. Have anyone run into that problem? Is there any workaround to it? Thanks in advance. -
In a Django view, how do I correctly render a returned HTML table to a template?
I'm having trouble correctly passing a html table created with Pandas DataFrame.to_html to a Django view. How do I do this correctly? In views.py I have the function: def my_view(request): data_table = Class().main() return render_to_response('app/insight.html', {'data_table':data_table}) Class().main() successfully returns a HTML table. A simplified insight.html body would be: <body> {{data_table}} </body> The problem is that I'm getting source like: &lt;table border=&quot;1&quot; class=&quot;dataframe&quot;&gt; &lt;thead&gt; &lt;tr style=&quot;text-align: right;&quot;&gt; &lt;th&gt;header 1:&lt;/th&gt; &lt;th&gt;header 2&lt;/th&gt; &lt;th&gt;header 3&lt;/th&gt; &lt;th&gt;header 4&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;data 1&lt;/td&gt; &lt;td&gt;data 2&lt;/td&gt; &lt;td&gt;data 3&lt;/td&gt; &lt;td&gt;data 4&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; And a page display of: <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> </thead> <tbody> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </tbody> </table> -
How to get the list of "objects" from a queryset in a Foreign Key relationship in Django
How can I get the list of objects from a Foreign Key realationship queryet? (as when you loop through a list using "for x in foo:print(x)") code below: class class Course(models.Model): name = models.CharField(max_length=20) user = models.ManyToManyField(User, related_name='typecourses') description = models.TextField(max_length=500) class Module(models.Model): name = models.CharField(max_length=20) courses = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='courses', null=True) Below are the two queries I have tried in the "views", they both output the same results as querysets. 1/ module_taken = list(Course.objects.get(id=1).courses.all()) 2/ module_taken = Module.objects.select_related('courses').all() result: <QuerySet [<Module: Foo>, <Module: Bar>]> Any help would be much appreciated. -
IntegrityError: FK field (user_id) remains "null" despite form_valid() override
The user should be able to log an activity into the Activity_Log model but the CreateView form must automatically fill the user_id from the current logged-in user. I have extended the django auth_user table on a OnetoOne relationship into another model named Profile (users-profile). user_id is a ForeignKey field automatically added to my Profile model (I can see it in MySQL WorkBench) and is the PrimaryKey in auth_user model. However, I'm getting an IntegrityError (1048: 'user_id' cannot be 'null'), despite using def form_valid(self, form) override in LogCreateView. I've tried several variants of form_valid() from StackOverflow examples but to no avail. My POST variables are all correct inputs for the other fields correctly taken from the form i.e. 'projectrowid', 'activityid', 'startdatetime', 'enddatetime', 'comments', but the user_id is not being passed along with the POST variables to the Activity_Log model. Any advice on how to correctly override def form_valid() would be really appreciated! views.py - LogCreateView class LogCreateView(LoginRequiredMixin, CreateView): model = Activity_Log fields = ['projectrowid', 'activityid', 'startdatetime', 'enddatetime', 'comments'] def get_template_names(self): if self.request.user.is_superuser: template_name = 'Administrator/activity_log_form.html' return template_name else: template_name = 'Staff/activity_log_form.html' return template_name def form_valid(self, form): form.instance.user_id = self.request.user.id return super(LogCreateView, self).form_valid(form) models.py - ActivityLog model class Activity_Log(models.Model): logentryid = models.AutoField(db_column='logEntryID', … -
The view ___ didn't return an HttpResponse object. It returned None instead
I have a scheduling app where patients can register for appointments. When I submit the form for a new appointment, I get the value error. views.py def patient_portal(request): appointments = Appointment.objects.filter(patient=request.user.patient.pid) data_input = request.GET.get('date') selected_date = Appointment.objects.filter(date = data_input).values_list('timeslot', flat=True) available_appointments = [(value, time) for value, time in Appointment.TIMESLOT_LIST if value not in selected_date] doctor = Patient.objects.get(doctor=request.user.patient.doctor).doctor print(doctor) if request.method == 'POST': form = AppointmentForm(initial={'doctor': doctor,'patient': request.user.patient}, instance=request.user.patient) if form.is_valid(): form.save() return redirect('../home/') else: form = AppointmentForm(initial={'doctor': doctor,'patient': request.user.patient}, instance=request.user.patient) return render(request, 'scheduling/patient.html', {"form" : form, "appointments" : appointments, "available_appointments" : available_appointments, "data_input": data_input, "doctor": doctor}) patient.html: <form method="post" action="" id="timeslot" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Submit</button> </form> forms.py: class AppointmentForm(forms.ModelForm): class Meta: model = Appointment fields = ('doctor','patient','date','timeslot') -
How to Express datetime higher or lower than 30 days django
how can i Express this in django : the difference between last dateins and today is more than 30 days. this is my model class Suivre(models.Model): dateins=models.DateTimeField() somthing like a=Suivre.objects.filter() -
python - django error "RunetimeError: doesn't declare an explicit app_label"
I am struggling with a problem in using django. When I type "python manage.py runserver", it holds for few seconds and keeps giving me a following message: "RuntimeError: Model class upload.models.ImgParent doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." I searched similar problems on the internet and tried to add 'upload.models.ImgParent' on INSTALLED_APPS in settings.py but it still doesn't work. My current INSTALLED_APPS in settings.py looks like this: INSTALLED_APPS = [ 'search.apps.SearchConfig', 'upload.apps.UploadConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'mod_wsgi.server', 'home', ] and my apps.py looks like this: class UploadConfig(AppConfig): name = 'upload' Please help with my problem and let me know if you need any additional information. Thank you. -
Cron job with django application
I would like to use a cron task in order to delete media files if condition is True. Users generate export files stored in Media folder. In order to clean export files in background, I have a Cron task which loop over each file and looks if the expiry delay is passed or not. I used django-cron library Example: File in Media Folder : Final_Products___2019-04-01_17:50:43.487845.xlsx My Cron task looks like this : class MyCronExportJob(CronJobBase): """ Cron job which removes expired files at 18:30 """ RUN_AT_TIMES = ['18:30'] schedule = Schedule(run_at_times=RUN_AT_TIMES) code = 'app.export_cron_job' def do(self): now = datetime.datetime.now() media_folder = os.listdir(os.path.join(settings.MEDIA_ROOT, 'exports')) for files in media_folder: file = os.path.splitext(files.split(settings.EXPORT_TITLE_SEPARATOR, 1)[1])[0] if datetime.datetime.strptime(file, '%Y-%m-%d_%H:%M:%S.%f') + timedelta(minutes=settings.EXPORT_TOKEN_DELAY) < now: os.remove(os.path.join(os.path.join(settings.MEDIA_ROOT, 'exports'), files)) # settings.EXPORT_TOKEN_DELAY = 60 * 24 I edited my crontab -e : 30 18 * * * source /home/user/Bureau/Projets/app/venv/bin/activate.csh && python /home/user/Bureau/Projets/app/src/manage.py runcrons --force app.cron.MyCronExportJob Then I launched service cron restart But nothing as changed. My file is still there. However it should be removed because his date is greater than now + settings.EXPORT_TOKEN_DELAY I'm using Ubuntu to local dev and FreeBSD as production server environment. -
What is different between path and url in Django? Which one is better?
What is different between path and url in Django? Which one is better? What I see there have no different. Why we need both? -
MultiValueKeyDictError Django while uploading csv file
I am trying to upload csv file from user and display it on the template. I have searched a lot for error but none has helped. So I decided to take help from this great community. Here is my code views.py @csrf_exempt def offlineResults(request): screenNametestList = [] friendsCountList = [] followersCountList = [] favouriteCountList = [] listedCountList = [] statusCountList = [] genEnabledList = [] protectedList = [] verifiedList = [] defaultProfileList = [] botsList = [] if request.method == 'POST' and request.FILES['filecsv']: csv_file = request.FILES['filecsv'] data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) # skipping 1st line because 1st line contains header file for column in csv.reader(io_string, delimiter=','): screenNametest = column[0] screenNametestList.append(screenNametest) friends_countTest = column[1] friendsCountList.append(friends_countTest) followers_countTest = column[2] followersCountList.append(followers_countTest) favouriteCountTest = column[3] favouriteCountList.append(favouriteCountTest) listedCountTest = column[4] listedCountList.append(listedCountTest) statusCountTest = column[5] statusCountList.append(statusCountTest) geoEnabledTest = column[6] genEnabledList.append(geoEnabledTest) protectedTest = column[7] protectedList.append(protectedTest) verifiedTest = column[8] verifiedList.append(verifiedTest) defaultProfileTest = column[9] defaultProfileList.append(defaultProfileTest) botsTest = column[10] botsList.append(botsTest) dicCSV = { 'sc': screenNametestList, 'friendCount': friendsCountList, 'followersCount': followersCountList, 'favouriteCount': favouriteCountList, 'listedCount': listedCountList, 'statusCount': statusCountList, 'geoEnabled': genEnabledList, 'protected': protectedList, 'verified': verifiedList, 'defaultProfile': defaultProfileList, 'bots': botsList } return JsonResponse(dicCSV) offline.html <div class="container"> <h1 class="text-center"><b><u>Offline Results</u></b></h1> <form class="md-form mt-4" method="post" enctype="multipart/form-data"> <div class="file-field"> <input type="file" name="filecsv" accept=".csv"> <button type="submit" id="load_csv" … -
Which is a more efficient method, using a list comprehension or django's 'values_list' function?
When attempting to return a list of values from django objects, will performance be better using a list comprehension: [x.value for x in Model.objects.all()] or calling list() on django's values_list function: list(Model.objects.values_list('value', flat=True)) and why? -
Arrayfield of model vs many to many
Let's say I have 2 models, User and Book. User can have multiple books and book can belong to multiple users. I only care to get what books each user has, and not so much about the other way around. I am thinking about 2 solutions here: ManyToManyField and ArrayField of Book model. What are the pros and cons? When I store ArrayField of Book model in User table, does Postgres duplicate the data in both Book and User table? -
Could not find a version that satisfies the requirement requests-html-0.8.2/ 0.9.0 / 0.10.0. Django - pythonanaywhere
When I try to deploy my application to pythonanywhere, the following error it is returned. Could not find a version that satisfies the requirement requests-html. I tried with the following versions 0.8.2/ 0.9.0 / 0.10.0- with no effect. How can I solve it? I tried to change the versions to a higher one or add other packages (as per the internet tips), but to no avail. Any help will be appreciated. absl-py==0.7.1 aiourllib==0.1.3 appdirs==1.4.3 asn1crypto==0.24.0 astor==0.7.1 beautifulsoup4==4.6.3 bleach==3.0.2 boto==2.49.0 boto3==1.9.103 botocore==1.12.103 bs4==0.0.1 certifi==2018.10.15 cffi==1.12.2 chardet==3.0.4 civis==1.9.0 civis-jupyter-extensions==0.1.3 civis-jupyter-notebook==0.4.2 click==6.7 cloudpickle==0.6.1 colorama==0.4.0 confusable-homoglyphs==3.2.0 crypto==1.4.1 cryptography==2.6.1 cssselect==1.0.3 cycler==0.10.0 decorator==4.3.0 defusedxml==0.5.0 Django==2.0 django-bootstrap3==11.0.0 django-bower==5.2.0 django-ckeditor==5.6.1 django-cors-headers==2.4.0 django-crispy-forms==1.7.2 django-debug-toolbar==1.9.1 django-filter==2.0.0 django-filters==0.2.1 django-js-asset==1.2.2 django-multiselectfield==0.1.8 django-registration==2.4.1 django-scheduler==0.8.7 django-storages==1.7.1 django-taggit==0.23.0 django-tinymce==2.8.0 django-widget-tweaks==1.4.3 djangorestframework==3.9.0 docutils==0.14 entrypoints==0.2.3 fake-useragent==0.1.11 Flask==1.0.2 gast==0.2.2 gitdb2==2.0.5 GitPython==2.1.11 grpcio==1.19.0 h5py==2.9.0 httplib2==0.11.3 icalendar==4.0.3 idna==2.7 ipykernel==5.1.0 ipython==6.2.1 ipython-genutils==0.2.0 ipywidgets==7.4.2 ItsDangerous==1.1.0 jedi==0.13.1 Jinja2==2.10 jmespath==0.9.4 joblib==0.11 jsonref==0.1 jsonschema==2.6.0 jupyter==1.0.0 jupyter-client==5.2.3 jupyter-console==6.0.0 jupyter-core==4.4.0 Keras-Applications==1.0.7 Keras-Preprocessing==1.0.9 kiwisolver==1.0.1 lxml==4.2.5 Markdown==3.0.1 MarkupSafe==1.0 matplotlib==3.0.3 mistune==0.8.4 Naked==0.1.31 nbconvert==5.4.0 nbformat==4.4.0 notebook==5.7.0 numpy==1.15.2 pandas==0.23.4 pandocfilters==1.4.2 parse==1.9.0 parso==0.3.1 pickleshare==0.7.5 Pillow==5.3.0 prometheus-client==0.4.2 prompt-toolkit==1.0.15 protobuf==3.7.0 psycopg2==2.7.5 pubnub==4.1.2 PyAutoGUI==0.9.41 pybase62==0.4.0 pycparser==2.19 pycrypto==2.6.1 pycryptodome==3.8.0 pycryptodomex==3.6.6 pyee==5.0.0 PyGetWindow==0.0.3 Pygments==2.2.0 PyMsgBox==1.0.6 pyparsing==2.2.2 pyppeteer==0.0.25 pyquery==1.4.0 PyRect==0.1.4 PyScreeze==0.1.19 python-dateutil==2.7.3 python-decouple==3.1 PyTweening==1.0.3 pytz==2018.5 pywinpty==0.5.4 PyYAML==3.13 pyzmq==17.1.2 qtconsole==4.4.2 requests==2.20.0 requests-html==0.9.0 s3transfer==0.2.0 scipy==1.1.0 seaborn==0.9.0 Send2Trash==1.5.0 shellescape==3.4.1 simplegeneric==0.8.1 six==1.11.0 smmap2==2.0.5 … -
Angular Websocket connection timeout with Django Channels
I'm currently having an issue with my websocket timing out with the following error message failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT My websocket connection via Django Channels works on my local, but on the server it just times out (not even hitting the onOpen console log). I'm not sure at all what the issue is and I'm very new to websockets so I was hoping someone could help. Below is how I'm instantiating my websocket. This is done on the aws ec2 if that is relevant. this.ws = new WebSocket('wss://api.example.com:9000/aurl/'); With my channel layers as such CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I'm pretty sure the routing is correct as it works in my local, so I have no idea where the error originates from. I tried using both daphne and redis using 'BACKEND': 'asgi_redis.RedisChannelLayer' but that didn't seem to work either, daphne is set up to run on port 9000. I feel like this is a simple error relating to the actual port numbers but I don't know. Edit: On my local I'm using this.ws = new WebSocket('ws://127.0.0.1:8000/aurl/'); for the creation of the websocket -
Django, is filtering by string faster than SQL relationships?
Is it a major flaw if I'm querying my user's informations by their user_id (string) rather than creating a Profile model and linking them to other models using SQL relationships? Example 1: (user_id is stored in django sessions) class Information(models.Model): user_id = models.CharField(...) ... # also applies for .filter() operations. information = Information.objects.get(user_id=request.getUser['user_id']) Example 2: (user_id is stored in Profile) class Profile(models.Model): user_id = models.CharField(...) ... class Information(models.Model): profile = models.ForeginKey(Profile, ...) ... information = Information.objects.get(profile=request.getProfile) note: I am storing the user's profile informations on Auth0, with this method Profile will only have one field, user_id. On Django, will using a string instead of a query object affect performances to retrieve items? -
Using Django framework only with admin backend without any apps
I want to use Django only with admin backend without any apps. So actually all I want to do is to use the admin backend to CRUD my database. Now apparently the admin backend does not have a models.py and no views.py. Do I really need the models.py from an app, or can I easily use only the admin backend to CRUD my database. How would I do this, add a models.py to the admin backend? -
How do I calculate the average difference between two dates in Django?
Using Django and Python 3.7. I'm tryhing to write a query to give me the average of the difference between two dates. I have two fields in my model, both "DateTimeField"s, and I try to calculate the average difference like so everything_avg = Article.objects.aggregate( avg_score=Avg(F('removed_date') - F('created_on'), output_field=models.DateTimeField()) ).filter(removed_date__isnull=False) return everything_avg but I end up getting this error when running the above AttributeError: 'dict' object has no attribute 'filter' What's the right way to get my average? -
How can I get all childs for each tree?
I have a two trees, building by django-treebeard. How can I get all childs for each tree in template. I can get all childs for each tree in views with get_all_child(), but I must be get this in template. {% for object in object_list %} ... {% endfor %} -
Jquery datepicker widget in django form not loading
I have searched everywhere and have tried multiple solutions to the same problem but I just cannot figure out what I am doing wrong here. I am trying to use jquery datepicker widget in my django form but the widget just won't load when i click the field. My base.html: {% load static %} <!DOCTYPE html> <html> <head> <!-- Jquery UI --> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" /> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'student_input/main.css' %}"> <title>Student Data</title> </head> My HTML: {% extends "student_input/base.html" %} {% load crispy_forms_tags %} {% block content %} <head> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script> </head> <h2>New Student</h2> <script type="text/javascript"> $( function() { $( "#id_input_date" ).datepicker(); }); </script> <script type="text/javascript"> $(document).ready( function(){ $("#jqtest").html("JQuery installed successfully!"); } ); </script> <p id="jqtest"></p> <form method="post" class="post-form">{% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save Student</button> </form> {% endblock content %} forms.py: from django import forms from .models import Student class StudentForm(forms.ModelForm): class Meta: model = Student widgets = {'input_date': forms.DateInput(attrs={'class': 'datepicker'})} fields = ('first_name', 'last_name', 'student_level', 'student_reading', 'student_dictation', 'student_speaking', 'student_writing', 'input_date', 'student_notes', models.py: from django.db import models class … -
How can I save data from POST method to the database from a forms.Model?
Since few hours ago I am facing a basic problem so I have decided to ask a question after tried to do many many example but I still can't save the data from my forms using POST method. Into my template views, when I post a data and from my web page nothing go to the database and even when I do print(request.POST) I got nothing, its seem like nothing work. I am using Django 2.1.7 the latest version of Django. This my models: class AddressDelivery(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) address_type = models.CharField(max_length=120, choices=ADDRESS_TYPES) address_line_1 = models.CharField(max_length=120) address_line_2 = models.CharField(max_length=120, null=True, blank=True) city = models.CharField(max_length=120) phone = PhoneNumberField(unique=True) country = models.CharField(max_length=120, choices=COUNTRIES, default=current_country) state_or_department = models.CharField(max_length=120) postal_code = models.CharField(max_length=120) def __str__(self): return str('{}'.format(self.billing_profile)) This is my forms: class AddressForm(forms.ModelForm): class Meta: model = AddressDelivery fields = [ 'first_name', 'last_name', 'phone', #'billing_profile', #'address_type', 'address_line_1', 'address_line_2', 'city', 'postal_code', 'state_or_department', 'country', ] widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), 'postal_code': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'postal code'}), 'state_or_department': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'state or department'}), 'city': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'city'}), 'address_type': forms.Select(attrs={'class': 'form-control'}), 'address_line_1': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'address line 1'}), 'address_line_2': forms.TextInput(attrs={'class': … -
Database isn't set how so?
I have a website I can access it but when I logged into it shows me the follows erros "database connection isn't set to UTC". I am using postgres, digital ocean and Django.