Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Captcha wouldn't show up in my html file in Django
I was trying to implement Captcha for my contact form. I followed the instructions, Installed Django-simple-captcha. Pillow was already installed. Made migrations, added the path to urls.py and created the appropriate class in forms.py. I put captcha in the INSTALLED APPS sections in settings. My urls.py is - urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), path(r'captcha/', include('captcha.urls')), ] My views.py is - def contact_sub(request): if(request.method == 'POST'): form = CapForm(request.POST) if(form.is_valid()): x = 3 else: form = CapForm() else: form = CapForm(request.GET) if(form.is_valid()): x = 3 else: form = CapForm() txtarea = request.GET['sum_inq'] fname = request.GET['fname'] cont_list = "First Name: " + fname lname = request.GET['lname'] cont_list = cont_list + '\n\nLast Name: ' + lname email_id = request.GET['email_id'] cont_list = cont_list + '\n\nEmail Id: ' + email_id are_you = request.GET['are_you'] cont_list = cont_list + '\n\nWhich of the following most accurately describes your organization?: ' + are_you if(are_you == "Other"): specify1 = request.GET['ay_specify'] cont_list = cont_list + '\n\nSpecify: ' + specify1 cont_list = cont_list + '\n\nSummary of Inquiry:\n' + txtarea try: validate_email(email_id) send_mail('Contact Form', cont_list, settings.EMAIL_HOST_USER, ['emailaddress'], fail_silently=False) #context = {'message': "Sent"} request.session['message'] = "Sent" return HttpResponseRedirect(reverse("contact_us")) #return render(request, "contact.html", context) except ValidationError: #context = {'message': "Not Send"} request.session['message'] = "Not … -
Error When Debugging Django project with ImageFields in Visual Studio Code
I spent so long solving this problem I wanted to post it in case it helps others. I have a django project in Visual Studio Code and I configured a virtual environment for the project. I would run the project in the Integrated Terminal using manage.py runserver after activating my virtual environment and that worked. I created a debug configuration with the default launch.json for django projects. Running the debugger, I got this error: (fields.E210) Cannot use ImageField because Pillow is not installed.HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Pillow was installed in the virtual environment as well as my global python installation. -
"Post.user" must be a "User" instance
I am new to using django and I'm creating a simple webpage that takes in user input and saves it to the Model Form models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): post = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py from django import forms from .models import Post class HomeForm(forms.ModelForm): post = forms.CharField() class Meta: model = Post fields = ('post',) views.py from django.shortcuts import render, redirect # Create your views here. from django.http import HttpResponse from django.views.generic import TemplateView from .forms import HomeForm class HomeView(TemplateView): template_name = 'home.html' def get(self, request): form = HomeForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() return redirect('home.html') args = {'form': form, 'text': text} return render(request, self.template_name, args) When I run the server the webpage comes up normal but when I type in some input an error page pops up and says : ValueError at / Cannot assign ">": "Post.user" must be a "User" instance. Any Help would be appreciated! -
'DatabaseOperations' object has no attribute 'geo_db_type' error when deploying GeoDjango to Heroku
I am tryin to deploy a geodjango app to Heroku following this Tutorial but I ran into an error when I run git push heroku master and get this error in the console Using geos version: <?xml version="1.0" encoding="UTF-8"?> Fetching, caching and installing geos https://dulaccc-buildpack-geodjango.s3.amazonaws.com/heroku-18/geos-<?xml version="1.0" encoding="UTF-8"?>.tar.gz gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now When I use this link official heroku-geo buildpack and remove the buildpacks from the previous tutorial the build completes successfully but I get a "DatabaseOperations' object has no attribute 'geo_db_type" when I run heroku run python manage.py migrate on my local environment. This is my database configuration in settings.py INSTALLED_APPS = ( ..., 'django.contrib.gis', ) DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': '<dbname>', 'USER': '<dbuser>', 'PASSWORD': '<dbpassword>', 'HOST': '<dbhost>', 'PORT': '<dbport>' } } GDAL_LIBRARY_PATH = environ.get('GDAL_LIBRARY_PATH') GEOS_LIBRARY_PATH = environ.get('GEOS_LIBRARY_PATH') import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I have installed the postgis extension on the heroku postgres add-on but nothing changes. This is my first time working with geodjango and heroku and I would really appreciate any help provided. -
Django Unable to update model based on link click
I'm trying to update the model record of a file when it is downloaded from the server. I am currently using a custom tag that finds the appropriate record and changes the 'used' Boolean to True, however I now realise that this occurs when the link is rendered, not when clicked. It's pretty clear this is not the way I should be doing this, but haven't found an alternative with my searching. Any help would be greatly appreciated! profile.html {% for x in source %} {% if forloop.counter <= 4 %} <div class="content-section"> <div class="media-body"> <h2 class="account-heading">{{ x.video_id }}</h2> {% for y in records %} {% if x.video_id == y.sourcevideo.video_id %} <div class="media-body"> <video width="320" height="240" controls> <source src="{{ y.highlight.url }}" type="video/mp4"> Your browser does not support the video tag </video> <h1>{{ y.highlight_id }}</h1> <br> <a class="btn" href="{% downloaded y.highlight.url y.highlight_id %}" download>Download</a> </div> {% endif %} {% endfor %} </div> </div> {% endif %} {% endfor %} templatetags/analytics.py from django import template from highlights.models import Highlight register = template.Library() @register.simple_tag def downloaded(url, pk): e = Highlight.objects.get(highlight_id=pk) e.used = True e.save() return url From views.py class ProfileView(ListView): model = Highlight template_name = 'users/profile.html' context_object_name = 'records' ordering = ['-date_created'] @method_decorator(login_required) … -
Can not run python manage file migrate
So this is an old project trying to run it on python2 django 1, the pip install -r requirements.txt command goes all fine, but error appears when i try to run migrate on manage.py file. Successful log for requirement.txt : (comparedjs) rehman@localhost:~/projects/comparedjs/comparedjs$ pip install -r requirements.txt DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Collecting git+https://github.com/aaronsw/pytorctl.git (from -r requirements.txt (line 39)) Cloning https://github.com/aaronsw/pytorctl.git to /tmp/pip-req-build-Bo1ad2 Running command git clone -q https://github.com/aaronsw/pytorctl.git /tmp/pip-req-build-Bo1ad2 Collecting Django==1.9.7 Using cached Django-1.9.7-py2.py3-none-any.whl (6.6 MB) Collecting Fabric==1.11.1 Using cached Fabric-1.11.1-py2-none-any.whl (91 kB) Processing /home/rehman/.cache/pip/wheels/cf/7d/99/ad1cad84793c8275f7750f711eda7e49cee1d0b0a688fc30ed/GeoIP-1.3.2-cp27-cp27mu-linux_x86_64.whl Processing /home/rehman/.cache/pip/wheels/a5/99/7e/1f6d116f7c3b3364ff840c73a8c8614d96e0cf4d78c9448837/Markdown-2.6.6-py2-none-any.whl Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Collecting Pillow==3.3.0 Using cached Pillow-3.3.0-cp27-cp27mu-manylinux1_x86_64.whl (5.5 MB) Processing /home/rehman/.cache/pip/wheels/d0/25/ae/654e8f6eb25c09b1b89b06546d6508b86a8436ff1e9ef97366/Unidecode-0.4.19-py2-none-any.whl Collecting amqp==1.4.9 Using cached amqp-1.4.9-py2.py3-none-any.whl (51 kB) Collecting anyjson==0.3.3 Using cached anyjson-0.3.3.tar.gz (8.3 kB) Requirement already satisfied: argparse==1.2.1 in /usr/lib/python2.7 (from -r requirements.txt (line 10)) (1.2.1) Processing /home/rehman/.cache/pip/wheels/17/f1/b0/bc7009f7df923445ca1e6054edb996e8709d1168f486182b38/beautifulsoup4-4.2.1-py2-none-any.whl Processing /home/rehman/.cache/pip/wheels/ef/c6/94/83b5a9a5bb1351095aaf66ad105cb21f3e425917e644e8be61/billiard-3.3.0.22-cp27-cp27mu-linux_x86_64.whl Collecting celery==3.1.18 Using cached celery-3.1.18-py2.py3-none-any.whl (515 kB) Processing /home/rehman/.cache/pip/wheels/8c/d1/79/d90a9ba086c49f3f5ddd92535e9e3977aee3e27ef5cd457a23/colorama-0.2.5-py2-none-any.whl Processing /home/rehman/.cache/pip/wheels/c1/12/7a/c676d85d30d1aa17f3882dab925a777ab1f651c4072cccefd7/configobj-5.0.6-py2-none-any.whl Processing /home/rehman/.cache/pip/wheels/7d/9c/94/98f98ab004c50c86735b1c7fa8403327b579736b1a3a8ece31/django_celery-3.1.17-py2-none-any.whl Collecting django-filter==0.13.0 Using cached django_filter-0.13.0-py2.py3-none-any.whl (27 kB) Collecting django-mailchimp-v1.3==1.4.0 Using cached … -
Is it possible to get an interactive django shell using the test database?
When running tests, you can do: ./manage.py test --keepdb To run your tests, and keep the test database. Is it possible to have the django shell actually connect to it, so we can interactively access the test database the same way the Django shell can normally work with the production database? Note that the answer and its comments here imply that you can access it by doing something like: from django import test test.utils.setup_test_environment() from django.db import connection db = connection.creation.create_test_db(keepdb=True) But when I do that, my database appears to be empty when I do queries. -
Attribute error: 'list' object has no attribute 'popleft'
I have the following error: 1) Given the following python function: import requests def universal_request(httpMethod, uri, appName, payload=None): response = '' if (httpMethod is None or uri is None or appName is None): return "Paramaters are required." else: s = requests.Session() if (appName == 'myapp'): s.headers.update({ 'Authorization': REQUIRED_AUTH, 'Content-Type': 'application/json', 'Accept': 'application/json' }) else: s.headers.update({ 'Content-Type': 'application/json', 'Accept': 'application/json' }) # try catch on HTTP Methods with sessions try: if (httpMethod == 'POST'): if appName == 'myapp' and payload is not None: response = s.post( uri, data=None, #also tried assigning the payload here json=payload, verify=True, ) else: print('HTTP Method not valid') except Exception as e: print(e) return response 1) I have the following python function calling the function above import json from thefile import universal_request def prepare_json(): json_obj = { 'ID': '12345678', 'OtherId': 123, 'Code': 0, 'SomeDate': '2020-04-06', 'pdf': "None", 'hl7': "None", 'json': "None" } json_dumped = json.dumps(json_obj) return json_dumped def submit_json(): payload = prepare_json() if payload is not None: response = universal_request('POST', "somewebsite.com", "myapp", payload=payload) return response 3) When I call the function submit_json(), my code ends up in the except part of universal_request() with the error: 'list' object has no attribute 'popleft' Not sure what I am doing … -
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-xaum7z8f/supervisor/
So I'm setting up an existing project and when I am running pip install -r requirements.txt After every dependency is installed it gives this error: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-d0j9czw9/supervisor/ This is the list of complete installation (venv) rehman@localhost:~/projects/cmdj3/cmdj3$ pip install -r requirements.txt Collecting git+https://github.com/aaronsw/pytorctl.git (from -r requirements.txt (line 39)) Cloning https://github.com/aaronsw/pytorctl.git to /tmp/pip-req-build-s3aouchw Collecting Django==1.9.7 (from -r requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/e6/f9/154e1460c4a95c90ab28ead50314161ea2c4016f3561033b41f687f0a76d/Django-1.9.7-py2.py3-none-any.whl (6.6MB) 100% |████████████████████████████████| 6.6MB 102kB/s Collecting Fabric==1.11.1 (from -r requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/e5/73/49d96ea3f4e8b7b707cbfd7c78a601691ea75f479204cefe5aa459e11c2b/Fabric-1.11.1.tar.gz (215kB) 100% |████████████████████████████████| 225kB 106kB/s Collecting GeoIP==1.3.2 (from -r requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/f2/7b/a463b7c3df8ef4b9c92906da29ddc9e464d4045f00c475ad31cdb9a97aae/GeoIP-1.3.2.tar.gz Collecting Markdown==2.6.6 (from -r requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/9b/53/4492f2888408a2462fd7f364028b6c708f3ecaa52a028587d7dd729f40b4/Markdown-2.6.6.tar.gz (302kB) 100% |████████████████████████████████| 307kB 87kB/s Collecting mysqlclient (from -r requirements.txt (line 5)) Downloading https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz (85kB) 100% |████████████████████████████████| 92kB 22kB/s Collecting Pillow==3.3.0 (from -r requirements.txt (line 6)) Downloading https://files.pythonhosted.org/packages/e0/27/f61098a12f14690689924de93ffdd101463083a80bf8ff3e0c218addf05b/Pillow-3.3.0.tar.gz (10.6MB) 100% |████████████████████████████████| 10.6MB 58kB/s Collecting Unidecode==0.04.19 (from -r requirements.txt (line 7)) Downloading https://files.pythonhosted.org/packages/5a/73/053be0fafe387d41ce705585412808093f5a333aaa71cabbab641f677c11/Unidecode-0.04.19.tar.gz (204kB) 100% |████████████████████████████████| 204kB 148kB/s Collecting amqp==1.4.9 (from -r requirements.txt (line 8)) Downloading https://files.pythonhosted.org/packages/ed/09/314d2788aba0aa91f2578071a6484f87a615172a98c309c2aad3433da90b/amqp-1.4.9-py2.py3-none-any.whl (51kB) 100% |████████████████████████████████| 61kB 62kB/s Collecting anyjson==0.3.3 (from -r requirements.txt (line 9)) Downloading https://files.pythonhosted.org/packages/c3/4d/d4089e1a3dd25b46bebdb55a992b0797cff657b4477bc32ce28038fdecbc/anyjson-0.3.3.tar.gz Collecting argparse==1.2.1 (from -r requirements.txt (line 10)) Downloading https://files.pythonhosted.org/packages/6f/ad/86448942ad49c5fe05bfdf7ebc874807f521dfcca5ee543afaca2974ad5a/argparse-1.2.1.tar.gz (69kB) 100% |████████████████████████████████| 71kB 114kB/s Collecting beautifulsoup4==4.2.1 (from -r requirements.txt (line 11)) Downloading https://files.pythonhosted.org/packages/df/b8/30ea521e7a852202445b30660df5981b94acfeccda15d2bc5a03d97b500a/beautifulsoup4-4.2.1.tar.gz (64kB) … -
Get many to many fields changes in a post save in Django 1.11
So, I have a post_save signal in my code to save logs of changes in models, but the changes in many to many fields aren't applied at the point post_save is triggered, so changes in m2m fields aren't saved in my logs. My code (you can pretty much ignore the code inside the method): def save_log(sender, instance, created, raw, update_fields, **kwargs): if ( not hasattr(sender, '_meta') or sender._meta.label not in settings.MODELS_TO_BE_LOGGED ): return sensitive_fields = ['password', ] user = get_user() # This creates the log with a json describing the changes if created: # This method creates a log instance.save_addition(user, '') else: changed_field_labels = {} original_dict = instance.original_dict actual_dict = instance.to_dict( exclude=['created_at', 'updated_at', 'original_dict', 'id'], ) change = False for key in set(list(actual_dict.keys()) + list(original_dict.keys())): if original_dict.get(key) != actual_dict.get(key): change = True if key == sensitive_fields: changed_field_labels[key] = {'change': 'field updated'} else: changed_field_labels[key] = { 'from': original_dict.get(key, '-'), 'to': actual_dict.get(key, '-'), } if change: json_message = json.dumps( {'changed': {'fields': changed_field_labels}}, cls=ModelEncoder ) # This method creates a log instance.save_edition(user, json_message) For example, consider a model Event that has a many to many field to EventCategory called categories. If changes were made to an event through an UpdateView, for example (including … -
Using Django how can I render in a recursive python function before each return?
I am stuck on this. A function runs recursively changing objects each time. I want to render a updated view before every return. How can I render the template on every step of the python function recursive call? Or how can I approach this problem? Here is my function below: def solveBoard(box, board, size): if box.isFinalValue: newY = box.y newX = box.x + 1 if newX >= size: newX = 0 newY = newY + 1 if newY >= size: return True if solveBoard(board[newY][newX], board, size): return True return False else: allPossibleValues = getAllPossibleValues(box, board, 9) if not allPossibleValues: return False else: for i in allPossibleValues: board[box.y][box.x].numValue = i board[box.y][box.x].isEmpty = False newY = box.y newX = box.x + 1 if newX >= size: newX = 0 newY = newY + 1 if newY >= size: return True if solveBoard(board[newY][newX], board, size): return True board[box.y][box.x].numValue = 0 board[box.y][box.x].isEmpty = True return False -
least memory comsuming way of saving large python data into DB
I have to save a significantly large python data into the a mysql database which consists of lists and dictionaries (0.4MB) but I get memory exception during the save operation. I have already benchmarked the saving operation and also tried different ways of dumping the data, including binary format but all methods seemed to consume a lot of memory. Benchmarks below: PYTHON DATA SIZE: 0.4MB MAX MEMORY USAGE DURING JSON SAVE: 966.83MB SIZE AFTER DUMPING json: 81.03 MB pickle: 66.79 MB msgpack: 33.83 MB COMPRESSION TIME: json: 5.12s pickle: 11.17s msgpack: 0.27s DECOMPRESSION TIME: json: 2.57s pickle: 1.66s msgpack: 0.52s COMPRESSION MAX MEMORY USAGE: json dumping: 840.84MB pickle: 1373.30MB msgpack: 732.67MB DECOMPRESSION MAX MEMORY USAGE: json: 921.41MB pickle: 1481.25MB msgpack: 1006.12MB msgpack seems to be the most performant library but the decompression takes up a lot of memory too. I also tried hickle which is said to consume little memory but the final size ended up being 800MB. Does anyone have a suggestion? Should I just increase the memory limit? can mongodb handle the save operation with less memory? -
Ordering search results by date in Django
I'm trying to order the results of my search by the publication date, where the filter offers two choices: Order by lastest first or the most recent first. This is the filter that I've created so far to do that: filters.py class PubFilters(django_filters.FilterSet): CHOICES = ( ('Fecha', 'Más reciente'), ('Fecha', 'Menos reciente' ) ) ordering = django_filters.ChoiceFilter(label="Ordenar por", choices=CHOICES) class Meta: model = publicaciones fields = ['Precio', 'Categoría'] However, this returns "Cannot resolve keyword 'ordering' into field". And worse: Because I replaced the results for the filtered results (as you can see below), my pagination is suddenly broken, I can see the numbers but paginate_by isn't working. views.py class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 2 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MyFilter = PubFilters(self.request.GET, queryset=self.get_queryset()) context['filter'] = MyFilter context['filtered_items'] = MyFilter.qs context['count'] = self.get_queryset().count() context['búsqueda'] = self.request.GET.get('q') return context def get_queryset(self): qs = self.model.objects.all().order_by('id') search = self.request.GET.get('q') if search: qs = qs.filter(Título__icontains=search) return qs How could I show the filter for "ordering date" correctly? Thanks in advance! -
Django - Account Settings BooleanField
I reviewed most of the posts here related to Django and BooleanField update, but I couldn't find any related to my problem solution. I have a custom user models.py: # Own custom user model class Account(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) guardianSource = models.BooleanField(default=True) bbcSource = models.BooleanField(default=False) independentSource = models.BooleanField(default=False) categoryCoronaVirus = models.BooleanField(default=False) categoryPolitics = models.BooleanField(default=False) categorySport = models.BooleanField(default=False) When I register a user it seems to register in the database all correct values for the checkboxes. The problem is when I want to edit user information I cannot see if a checkbox was checked on registering or not, it displays the checkboxes itself, but they are all empty (False). However, it correctly requests the username and displays it so I can edit it, but all the checkboxes are unchecked. views.py: def account_view(request): if not request.user.is_authenticated: return redirect('login') context = {} if request.POST: form = AccountUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() context['success_message'] = "Updated" else: # Display the saved user details from database form = AccountUpdateForm( initial = { 'username':request.user.username, "guardianSource": request.user.guardianSource, "bbcSource": request.user.bbcSource, "independentSource": request.user.independentSource, "categoryCoronaVirus": request.user.categoryCoronaVirus, "categoryPolitics": request.user.categoryPolitics, "categorySport": request.user.categorySport, }) context['account_form'] = form return render(request, 'accounts/account.html', context) account html: {% extends 'base.html' %} {% block content %} <form class="form-signin" … -
Unable to push my django app to heroku due to requirements
So I'm trying to deploy my Django app to heroku (using their tutorial) and I get the following error Terminal info: diaj3@diaj3-TUF-Gaming-FX505DD-FX505DD:~/Desktop/direct_bet$ git push heroku master Counting objects: 9177, done. Delta compression using up to 8 threads. Compressing objects: 100% (5988/5988), done. Writing objects: 100% (9177/9177), 20.59 MiB | 1.29 MiB/s, done. Total 9177 (delta 2148), reused 9177 (delta 2148) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory remote: -----> Installing python-3.6.10 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: Sqlite3 successfully installed. remote: -----> Installing requirements with pip remote: ERROR: Could not find a version that satisfies the requirement apt-clone==0.2.1 (from -r /tmp/build_ca7b1fda063f2c983e5082dbb19235bf/requirements.txt (line 1)) (from versions: none) remote: ERROR: No matching distribution found for apt-clone==0.2.1 (from -r /tmp/build_ca7b1fda063f2c983e5082dbb19235bf/requirements.txt (line 1)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to protected-chamber-65006. remote: To https://git.heroku.com/protected-chamber-65006.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/protected-chamber-65006.git' Here's the Tree info Even tho the requirements file is there, I still get the … -
Double ForeignKey Relation between Models Django
I'm a little confuse here: class MyBirthday(Model): date = models.DateTimeField() invitations_quantity = models.IntegerField() message = models.CharField(max_length=500) user = models.ForeignKey(User) location = models.OneToOneField(Location) class Attendant(Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday_id = models.ForeignKey(MyBirthday) The thing is whether or whether not to use the user attribute in MyBirthday model, I mean, is it okay if I just left the Attendant attribute 'birthday_id' reference it? -
in django delete a column in sqlite3 when the time exceeds
In django is there a way to save mobile.no,otp and created_time to DB and let DB remove column when the time created_time is more than 10sec. (like time to live) -
Django 'str' object has no attribute 'username' in forms.py
I'm trying to save the data on to a model. What i have done is created models and forms when i try to submit the form i'm getting an error below 'str' object has no attribute 'username' My model models.py from django.db import models from django.contrib.auth.models import User class Group(models.Model): group_name = models.CharField('Group name', max_length=50) group_admin = models.ForeignKey(User, on_delete=models.CASCADE) is_admin = models.BooleanField(default=False) created_on = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.group_name class GroupMembers(models.Model): group_name = models.ForeignKey(Group,on_delete=models.CASCADE) members = models.ForeignKey(User, on_delete=models.CASCADE) def __unicode__(self): return self.members class Transactions(models.Model): bill_type = models.CharField('Bill type',max_length=200) added_by = models.ForeignKey(User, on_delete=models.CASCADE) added_to = models.ForeignKey(Group, on_delete=models.CASCADE) purchase_date = models.DateField(auto_now=True) share_with = models.CharField('Share among', max_length=250) amount = models.IntegerField(default=0) def __str__(self): return self.bill_type forms.py from django import forms from .models import Transactions, GroupMembers class Bill_CreateForm(forms.ModelForm): def __init__(self, user_list, *args, **kwargs): print("Came here ", user_list) if len(user_list)>0: super(Bill_CreateForm, self).__init__(*args, **kwargs) self.fields['share_with'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.username.capitalize()) for name in user_list])) #share_with = forms.ModelMultipleChoiceField(queryset=GroupMembers.objects.get(group_header=),widget=forms.CheckboxSelectMultiple) class Meta: model = Transactions fields = ( 'bill_type', 'amount', 'share_with' ) views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from .models import Transactions, GroupMembers, Group from .forms import Bill_CreateForm from django.http import HttpResponse, HttpResponseRedirect # Create your views here. def add_bills_home(request, id=None): user = User.objects.get(id=id) grp = GroupMembers.objects.get(members=user) … -
Graphene always returning "none" in Json
Im fairly new to GraphQL and Graphene so it's hard for me to grasp whats wrong with my code. I can't even succeed with the simplest of the examples with GraphQL. Here is my code: models.py class Task(models.Model): task_name = models.CharField('Aufgabe', max_length=255) project = models.ForeignKey(Project, on_delete=models.CASCADE) done = models.BooleanField(verbose_name="Erledigt", default=False) def __str__(self): return self.task_name schema.py class Task(models.Model): task_name = models.CharField('Aufgabe', max_length=255) project = models.ForeignKey(Project, on_delete=models.CASCADE) done = models.BooleanField(verbose_name="Erledigt", default=False) def __str__(self): return self.task_name My Query in the same file: class TaskQuery(graphene.ObjectType): all_tasks = graphene.List(TaskType) def resolve_all_tasks(self, info, **kwargs): return Task.objects.all() Another Queryfunction: class Query(graphene.ObjectType): tasks = TaskQuery.all_tasks projects = ProjectQuery.all_projects This is my schema.py int the settings directory: import graphene from todo import schema class Query(schema.Query): pass class Mutation(schema.Mutation): pass schema = graphene.Schema(query=Query, mutation=Mutation) When opening GraphiQL I can see the Query in the docs, but when I try to use this query like so (for example): query { tasks{ id taskName done } } it always returns this: { "data": { "tasks": null } } Although I am pretty sure that I have entries in my Database that should be displayed there. I have checked the beginners Tutorial a view times and I can't even pass the first hurdle. … -
Ngnix in docker container 500 interlal error
I encounter this issue with nginx and docker: I have two containers, one for my django webapp and another for nginx, i want to nginx container get the browser requests and redirect to my django app, but i keep getting 500 internal error 500 error i follow this tutorial but cant make it nginx config file docker-compose -
Using sass with django, sass_tags not found
I am trying to use sass with django. I followed a tutorial and carried out the following steps; i.) i installed the Django Sass libraries pip install libsass django-compressor django-sass-processor ii.) made the necessary changes to my settings.py file: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'crispy_forms', 'classroom', 'sass_processor', ] ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] SASS_PROCESSOR_ROOT = os.path.join(BASE_DIR, 'static') iii.) and my html {% load static %} [% load sass_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <link href="{% sass_src 'second/css/app/quiz_control.scss' %}" rel="stylesheet" type="text/css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'second/js/app/quiz_control.js' %}" defer></script> </head> However, when I run my project i get the error message: Invalid block tag on line 9: 'sass_src'. Did you forget to register or load this tag? -
How Can I send json file by ajax to django?
Can I send .json with data like (login,password from input html) to django who download this file and check login/password? Then I want return results by django to js,jquery. I dont wan use forms-django in form-html and dont want change urls. code html: <form id='login_form' action="" method="POST"> {% csrf_token %} <div id='Login_form'> <p>Login: </p> <input type="text" onblur="CheckEmptyElements();" id="flogin"> <p>Password: </p> <input type="password" onblur="CheckEmptyElements();" id="lpass"> <div id="butt_form"> <button type="button" class="butt_forme" id="button" onclick="CheckBeforeSend();">Enter</button> </div> </div> </form> code js: var LoginInput = document.getElementById('flogin'); if(LoginInput.value.match(/^[a-zA-Z]+['.']+[a-zA-Z]+[0-9]+$/) == null) { if(document.getElementById('Windows').childElementCount > 2) { document.getElementById('Windows').children[0].remove(); } AddPicture("paperJsConn"); } else // <--- Check login/pass in base django { document.getElementById("button").type = "submit"; $.ajax({ type:"POST", url: '', data: { "login": "password": }, success: function(response){ //animation and change site if correct login/pass or reloaded site. } }); } and views.py: def Logget(request): if request.is_ajax and request.method == "POST": //take login from json and check in base by loop //if find check password if: // correct // return .json or message that is correct. else: // return .json or message that is not correct. return render(request, 'index.html') Someone help please? -
Django Template not rendering {{ }}
I'm not sure where I've gone wrong, but my template is not rendering. I believe I have set all the correct code in the following Python files, but I do not see it rendering. I am using postgresql if that matters: urls.py: from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), path('', jobs.views.home, name='home') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py: INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'jobs.apps.JobsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] views.py from django.shortcuts import render from .models import Job def home(request): jobs = Job.objects return render(request, 'jobs/home.html', {'jobs': jobs}) models.py: from django.db import models class Job(models.Model): image = models.ImageField(upload_to = 'images/') summary = models.CharField(max_length = 200) jobs/templates/jobs/home.html: <div class="album py-5 bg-light"> <div class="container"> <div class="row"> {% for i in jobs.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img src="" alt=""> <div class="card-body"> <p class="card-text">{{ jobs.summary }}test</p> </div> </div> </div> {% endfor %} </div> </div> </div> -
Django: delete object with a button
In my website in the user page I've got a list of all the items he added to the database. Next to the items there's a delete button. I'd like the user to be able to delete that item through the button.Thanks a lot! models.py class Info(models.Model): utente = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) band = models.CharField(max_length=200) disco = models.CharField(max_length=200) etichetta_p = models.CharField(max_length=200) etichetta_d = models.CharField(max_length=200) matrice = models.CharField(max_length=200) anno = models.PositiveIntegerField(default=0) cover = models.ImageField(upload_to='images/', blank=True) view.py (I'm not sure about this part) def DeleteInfo(request, id=None): instance = get_object_or_404(Info, id=id) instance.delete() return redirect ('search:user') urls.py path('<int:id>/delete', views.DeleteInfo, name='delete'), html template: {% if object_list %} {% for o in object_list %} <div class="container_band"> <div class=album_band> <!-- insert an image --> {%if o.cover%} <img src= "{{o.cover.url}}" width="100%"> {%endif%} </div> <div class="info_band"> <!-- insert table info --> <table> <tr><th><h3>{{o.band}}</h3></th></tr> <tr><td> Anno: </td><td> {{o.anno}} </td></tr> <tr><td> Disco: </td><td> {{o.disco}} </td></tr> <tr><td> Etichetta: </td><td> {{o.etichetta_d}} </td></tr> <tr><td> Matrice: </td><td> {{o.matrice}} </td></tr> </table> </div> <div class="mod"> <table> <tr><td><button> Update </button></td></tr> <tr><td><button> Delete </button></td></tr> </table> </div> </div> {% endfor %} {%endif%} </div> -
Question objects need to have a primary key value before you can access their tags
i am trying to save both FK data as well as tags into same model. FK is the user. user has to submit the question and tags like stack overflow. but i am not able to save both of them. it looks some issue at my views. Can you please help. ValueError at /qanda/askquestion/ Question objects need to have a primary key value before you can access their tags. Request Method: POST Request URL: http://127.0.0.1:8000/qanda/askquestion/ Django Version: 2.2.4 Exception Type: ValueError Exception Value: Question objects need to have a primary key value before you can access their tags. Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/taggit/managers.py in get, line 424 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 Python Version: 3.7.4 Python Path: ['/Users/SRIRAMAPADMAPRABHA/Desktop/IampythonDEV/iampython', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/SRIRAMAPADMAPRABHA/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question_number = models.AutoField(primary_key=True) question_category=models.ForeignKey(Question_Category,related_name='questioncategory',on_delete=models.CASCADE) question_title=models.CharField(max_length=250) question_slug = models.SlugField(unique=True, max_length=250) question_description=RichTextField() question_tags = TaggableManager() question_posted_at=models.DateTimeField(default=datetime.now,blank=True) question_status= models.IntegerField(choices=STATUS, default=1) question_updated_on= models.DateTimeField(auto_now= True) def __str__(self): return self.question_title views.py @login_required def createQuestion(request): if request.method == 'POST': form = QuestionAskForm(request.POST) if form.is_valid(): new_question=form.save(commit=False) question_title = request.POST['question_title'] new_question.slug = slugify(new_question.question_title) new_question=request.user new_question.save() form.save_m2m() messages.success(request,'You question is succesfully submitted to the forum') return redirect('feed') else: form = QuestionAskForm() return render(request,'qanda/askyourquestion.html',{'form':form}) I want to submit both foreign key and as well as …