Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send a data from one page to another page with autofilling the form
I have a table in one page, and every raw of this table has a button that redirects to another page with a form. I want the following: by pressing the button in the raw of table, the data of this raw goes to another page and fills the form by itself. And all i have to do is to submit -
How to use Channels with multi-tenancy?
I'm creating Trello-like task manager application and I want to implement the same feature with drag&drop task cards to columns with websockets. The project is created with using django-tenant-schemas and channels are added later. I set up websocket connection in connect function, where I also set up connection to tenant (see below). It works, but when consumer receives json with task and column ids and it needs to work with relationships (assign task to column) it raises error that such relationship doesn't exist. I send a json like this: { "task": 3, "column: 1, } It returns this error: relation "task_manager_column" does not exist LINE 1: ...mn"."board_id", "task_manager_column"."code" FROM "task_mana... But actually I'm connected to tenant That's how my code looks like class TMConsumer(AsyncWebsocketConsumer): board_id = None board_name = None board_group = None university = None tenant = None async def get_tenant(self): # Client is TenantMixin object return Client.objects.get(name=self.university) async def connect(self): # University is a tenant self.university = self.scope['headers'][0][1].decode('utf-8').split('.')[0] self.tenant = await self.get_tenant() # connection is from django.db connection.set_tenant(self.tenant) self.board_id = self.scope['url_route']['kwargs']['board_id'] self.board_name = "board_{}".format(self.board_id) self.board_group = "{}_group".format(self.board_name) await self.accept() async def disconnect(self, code): await self.disconnect(code) async def receive(self, text_data=None, bytes_data=None, **kwargs): # load the json that was above … -
How to create select field with query set in django forms?
I want to create a django form which will allow me to choose to objects - departure and destination, from a model to search the route between this places, but I got an error that the model Place is not iterable my form: from django import forms from .models.places_models import Place from django.db.models import Q class TripSearchForm(forms.Form): departure = forms.CharField(max_length=128, widget=forms.Select(choices=Place.objects.filter(Q(role=Place.CITY) | Q(role=Place.VILLAGE) | Q(role=Place.TOWN)))) destination = forms.ChoiceField(max_length=128, widget=forms.Select(choices=Place.objects.filter(Q(role=Place.CITY) | Q(role=Place.VILLAGE) | Q(role=Place.TOWN)))) -
Send data from template to views
I am creating a phone-comparison project. I this when the user clicks the compare button a side nav will come out and he will add the products dynamically by clicking on the add button when the user is done with adding the products. then the user will click on another compare button for comparing the products and all the name of the products will go as an array to the views from the template. now in views, the compare function will scrape the data on the basis of the array value and create a dictionary and render the dictionary to the demo.html. but the problem is when I'm using XMLHttpRequest an Array is sent to the views and compare function is scraping the data but I can't use here render function Instead of it I'm returning JSONresponse. but I don't know how to display the jsonresponse data in the template. please help me to solve it. thanks in advance the function which sends the array to views: function ComAction() { let xhr = new XMLHttpRequest(), data = new FormData(); data.append('csrfmiddlewaretoken', getCookie('csrftoken')); brands.forEach(function (brand) { data.append('brand', brand); }); xhr.open('POST', 'compare_in/', true); xhr.onload = function () { if (xhr.status === 200) { … -
How to upload image in frontend using django api
APi is written to upload images and details of shop, How i send image data to api in frontend..here is frontend code. <div class="form-group"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <label for="shopimage">Shop image:</label> </div> </div> <div class="row"> <div class="col-md-4 col-md-offset-4"> <input type="file" class="form-control" id="shopimage"> </div> </div> </div> -
how to send email using company email address instead of gmail account in django
I want to send reset password link with my company email address instead of my personal gmail account.I have a compnay email address and password but got no idea what i have to give in EMAIL_HOST .How can i do this ? settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' ## ?? EMAIL_HOST_USER = "myname@compnayname.com" EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = '587' -
Running and stop celery beat with python script
I am using celery in my Django project.I start my celery beat with the command celery -A projectname worker -B and I stop it by killing its process.I wanted to know if there is anyway I could start and stop the celery beat with a python script. Any help would be appreciated. -
"Login timeout expired" when trying to access MSSQL db from django
My django app was working on sqlite3 database. Few days ago I got a "mission" to make the app using mssql. And I can't connect to database. My settings.py looks like this: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'ESD_CONTROL', 'HOST': 'Mateo-PC\SQLEXPRESS01', 'USER': 'esd', 'PASSWORD': 'red3fred4', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server' } } } When I'm trying to run, for example, python manage.py migration, this error occurs: django.db.utils.OperationalError: ('HYT00, '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') For my test env, I had SQL Server Express installed on my laptop. It's 14.0.1000.169 version. I'm using, as you can see above, ODBC Driver 17 for SQL Server. It's my "first time" with mssql and I don't even know, whan can I do. -
Break sentence of a paragraph and dynamically rearrange and re frame
consider a paragraph, p = "Both apples and oranges are fruits but apples are usually sweet and oranges are usually citrus.Apple have a pH arround 3 and orange between 3-4. Oranges are an excellent source of Vitamin C. Apples have a higher foliage (55mcg) as compared to oranges (23mcg). I want to reframe the para like, re_order = "Apple have a pH arround 3 and orange between 3-4.Both apples and oranges are fruits but apples are usually sweet and oranges are usually citrus.Apples have a higher foliage (55mcg) as compared to oranges (23mcg).Oranges are an excellent source of Vitamin C." how transform p to re_order paragraph using python? -
How do i create API for my own Login page in Django rest freamework
I have created Registration API and data stored in my database. Now i want to write API for Login if the user already registered it will allow to login or successfully Log in message otherwise it will through error message. -
Cant migrate django_pyowm on Django 1.10.5
I installed django_pyowm in my project, but django refuses to migrate the models. Referring to the fact that I have not installed modules. Below I get this error output: >>> python3 manage.py makemigrations django_pyowm Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django_pyowm/models.py", line 4, in <module> from pyowm.webapi25.location import Location as LocationEntity ImportError: No module named 'pyowm.webapi25' Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/dave/Geo_Django/Django_geo_test/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models self.models_module = … -
UnboundLocalError:local variabel 'socialhandle' referenced before assignment
I'm working on a django project and i'm trying to fetch data from the database, according to some primary key value. However when the object exists in the DB then everything is working fine but when it doesn't then django is raising: UnboundLocalError: local variable 'socialhandle' referenced before assignment. Here is my django view: def profile(request, profile_id): """View for returning a unique profile""" profile = get_object_or_404(UserProfile, pk=profile_id) try: socialhandle = SocialPlatform.objects.get(user_id=profile_id) except socialhandle.DoesNotExist: socialhandle = None context = { 'profile' : profile, 'socialhandle' : socialhandle, } return render(request, 'profiles/profile.html', context) -
django app on uwsgi & nginx showing internal server error page
My django Project structure is below # tree -L 2 . ├── account │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── apps │ ├── blog │ ├── blogs │ ├── gallery │ ├── __init__.py │ ├── myapp │ ├── mysensing │ ├── __pycache__ │ └── qrcreate ├── Blog │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── static │ ├── urls.py │ ├── views.py │ └── wsgi.py and this is my uwsgi file content [uwsgi] project = djangy uid = $USER base = /home/%(uid) chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).Blog.wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true and lastly my nginx configuration file server { listen 80; server_name djangy.vm www.djangy.vm; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/$USER/djangy; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/djangy.sock; } } When I run this project using manage.py, it runs fine and shows as this But when I run it behind uwsgi & nginx, it shows internal server error, I can't … -
How to join these Django models?
How should I join these Django models to get all Player models that participate in challenges of logged in users (see variable named challenges_participants in views.py ? In SQL this could maybe be done with a subquery? However, I did not came up with a solution on how to efficiently implement this with Django models. Thanks a lot! Code: models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional fields userid = models.CharField(max_length=256) wallet_balance = models.IntegerField(default=0) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Player.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.player.save() class Challenge(models.Model): id = models.IntegerField(primary_key=True, unique=True) status = models.CharField(max_length=20) type = models.CharField(max_length=20) amount = models.DecimalField(max_digits=10, decimal_places=2) created_timestamp = models.DateTimeField() duration = models.DurationField() started_timestamp = models.DateTimeField(null=True, blank=True) end_timestamp = models.DateTimeField(null=True, blank=True) def __str__(self): return str(self.id) class PlayerChallenge(models.Model): user_challenge_id = models.IntegerField(primary_key=True, unique=True) player = models.ForeignKey(Player, on_delete=models.CASCADE) challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) accepted_timestamp = models.DateTimeField(null=True, blank=True) def __str__(self): return str(self.user_challenge_id) + " (Player: " + str(self.player.user.username) + ", Challenge: " + str(self.challenge.id) + ")" views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth import authenticate, login, … -
Specify fields of related model in Django GeoJSON serializer field
I am trying to plot the latlong points in the map using geojson serializer. For this functionality, I have two models named Activity and ClusterA. Activity is a model that stores data for some activity defined in a project. This activity contains a PointField field called location. This is my Activity model: class Activity(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) target_number = models.IntegerField(null=True, blank=True) target_unit = models.CharField(max_length=200, null=True, blank=True) beneficiary_level = models.BooleanField(default=True) weight = models.FloatField(default=0) location = PointField(geography=True, srid=4326, blank=True, null=True) def __str__(self): return self.name @property def latitude(self): if self.location: return self.location.y @property def longitude(self): if self.location: return self.location.x Similarly, an activity can belong to a cluster. This data is stored in the model ClusterA(Cluster Activity). ClusterA refers to the activities that are specific for a cluster. Cluster model class Cluster(models.Model): name = models.CharField(max_length=200) ward = models.CharField(max_length=200) def __str__(self): return self.name ClusterA model class ClusterA(models.Model): activity = models.ForeignKey('Activity', related_name='clustera') target_number = models.IntegerField(null=True, blank=True, default=0) target_unit = models.CharField(max_length=200, null=True, blank=True, default='') time_interval = models.ForeignKey(ProjectTimeInterval, related_name='cainterval', null=True, blank=True) target_completed = models.IntegerField(null=True, blank=True, default=0) interval_updated = models.BooleanField(default=False) target_updated = models.BooleanField(default=False) location = PointField(geography=True, srid=4326, blank=True, null=True) def __str__(self): return self.name @property def latitude(self): if self.location: return self.location.y @property def longitude(self): if self.location: return … -
Do not have right aruguements and getting an error
Error - >>> expected string or bytes-like object I have know idea about what is wrong in this models.py ->> publish_date = models.DateTimeField(auto_now =True, auto_now_add = False, null =True) timestamp = models.DateTimeField( auto_now_add = True, ) updated = models.DateTimeField(auto_now =True) -
How to replace `created_at` field with `updated_at` field in templates when a post is updated?
I have the following model wherein is created_at and updated_at field respectively: class BlogPost(models.Model): title = models.CharField(max_length=255) content = models.TextField() slug = models.SlugField(blank=True, unique=True) image = models.ImageField(default='default.jpg',upload_to='posts/%Y/%m/%d') created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and this is the result when I create a post: I want it to show only Posted now text, the current time, and only when I update that field it should show Updated now text. and this is the html of above template: <small class="text-secondary">Posted {{ object.created_at|naturaltime }}</small><br> <small class="text-secondary">Updated {{ object.updated_at|naturaltime }}</small><br> I don't know whether to change my model or use some if conditions in my template, Can you please help me do this? Thank you very much! -
AttributeError: module 'django.db.models' has no attribute 'cascade'
I'm fairly new to Python and the Django framework and have run into a problem that i can't find much information on, I'm currently following the django tutorial on: https://docs.djangoproject.com/en/2.2/intro/tutorial02/ I keep running into this error - question = models.ForeignKey(Question, on_delete=models.cascade) AttributeError: module 'django.db.models' has no attribute 'cascade' i feel like there is something very simple i'm not doing and would love some help. from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.cascade) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) It says i'm supposed to get: Migrations for 'polls': polls/migrations/0001_initial.py: - Create model Choice - Create model Question - Add field question to choice -
How to fetch value of vDateField on change by using Django Admin Datepicker widget?
I am trying to fetch the value of a date field in Django admin using jquery. Right now I have managed to fetch the value of the text field if its manually changed, but if the value is changed using admin date picker widget, the code isn't working. $( document ).ready(function() { console.log( "ready!" ); $('#id_start_date_0').bind('change', function() { alert($(this).val()); }); }); -
Wagtail Documents: Large file size (>2GB) upload fails
I'm trying to upload a file using the built in wagtaildocs application in my Wagtail application. I've setup my Ubuntu 16.04 server was setup with the Digital Ocean tutorial methods for Nginx | Gunicorn | Postgres Some initial clarifications 1. In my Nginx config I've set client_max_body_size 10000M; 2. In my production settings I have the following lines. MAX_UPLOAD_SIZE = "5242880000" WAGTAILIMAGES_MAX_UPLOAD_SIZE = 5000 * 1024 * 1024 3. My file type is a .zip 4. I'm not receiving a timeout error. So as along as my File size is below 5Gb I should be fine from a configuration stand point unless I'm missing something or am blind to a typo. My error occurs some where between 2Gb and 2.3Gb I've already tried adjusting all the configuration values even to unreasonably large values. I've tried using other file extensions and doesn't change my error. Here is my error message Internal Server Error: /admin/documents/multiple/add/ Traceback (most recent call last): File "/Users/wesleygarlock/Git/thearchmedia/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/wesleygarlock/Git/thearchmedia/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/wesleygarlock/Git/thearchmedia/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/wesleygarlock/Git/thearchmedia/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File … -
How to correctly make an assertLogs test with unittest using a django settings configuration for logging?
I have a setting for logging in my django project and I want to make a test using assertLogs. I used the example provided in the documentation: https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertLogs with self.assertLogs('foo', level='INFO') as cm: logging.getLogger('foo').info('first message') logging.getLogger('foo.bar').error('second message') self.assertEqual(cm.output, ['INFO:foo:first message', 'ERROR:foo.bar:second message']) My django settings are like below: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, 'standard': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'default': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + '/logs/default.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter':'standard', }, 'debug_file': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + '/logs/debug.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter':'standard', }, 'warning_file': { 'level':'WARNING', 'class':'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + '/logs/warning.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter':'standard', }, 'info_file': { 'level':'INFO', 'class':'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + '/logs/info.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter':'standard', }, 'error_file': { 'level':'ERROR', 'class':'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + '/logs/error.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter':'standard', }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', }, 'emails': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + … -
Django Admin Error (Always require login couple of time) when DEBUG = False (Productions)
I've just deployed Django 2.2 in Google App Engine. Everything works fine except this one. The admin page requires login couple of time till I can finally go to the dashboard. This happens also when I click on the Post model to create a new post, I need to login again. I'm not sure why but this happen when the DEBUG = False. I take a look at this question and his answer but it might bit different for the debug. Does anyone have the same issue as mine? Here's my settings.py file: DEBUG = False # SECURITY WARNING: don't run with debug turned on in production! BASE_URL = "https://example.com" ALLOWED_HOSTS = ['*'] # ALLOWED_HOSTS = [ # 'www.notnoob.com', # 'notnoob.com' # ] # SESSION_COOKIE_NAME # SESSION_COOKIE_DOMAIN = None SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'home', 'blog', 'contact', 'ckeditor', 'ckeditor_uploader', 'taggit', 'meta', 'django_filters', ] ... ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dj.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'dj/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
how to get value django choice field?
i cant read data from django form choice field. data in form does not go to form in views.py or forms.py. error list = Select a valid choice. Rate is not one of the available choices. how to fix it ? #views.py def recipe_detail(request, recipe_name): recipe = Recipe.objects.get(recipe_name=recipe_name) form = VoteSubmissionForm() if request.method == 'POST': recipe = Recipe.objects.get(recipe_name=recipe_name) if 'Like' in request.POST: recipe_like = recipe.recipe_like recipe_like = int(recipe_like) + 1 recipe = Recipe.objects.filter(recipe_name=recipe_name).update(recipe_like=recipe_like) recipe = Recipe.objects.get(recipe_name=recipe_name) return render(request, 'detail.html', { 'recipe': recipe, 'form': form, }) elif 'vote' in request.POST: form = VoteSubmissionForm(request.POST) #forma veri gelmiyor ? if form.is_valid(): recipe_vote = recipe.recipe_vote recipe_vote_count = recipe.recipe_vote_count recipe_vote = (int(recipe_vote) * int(recipe_vote_count) + form.cleaned_data['vote']) / (int(recipe_vote_count) + 1) recipe_vote_count = int(recipe_vote_count) + 1 recipe = Recipe.objects.filter(recipe_name=recipe_name).update(recipe_vote=recipe_vote, recipe_vote_count=recipe_vote_count) recipe = Recipe.objects.get(recipe_name=recipe_name) return render(request, 'detail.html', { 'recipe': recipe, 'form': form, }) else: return redirect('index') return render(request, 'detail.html', { 'recipe': recipe, 'form': form, }) #forms.py VOTE_CHOICES = ( ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10') ) class VoteSubmissionForm(forms.Form): vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.Select, label='Vote') <form method="POST"> {% csrf_token %} {{ form }} <input class="btn btn-primary" type="submit" name="vote" value="Rate"> </form> form not is_valid. … -
How to persist data found in tables within a django template, in postgresql
I am scraping several sites and I show the data obtained in 6 tables within a django template. My intention is to persist the data of the tables in postgresql, but I can not realize how to perform that task. In principle I am trying to save the data from the second table. For this I have created the models that I show below, as well as a view that is called: registroDivisaArgentina (). The template is called quotes.html and within it, there are 6 tables. I have tried to work with a class called: RegisterArgentineValues () within a forms.py file models.py class DivisasArgentina(models.Model): class Meta: ordering = ['CodigoDA'] CodigoDA = models.CharField(max_length=50, primary_key = True) Texto_para_Reporte = models.CharField(max_length=70) def __str__(self): return '{}'.format(self.Texto_para_Reporte) class ValoresDivisasArgentina(models.Model): class Meta: ordering = ['Dia'] DivisasArgentina = models.ForeignKey(DivisasArgentina, on_delete=models.PROTECT) Dia = models.DateField(default=date.today) Hora = models.DateTimeField(default=timezone.now) Compra = models.FloatField() Venta = models.FloatField() Variacion_dia_anterior = models.FloatField() ClaveComparacion = models.CharField(max_length=1) def __str__(self): return '{} - {} - {}'.format(self.DivisasArgentina, self.Dia, self.ClaveComparacion) cotizaciones.html {% extends 'base.html' %} {% block contenido %} <form method="POST" class="post-form">{% csrf_token %} <div class="container"> <table class="table table-striped table-bordered" id="tab1"> <thead> <tr> <th>Divisas en el Mundo</th> <th>Valor</th> </tr> </thead> <tbody> <tr> {%for element in cotiz_mun%} <tr> {% for … -
Display records of login user related on 3 tables in Django ORM
I'm trying to display all the records of login user from NewRegistration Model on the basis of municiplaity from Profile model.Can someone help me? def get_queryset(self): # user=request.session['auth_user_id'] user=self.request.user u_id = Profile.objects.filter(id=user.id) profile_qs = Profile.objects.filter(id=u_id).values_list("user_id", flat=True) return models.NewRegistration.objects.filter(is_forwarded=False, user_id__in=profile_qs).order_by('-id') Profile Model class Registration(models.Model): fiscalyear = models.ForeignKey(system_settings.models.FiscalYear) registration_date = models.DateField() date_and_time = models.CharField(max_length=30) houseowner_name_en = models.CharField(max_length=30) houseowner_name_np = models.CharField(max_length=50) ward_no = models.ForeignKey(system_settings.models.Wardno) contactno = models.CharField(max_length=30) construction_type = models.ForeignKey(system_settings.models.ConstructionType) latitude = models.DecimalField(decimal_places=16, max_digits=30) longitude = models.DecimalField(decimal_places=16, max_digits=30) taxpayer_id = models.CharField(max_length=30, blank=True, null=True) cen = models.IntegerField() user = models.ForeignKey(User) Profile Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) designation = models.CharField(max_length=30, blank=True) department = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) municipality = models.CharField(max_length=500, blank=True)